Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Owner turns in a group chat get the whole answer, marked with what the room could read
garrytan1427457b7144
diff --git a/behavior-changes.d/owner_room_marks_gst2639.md b/behavior-changes.d/owner_room_marks_gst2639.mdnew file mode 100644index 0000000000..71364009e5--- /dev/null+++ b/behavior-changes.d/owner_room_marks_gst2639.md@@ -0,0 +1 @@+A harness can now declare the group chat an answer goes into (the X-Gbrain-Room header, request-level _meta.room, or a room tool argument once whoami shows features.room). The caller's read is unchanged; every page and fact in the answer is marked room_access with whether the people in that chat could have read it, and the room_above_level notice tells the agent to keep those items out of the reply. A call with no room is unaffected. With mcp.strict_params set to reject, every tool schema now also declares the optional room argument. See docs/guides/rooms.md.diff --git a/changelog.d/gbra498-owner-room-marks.md b/changelog.d/gbra498-owner-room-marks.mdnew file mode 100644index 0000000000..e23824e8b0--- /dev/null+++ b/changelog.d/gbra498-owner-room-marks.md@@ -0,0 +1,11 @@+### The owner can ask a shared agent in a group chat and still get the whole answer++**A harness can now tell gbrain which group chat an answer goes into, and gbrain marks every page and fact with whether the people in that chat could have read it.** The owner of a brain who asks their agent something in a team chat should get the same work as in a direct message, but the agent also needs to know what not to repeat in front of the room. Declaring the room does exactly that and nothing more: the read is never refused, shortened, reordered or failed because of it, and a call with no room returns what it always did.++- Declare the room with the `X-Gbrain-Room` header (`gbrain serve --http`) or request-level `_meta.room`; a harness that can set neither may pass a `room` tool argument once `whoami` shows `features.room: true`. Entries are member ids, `group:<id>` or `guest`.+- Each item in `get_page`, `search`, `query`, `list_pages`, `find_pages`, `get_chunks`, `get_timeline`, `get_backlinks`, `recall` and `entity` answers, and each hot-memory fact, carries `room_access`: `{readable: true}`, `{readable: false, reason}` (`readers`, `folder_rule`, `labelled_only`, `private_label`, `derived`) or `{readable: "unknown", reason}`. `_meta.room` sums it up.+- The `room_above_level` notice tells the model to use those items for the work, keep them out of the reply unless the ask needs them and offer them in a direct message. `room_hints_unavailable` says when the room could not be judged (every item is then marked unknown), and `room_conflict` says when a `room` argument disagreed with the harness; an argument can only add people.+- The owner's own credential needs no `may_act_for` to declare a room, because a room only adds marks; any other member's credential needs `may_act_for` covering the room. Each marked call writes a count-only `room_marked` row to the audience audit log.+- No setting, no migration, and it works the same on a repo-less brain. Guide: [docs/guides/rooms.md](docs/guides/rooms.md).++<!-- behavior-change: owner_room_marks_gst2639 -->diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex 77be8f694e..7cd083ff8b 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -3,7 +3,7 @@[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 `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal; a binding lookup that fails never reads as unbound: a statement error throws `access_identity_unavailable` (retryable, `fix.next: wait`), a transient failure (`transientDatabaseFailure`, `transientInterruption` in `persistence/transient-retry.ts`) or a non-statement failure is rethrown unchanged for the persistence consumer, and only a schema missing `access_members`, `access_group_members` or `member_id` reads as unbound). 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`). GST-2490: an owner read (`CallerAccess.lineage` with `owner`, read-only ops only) uses `lineageAccessSql`: the owner's readers and folder rules as for any member, with `gbrain_access_origin_hidden_for()` (v304; per origin `gbrain_access_origin_closed_for()`) in place of the every-caller lineage, so a derivative or fact passes when the owner reads every origin; `ownerReadsRestricted` (config `access.owner_reads_restricted`, `owner.ts` `setOwnerReadsRestricted`, local only) also passes pages kept to other members except another member's own member page and pending coverage. `access check`, `who-can-read`, `whoami` (`ownerReadsRestrictedNotice`) and doctor `access_owner_reads_restricted` report it; test `test/owner-reads-restricted.test.ts` (both engines, database and access.yml rules). GBRA-108 (migration v305, `v305-access-lineage-designs.ts`): `access_rules.covers_derived` (default true) — a raw-only rule (`folder-rules.ts` `covers_derived: false`, `rule add --raw-only`; digest unchanged for covering rules; true→false is the held widening `derived_released`, false→true the narrowing `derived_covered`) is dropped from an origin's rule set by the SQL function `gbrain_access_lineage_rules()` inside `gbrain_access_origin_restricted()` and the 10-argument `gbrain_access_origin_closed_for()`, so it keeps its pages but not their lineage (a page's own readers still close it; fact provenance filters judge with `derived = true`). `access_members.kind` (`person` | `audience`, `members.ts` `setMemberKind`, local only): an owner read carries `CallerAccess.audienceKindMembers`, whose member pages pass the readers test and the member-page exemptions (`audiencePages`, `notOtherMemberPageSql`, the `p_audience_pages` argument of the 9-argument `gbrain_access_origin_hidden_for()`). Config `access.members_read_lineage` (`lineage.ts`, local only) sets `CallerAccess.lineage` for any member read speaking for itself (`caller.ts`; never an audience of several or an unbound credential; `withCallerAccess` drops it for several identities and keeps the owner opt-in and audience members owner-only). Cache keys: `knobsHash` `xol=3` and `xak=`, `callerIdentityKey` `owner_reads`/`audience_kind`. Doctor `access_lineage` (`checks/access-lineage.ts`). Tests: `test/access-raw-only-rules.test.ts`, `test/access-audience-members.test.ts`, `test/access-members-read-lineage.test.ts` (both engines, both stores; fixture `test/helpers/access-lineage-fixture.ts`). GBRA-108 design 1 (the labelled-only migration, `schema-migrations/v*-access-labelled-only.ts`): `access_members.labelled_only` (`labelled-only.ts` `setMemberLabelledOnly`, local only, refused on the owner with `access_labelled_only_owner` from `owner.ts`, which `setOwner` also raises) sets `CallerAccess.labelledOnly` (`caller.ts`, `actor.ts`, `as-preview.ts`; fails closed to true when the table cannot be read). `private-visibility.ts` `labelledOnlySql` ANDs `page_readers && identity OR folder_rule_ids && satisfied` into `callerAccessSql`, `callerReadersAllowedSql` (a snapshot needs its own readers or a rule on the live page) and the fact filters (`labelledOnlyFactSql`: a fact on the caller's own member page while it names the member, or under member lineage a provenance page that passes; else FALSE); under member lineage a derived row may pass through `gbrain_access_origin_labelled_for()` (every origin labelled, none missing). Remote read gates that are not caller-aware use `remoteReadFloorSql` / `remoteProvenanceFloorSql` (the plain fragment, plus the labelled-only conjunct only for a labelled-only caller); `test/remote-read-floor.test.ts` lists the sites that keep the plain fragment. `labelledOnlyFor` never reports the configured owner, and dispatch refuses a scope read for a labelled-only person (`scope-read.ts` `scopeReadLabelledOnlyRefused`). The entity page of a fact is judged by the ordinary policy. Writes: `persistence/page-visibility.ts` (`writerReadPolicySql`, `remoteLabelsChecked` → `assertLabelledOnlyCreate` → `access_labelled_only_unnamed`), `cli/enforced-member.ts` `memberPageView`. Cache keys `xlo=1`, `labelled_only`; doctor `access_labelled_only_members` (`checks/access-labelled-only.ts`). Test: `test/access-labelled-only.test.ts` (both engines, both storesA derivative of a page that names readers is otherwise 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 (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); 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` (v298, `--attest-read`; over HTTP `attestRead` on `/admin/api/access/attest`) is `person`, and handlers read the mode with `currentReadMode`. GST-2407: `context_pack` is a scope read too: its `entity_refs` count as naming sources, `assertPackConfined` refuses before any read a scope call without `source_id`, with an `entity_refs` entry in another source or with `session_id`, and the handler reads the named source as home (core block, pull brief, hot facts). `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`, v299; `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`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. GST-2346 D1: the owner speaking for itself (`ownerSpeaksForItself`: `CallerAccess.owner`, no actor or audience, no subagent, no slug fence) takes the world route unless it passes `visibility: "private"` or the page or `facts.default_visibility` makes the default private (then its member page), is never refused `member_share_required`, and its `forget` of a fact off its member page takes the ordinary remote path when that path reads the fact. A fact off every member and scope page, on a page the owner reads under the GST-2490 rule with the opt-in off (`ownerReadPolicyFragment`) and may write as a member, a page whose readers name it included, with the fact's entity page judged the same way (`ownerReachesFact`, `forget-prepare.ts`), is withdrawn too: submission marks the request `owner_reach`, and preparation judges the owner again from the stored authority (`storedOwnerSpeaksForItself`, `page-visibility.ts`), so a writer that is no longer the owner gets `not_found`; a more trusted fact files the `forget_requires_owner` proposal. 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`); a remote save there meets only the page's own withdrawals and those of a claim its member reads (`memberPageWithdrawal`), and the insert guards mark a member-page row only by its page's own withdrawals (`schema-migrations/*-member-page-withdrawal-scope.ts`), so a claim the member never read cannot refuse or expire its save; 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`) on the stored actor, else the stored audience, 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) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. 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 `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal; a binding lookup that fails never reads as unbound: a statement error throws `access_identity_unavailable` (retryable, `fix.next: wait`), a transient failure (`transientDatabaseFailure`, `transientInterruption` in `persistence/transient-retry.ts`) or a non-statement failure is rethrown unchanged for the persistence consumer, and only a schema missing `access_members`, `access_group_members` or `member_id` reads as unbound). 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`). GST-2490: an owner read (`CallerAccess.lineage` with `owner`, read-only ops only) uses `lineageAccessSql`: the owner's readers and folder rules as for any member, with `gbrain_access_origin_hidden_for()` (v304; per origin `gbrain_access_origin_closed_for()`) in place of the every-caller lineage, so a derivative or fact passes when the owner reads every origin; `ownerReadsRestricted` (config `access.owner_reads_restricted`, `owner.ts` `setOwnerReadsRestricted`, local only) also passes pages kept to other members except another member's own member page and pending coverage. `access check`, `who-can-read`, `whoami` (`ownerReadsRestrictedNotice`) and doctor `access_owner_reads_restricted` report it; test `test/owner-reads-restricted.test.ts` (both engines, database and access.yml rules). GBRA-108 (migration v305, `v305-access-lineage-designs.ts`): `access_rules.covers_derived` (default true) — a raw-only rule (`folder-rules.ts` `covers_derived: false`, `rule add --raw-only`; digest unchanged for covering rules; true→false is the held widening `derived_released`, false→true the narrowing `derived_covered`) is dropped from an origin's rule set by the SQL function `gbrain_access_lineage_rules()` inside `gbrain_access_origin_restricted()` and the 10-argument `gbrain_access_origin_closed_for()`, so it keeps its pages but not their lineage (a page's own readers still close it; fact provenance filters judge with `derived = true`). `access_members.kind` (`person` | `audience`, `members.ts` `setMemberKind`, local only): an owner read carries `CallerAccess.audienceKindMembers`, whose member pages pass the readers test and the member-page exemptions (`audiencePages`, `notOtherMemberPageSql`, the `p_audience_pages` argument of the 9-argument `gbrain_access_origin_hidden_for()`). Config `access.members_read_lineage` (`lineage.ts`, local only) sets `CallerAccess.lineage` for any member read speaking for itself (`caller.ts`; never an audience of several or an unbound credential; `withCallerAccess` drops it for several identities and keeps the owner opt-in and audience members owner-only). Cache keys: `knobsHash` `xol=3` and `xak=`, `callerIdentityKey` `owner_reads`/`audience_kind`. Doctor `access_lineage` (`checks/access-lineage.ts`). Tests: `test/access-raw-only-rules.test.ts`, `test/access-audience-members.test.ts`, `test/access-members-read-lineage.test.ts` (both engines, both stores; fixture `test/helpers/access-lineage-fixture.ts`). GBRA-108 design 1 (the labelled-only migration, `schema-migrations/v*-access-labelled-only.ts`): `access_members.labelled_only` (`labelled-only.ts` `setMemberLabelledOnly`, local only, refused on the owner with `access_labelled_only_owner` from `owner.ts`, which `setOwner` also raises) sets `CallerAccess.labelledOnly` (`caller.ts`, `actor.ts`, `as-preview.ts`; fails closed to true when the table cannot be read). `private-visibility.ts` `labelledOnlySql` ANDs `page_readers && identity OR folder_rule_ids && satisfied` into `callerAccessSql`, `callerReadersAllowedSql` (a snapshot needs its own readers or a rule on the live page) and the fact filters (`labelledOnlyFactSql`: a fact on the caller's own member page while it names the member, or under member lineage a provenance page that passes; else FALSE); under member lineage a derived row may pass through `gbrain_access_origin_labelled_for()` (every origin labelled, none missing). Remote read gates that are not caller-aware use `remoteReadFloorSql` / `remoteProvenanceFloorSql` (the plain fragment, plus the labelled-only conjunct only for a labelled-only caller); `test/remote-read-floor.test.ts` lists the sites that keep the plain fragment. `labelledOnlyFor` never reports the configured owner, and dispatch refuses a scope read for a labelled-only person (`scope-read.ts` `scopeReadLabelledOnlyRefused`). The entity page of a fact is judged by the ordinary policy. Writes: `persistence/page-visibility.ts` (`writerReadPolicySql`, `remoteLabelsChecked` → `assertLabelledOnlyCreate` → `access_labelled_only_unnamed`), `cli/enforced-member.ts` `memberPageView`. Cache keys `xlo=1`, `labelled_only`; doctor `access_labelled_only_members` (`checks/access-labelled-only.ts`). Test: `test/access-labelled-only.test.ts` (both engines, both storesA derivative of a page that names readers is otherwise 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 (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); 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`. Rooms (GST-2639): `room.ts` reads the shared chat an answer goes into (`readRoomDeclaration`: the `X-Gbrain-Room` header, request-level `_meta.room` and a `room` tool argument, which is stripped before the handler; the argument can only add people, a disagreement sets `conflict`; an empty or malformed channel is `invalid`, never a refusal) and `assessRoom` marks a copy of a covered op's result (`ROOM_COVERED_OPS`) plus hot memory with `room_access`: pages through `privatePagesFilterForCaller` under the room's caller-access record (`audienceCallerAccess`, the audience branch of `remoteCallerAccess`), facts through `factVisibilitySql` and `privateProvenanceFilterUnderPolicy`, with reasons `readers`, `folder_rule`, `labelled_only`, `private_label`, `derived`. It never throws, never narrows, reorders or fails the read (a failure, the 3 s deadline, more than 2,000 references or an uncovered op leave the body unchanged and mark items unknown), writes `_meta.room` and the notices `room_above_level`, `room_hints_unavailable`, `room_conflict`, and appends a count-only `room_marked` audit row. `resolveAudienceIdentities` takes `mayActFor: 'owner_room_assessment'` to skip `may_act_for` for the owner's room only. Dispatch ignores a room on a trusted local call. Test: `test/access-room.test.ts` (both engines, repo-less). 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` (v298, `--attest-read`; over HTTP `attestRead` on `/admin/api/access/attest`) is `person`, and handlers read the mode with `currentReadMode`. GST-2407: `context_pack` is a scope read too: its `entity_refs` count as naming sources, `assertPackConfined` refuses before any read a scope call without `source_id`, with an `entity_refs` entry in another source or with `session_id`, and the handler reads the named source as home (core block, pull brief, hot facts). `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`, v299; `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`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. GST-2346 D1: the owner speaking for itself (`ownerSpeaksForItself`: `CallerAccess.owner`, no actor or audience, no subagent, no slug fence) takes the world route unless it passes `visibility: "private"` or the page or `facts.default_visibility` makes the default private (then its member page), is never refused `member_share_required`, and its `forget` of a fact off its member page takes the ordinary remote path when that path reads the fact. A fact off every member and scope page, on a page the owner reads under the GST-2490 rule with the opt-in off (`ownerReadPolicyFragment`) and may write as a member, a page whose readers name it included, with the fact's entity page judged the same way (`ownerReachesFact`, `forget-prepare.ts`), is withdrawn too: submission marks the request `owner_reach`, and preparation judges the owner again from the stored authority (`storedOwnerSpeaksForItself`, `page-visibility.ts`), so a writer that is no longer the owner gets `not_found`; a more trusted fact files the `forget_requires_owner` proposal. 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`); a remote save there meets only the page's own withdrawals and those of a claim its member reads (`memberPageWithdrawal`), and the insert guards mark a member-page row only by its page's own withdrawals (`schema-migrations/*-member-page-withdrawal-scope.ts`), so a claim the member never read cannot refuse or expire its save; 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`) on the stored actor, else the stored audience, 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) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. 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/open-twins.ts` (GST-2603) — `openTwins(engine, pages, readers, cover)`: for the pages a label or rule preview changes, the live pages with the same slug in other sources that are not private by their own labels (`privateSnapshotFilterFragment`; no links are read) and that the empty identity or an enabled member outside `readers` passes by its own readers and folder rules (`readersAllowedSql`, `folderRulesAllowedSql` with `folderAccessFor`), since labels and rules apply per source. Read-only and bounded (`OPEN_TWINS_PAGES` 1000 pages checked, `OPEN_TWINS_LISTED` 50 named, `count` over all); never part of a preview hash. Callers: `repair/visibility.ts` (pages turning private, owner inside), `repair/readers.ts` (`--readers`), `repair/private-labels.ts` (`--class restore`) and `commands/access-rules.ts` `previewRules` (each narrowed rule's pages); `cover(source, slugs)` names the same repair or rule with `--source <other>`. Test: `test/label-repair-derived-stamps-gst2603.test.ts`.- `src/core/access/federation-exposure.ts` (#8982) — `remotePagesFederationExposes(engine, source)`: the live pages of a source that name no readers and no folder rule, that the read paths' privacy rules (`privacyPartSql`) do not hide from a no-grant connection (#9068; skipped when `remotePrivacyRelaxed` says an operator opted out), and whose live revision (`pages.revision_principal_*`) or any version (`page_versions.write_principal_*`) a token or OAuth client wrote (revoked or deleted included; no record keeps a credential's member at write time, so an unbound, rebound or deleted one counts and each example names its member now; a tag change moves the revision attribution without a version, hiding the earlier author): count, the first five slugs, and shell-quoted `who-can-read` / `access rule add` commands. `remotePagesFederationExposesOrWarn` runs it, after the change commits, only for a change that added the source to the no-grant floor (federate reads the prior state under the source row lock), and turns a failed read into a stderr warning, so the caller's federation never changes. Read by `sources federate`, the unmanaged `sources restore` (stderr; `--json` as `pages_exposed`) and the managed `source_lifecycle` restore result. Pinned by `test/sources-federate-member-pages.test.ts` and `test/federation-exposure-private-9068.test.ts`.- `src/core/access/serves.ts` + `src/commands/access-serves.ts` (GST-363 PR 1) — whether a brain serves several people (`brainServes`: config `access.serves` `one`|`several` wins, else `access.serves_derived`, which migration v309's trigger keeps as `several` while 2+ members are enabled; `since` is `access.serves_since`, set once) and `gbrain access serves [several --members a,b [--yes]]`: preview, then config, members (kept when present), one folder rule `people/<member>/` per member through `addFolderRules` (`access-rules.ts`, the `rule add` preview-then-write path; a git store commits `.gbrain/access.yml` through the commit door), and one read-write token `member-<id>` per member through `auth-mint.ts` (the `auth create` mint) written to `<configDir>/member-keys/<id>.key` (0600, dir 0700, refused inside a git work tree: `access_serves_key_dir_in_git`). Idempotent on the member id; a token whose file is gone is reported, never re-minted. `GBRAIN_SETUP_ABORT_AFTER=serves-members|serves-rules|serves-key` is the crash seam. Doctor: `checks/unlabeled-people-folders.ts` fails a `people/<x>/` folder with pages no rule covers on a several-person brain. Tests: `test/setup-serves-several.test.ts` (both engines).diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex e9e3145bb9..b499b279e5 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/tool-catalog.ts` — `renderToolCatalogMarkdown()`: the docs/TOOL_CATALOG.md renderer. Config-independent + deterministic (no engine/config reads, no timestamps): non-localOnly ops grouped one section per `Operation.area`, per-op first-sentence description (from `buildToolDefs`'s non-strict shape), scope, STARTER_OPS membership, publish-gate key. Generated by `scripts/generate-tool-catalog.ts`; freshness-guarded by `scripts/check-tool-catalog-fresh.sh` in `bun run verify` (the METRIC_GLOSSARY pattern). Pinned by test/tool-catalog.test.ts.-- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list`, and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire, and on object `properties` (closed with `additionalProperties: false`, member `required` keys). Key ordering (type, description, enum, default, items, properties) is intentional so `JSON.stringify` output stays byte-stable. `toolAnnotations(op)` is the one annotation rule: curated op annotations win; else `readOnlyHint: true` for a read-scope op tagged `mutating: false`, `readOnlyHint: false` for one tagged `mutating: true`, nothing for untagged ops. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`. Annotations: curated `op.annotations` win; else `readOnlyHint: true` iff `mutating === false`, `readOnlyHint: false` (+ `idempotentHint: true` when `idempotent`) iff `mutating === true`; every op declares both tags (`test/ops-mutation-tags.test.ts`).+- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list`, and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run`/`room` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire, and on object `properties` (closed with `additionalProperties: false`, member `required` keys). Key ordering (type, description, enum, default, items, properties) is intentional so `JSON.stringify` output stays byte-stable. `toolAnnotations(op)` is the one annotation rule: curated op annotations win; else `readOnlyHint: true` for a read-scope op tagged `mutating: false`, `readOnlyHint: false` for one tagged `mutating: true`, nothing for untagged ops. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`. Annotations: curated `op.annotations` win; else `readOnlyHint: true` iff `mutating === false`, `readOnlyHint: false` (+ `idempotentHint: true` when `idempotent`) iff `mutating === true`; every op declares both tags (`test/ops-mutation-tags.test.ts`).- `src/mcp/validate-params.ts` — param normalization + validation for dispatch (direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, and so do the values a param's schema rules out: `0` below `minimum`/`exclusiveMinimum`, `[]` under `minItems`, `{}` on an object with a required member, `false` on an `actsWhenTrue` flag, then any param whose `appliesWith` param is absent (GST-927); required params untouched, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only, plus the explicit `PARAM_ALIAS_HINTS` aliases edit distance cannot reach, e.g. `add_timeline_entry` `content` → `detail` and `remember` `facts` → `items`, `text` → `fact`; dispatch rejects unknown keys on every `mutating` op regardless of `mcp.strict_params`, so a typo never commits a write, and appends the op's optional `callShape` (a valid call with placeholder values, set only by `remember`, GST-1493) to the suggestion), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per engine — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts. Every path that hands arguments to an op handler runs normalize → validate first: `dispatchToolCall`, `handleToolCall` (`gbrain call`) and the SkillOpt rollout and write-capture registries, so a model that sends `""` or `null` for every optional argument reads the same as one that omits them (`test/tool-args-empty-optional-sol.test.ts`). On a remote call the audience and attested-actor checks in `dispatchToolCall` read the normalized arguments, so `acting_user: ""` or `null` counts as omitted.- `src/core/mcp-request-log-retention.ts` — opt-in request-log retention (`cycle.purge.mcp_request_log_retention_days`: unset/0/off = off, 30-3650; `mcpLogRetentionRefusal` is the `config set` refusal). `pruneMcpRequestLog` runs batches of 2,000 (200 per run, the cutoff fixed once), each ONE statement: oldest rows past the cutoff in `created_at` order `FOR UPDATE SKIP LOCKED`, minus `AUDIT_LOG_OPERATIONS`, deleted and added to `mcp_request_log_rollup` (requests, last_used_at, `pruned_through` = newest pruned row; NULL token under `''`), so a failed tally deletes nothing; a missing tally table skips. `runMcpLogRetention` reads the key and records `{at, deleted, capped}` under `cycle.purge.mcp_request_log_last_prune`; callers: the cycle purge phase and `startMcpLogPruneTicker` (PGLite only, hourly, 3 s budget, yields between batches) in both serve lanes. `lifetimeUsage` = kept rows + tally in one statement (admin Agents totals). Pinned by `test/mcp-request-log-retention.test.ts` (both engines) and `test/serve-http-admin-request-log-retention.test.ts`.diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 49063fb908..8d78918d5b 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -28,6 +28,12 @@ harness --remove` stops the hooks from banking session text at all (see[ambient writeback](ambient-writeback.md#capture-lanes-and-the-off-switch)).Time-limited facts need an explicit TTL; ordinarysaved facts do not expire just because they describe a temporary situation.++In a shared chat, the owner's own questions are answered at the owner's full+scope, with every item marked by whether the people in the room could have+read it ([rooms](rooms.md)). The marks are for the agent's judgment about what+to say; they do not keep the raw results out of a group transcript, so the+harness must.`forget` withdraws a fact from active recall, not from all source material,history, or private backups. To remove the text itself from live stores, theowner runs a [purge](#purge) on the brain host. See [ambient writeback](ambient-writeback.md).diff --git a/docs/guides/rooms.md b/docs/guides/rooms.mdnew file mode 100644index 0000000000..5c6da7f427--- /dev/null+++ b/docs/guides/rooms.md@@ -0,0 +1,132 @@+# Owner turns in a shared room++**Say to your agent:** *"When I ask you something in the team chat, do the work with everything you know, and tell me privately about anything the room shouldn't see."*++A shared agent (a Slack, Telegram or Discord bot, a shared OpenClaw or Hermes)+often answers its owner inside a group chat. The owner should get the same+work they would get in a direct message, so gbrain never narrows that read.+What the agent needs is a way to tell which parts of the answer the people in+the room could not have read themselves. A **room** gives it that: the harness+says who is in the chat, gbrain answers at the caller's normal scope, and every+page and fact in the answer carries a `room_access` mark.++A room is a hint, never a filter. Declaring one never refuses, shortens,+reorders or fails a read, and a call that declares no room returns exactly what+it returned before rooms existed.++## Quickstart++1. Check that the server supports rooms: `whoami` returns `features.room: true`.+2. On every call made for a turn in a shared chat, name the people in it:++ ```text+ X-Gbrain-Room: alice-example, group:team-a # HTTP header (gbrain serve --http)+ "_meta": { "room": ["alice-example", "group:team-a"] } # request-level _meta, a sibling of arguments+ ```++ Entries are member ids, `group:<id>` or `guest` (someone who is not a+ member), the same grammar as `readable_by` and `on_behalf_of`.+3. Read each item's mark and the `_meta.room` summary, then write the reply.++## Channels++Prefer `_meta.room` or the `X-Gbrain-Room` header: the harness sets them and+conversation text cannot. A harness that cannot set either may pass a `room`+tool argument, but only after `whoami` shows `features.room` (an older server+rejects or ignores an unknown argument). The argument is removed before the+tool runs, so no handler, cache, retry or stored write ever sees it.++Text in the chat can put words into tool arguments, so an argument can only+add people, never remove them. When the argument names a different room than+the harness did, gbrain marks the answer for everyone either one names and+adds the `room_conflict` notice. Naming a smaller room in an argument changes+nothing else.++## What the marks mean++| `room_access` | Meaning | What the agent does |+|---|---|---|+| `{readable: true}` | everyone in the room could read this item themselves | use it freely in the reply |+| `{readable: false, reason}` | someone in the room could not read it | use it to do the work; keep it out of the reply unless the ask needs it, and offer it in a direct message |+| `{readable: "unknown", reason}` | gbrain could not tell | treat it like `false` |++`readable: true` means exactly what an `on_behalf_of` read for the same room+would return. The reasons for `false`, checked in this order:++| Reason | Why the room could not read it |+|---|---|+| `readers` | the page's `readable_by` leaves out someone in the room |+| `folder_rule` | a folder rule keeps it from someone in the room |+| `labelled_only` | someone in the room reads only pages labelled for them, and this one is not |+| `private_label` | the page is `visibility: private` |+| `derived` | it was built from a page the room cannot read |++When any item is not `true`, the answer carries the `room_above_level`+safety notice, so a model that never sees `_meta` still sees the warning.++`_meta.room` summarizes the call: `principals` (the room as read),+`declared_by` (`harness` or `argument`), `conflict`, `complete`,+`counts` (`items`, `readable`, `above`, `unknown`), `by_reason` and+`above` (each page or fact the room could not read, or that could not be+judged, by `source_id` and `slug`, `page_id` or `fact_id`, with its reason). Hot-memory+facts in `_meta.brain_hot_memory` are marked the same way.++Covered tools: `get_page`, `search`, `query`, `list_pages`, `find_pages`,+`get_chunks`, `get_timeline`, `get_backlinks`, `recall` and `entity`. Every+other tool still runs normally with a room declared; its answer is marked+unknown with reason `op_not_covered`.++## Who may ask++The brain owner's own credential may declare any room without `may_act_for`.+That exemption widens nothing: the owner already reads every page the room+could, the room only adds marks, and a room never changes which pages are+returned. It is also only an exemption for rooms; an `on_behalf_of` audience+from the owner's credential still needs `may_act_for` like anyone else's.++Any other member's credential needs `may_act_for` covering everyone in the+room, because the marks tell it what those people may read. Without it the+answer is unchanged and every item is marked unknown (`not_permitted`). A+connection bound to no member gets unknown marks (`unbound`).++A room describes who will see the answer, not whose turn it is. For a turn+asked by someone other than the owner, the harness names that audience with+`on_behalf_of`, which does narrow the read ([shared agents](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).++## When marks are unavailable++If the room cannot be judged, the answer is still complete and every item is+marked `{readable: "unknown", reason}`, `_meta.room.complete` is false and the+`room_hints_unavailable` degraded notice explains why:++| Reason | Cause | Fix |+|---|---|---|+| `invalid` | the room was empty or malformed | send a list of member ids, `group:<id>` or `guest` |+| `not_permitted` | the credential's `may_act_for` does not cover the room | the operator widens `may_act_for` |+| `unknown_principal` | the room names a disabled or unknown member or group | fix the name, or add the member |+| `unbound` | the connection is bound to no member | bind the credential to a member |+| `mark_failed`, `deadline` | judging failed or took more than 3 seconds | retry; nothing was changed |+| `op_not_covered` | the tool does not mark its results | none needed |++Some items can be unknown inside a complete answer too: `not_found` (the item+could not be looked up again), `not_identified` (it carries no page or fact+id) and `over_limit` (only the first 2,000 references are judged). When the+marked answer would exceed the response size cap, the unmarked answer is sent+with `_meta.room.complete: false`; treat every item as above the room.++## Keep raw results out of the room's transcript++Marks only help if the owner's raw tool results stay private. Many harnesses+store tool output in the conversation history, and in a group chat that+history may be visible to, or replayed for, everyone in it. A harness that+declares rooms must keep the owner's raw tool results out of any transcript+the room can read, and store only the reply it sent.++## Audit and repo-less brains++Each marked call appends a count-only `room_marked` row to+`~/.gbrain/audit/access-audience-YYYY-Www.jsonl`: how many items were+readable, above or unknown, by reason. It never records the room's names, slugs+or content. Rooms add no setting and no migration, and they work the same on a+repo-less brain, where the readers, folder rules and labels live in the+database.diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 058cea04d5..47833377f8 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -465,6 +465,13 @@ It never changes a grant or an exit code. A credential holdingnames, and a call that names no audience reads the credential's full grant, sothe harness must name one on every call.+The owner's own turn in a group chat is different: the owner should get the+whole answer, so the harness declares a room (`X-Gbrain-Room` or+`_meta.room`) instead of an audience. The read is unchanged and each item is+marked with what the room could read. The owner's credential needs no+`--may-act-for` for this; any other member's credential needs it to cover the+room. See [rooms](../guides/rooms.md).+`gbrain doctor --only unscoped_multi_user_token` runs the same detection overevery active token and OAuth client, and over the local agents setup wired: itwarns when one of them reads chat from 2+ channels, and reports a wired botdiff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.mdindex fd63f38957..ec32bcdc72 100644--- a/docs/operations/mcp-surface-runbook.md+++ b/docs/operations/mcp-surface-runbook.md@@ -178,7 +178,7 @@ gbrain config set mcp.strict_params reject**Expected outcome (schema emission change):** besides rejecting unknownargs, tools/list schemas change shape — each `inputSchema` closes with-`additionalProperties: false` and declares the `_meta`/`dry_run`+`additionalProperties: false` and declares the `_meta`/`dry_run`/`room`passthrough keys (D14.1), keeping schema-validating clients aligned withthe server's reject posture. Read per request; flipping back to `warn`reopens the schemas on the next list. A transient config-read failurediff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex 34e285dda7..b474a89b13 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -753,7 +753,8 @@ except the notices that describe one call's result. HTTP is stateless, sodedupe is per authenticated client and session, and `degraded` and `safety`notices ride every affected call. At most 2 `coaching` notices per session.Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,-`listing_truncated`, `delta_incomplete`, `facts_unembedded`)+`listing_truncated`, `delta_incomplete`, `facts_unembedded`, and the room+notices `room_above_level`, `room_hints_unavailable` and `room_conflict`)are never deduped on any transport, with one exception: a `degraded_recall`whose only stages come from the brain's configuration (`embed_unavailable` ona keyless brain, which degrades every search the same way) shows once per@@ -866,6 +867,19 @@ nothing; it returns in the next session until the decision is answered`gbrain onboard --check` list decisions that are open but muted, with the`gbrain notices unmute first_run_decisions` command.+### Room notices++A harness that declares the shared chat an answer goes into (`X-Gbrain-Room`,+`_meta.room` or a `room` argument) gets the caller's full answer with each+item marked `room_access` ([rooms](../guides/rooms.md)). Three notices ride it,+and none of them ever refuses the work:++| Code | Kind | What you do |+|---|---|---|+| `room_above_level` | `safety` | some items are `readable: false` or `unknown` for the room: use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a direct message |+| `room_hints_unavailable` | `degraded` | the room could not be judged (`_meta.room.unavailable` names why): the answer is complete, treat every item as above the room, and follow `fix` when one is given |+| `room_conflict` | `safety` | the `room` argument named a different room than the harness did: the answer was marked for everyone either names; trust the harness's room |+## Degraded stampEvery successful read whose result is partial or degraded carries one stamp,diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex a6bf416196..9a0f997082 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -34,6 +34,7 @@ shape for it.| `degraded` | dispatch (`src/core/degraded-stamp.ts`), on every transport | `{reasons: [...]}`: present only when the result is partial or degraded; sorted, unique stable codes ([AGENT_OPERATOR_v1.md, Degraded stamp](AGENT_OPERATOR_v1.md#degraded-stamp)). Mirrored as the last content block, `[gbrain degraded: <codes>] …` || `retrieval` | `search`/`query` op handlers; `recall` and `find_experts` emit `{degraded[]}` when their page search degraded | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed), `timings` (`{total_ms, stages_ms, other_ms, overlapped_ms?, parts_ms?}`, integer ms, every response; [search-explain.md](../guides/search-explain.md#see-where-the-time-went)) || `access` | dispatch (`appliedAccessSummary`, `src/core/access/caller.ts`), every remote response that reached the operation | The view the call was answered under: `member` and `groups` it read as (null and `[]` for an unbound caller or an audience of several entries), `audience` (the normalized `on_behalf_of` principals, or null), `policy_rev` (each source's applied folder-rule revision; null on a brain with no restriction), `relaxation` (`none`, `granted_sources`, `operator` or `owner`: what relaxed `visibility: private`; `owner` is a credential bound to the brain owner, see [access designations](../guides/access-designations.md)). `whoami` returns the same object as `access.applied`. An attested call adds `actor` (`{system}`); an unlinked `memory_recall` carries `code: "actor_unlinked"`, `member: null` and the id as sent. |+| `room` | dispatch (`assessRoom`, `src/core/access/room.ts`), only on a call that declared a room | The shared chat the answer goes into, as read: `principals`, `declared_by` (`harness` or `argument`), `conflict` (present when the argument and the harness disagreed), `complete`, `counts` (`{items, readable, above, unknown}`), `by_reason`, `above` (references the room could not read) and `unavailable` (why no marks could be computed: `invalid`, `not_permitted`, `unknown_principal`, `unbound`, `mark_failed`, `deadline`, `op_not_covered`, `response_cap`). Each page and fact in the body carries `room_access` (`{readable: true}`, `{readable: false, reason}` with reason `readers`, `folder_rule`, `labelled_only`, `private_label` or `derived`, or `{readable: "unknown", reason}`). [Details](#room) || `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]`: a parameter a read ignored. This is the only place the warning appears; no content block or notice carries it, so a harness that stores tool output in its turns never stores it (writes refuse unknown parameters instead). || `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |@@ -158,6 +159,29 @@ whose first source is that member's private source."_meta": {"session_id": "channel-a", "hot_memory": "off"}}}```+## `room`++`room` is the one key that also travels on the request. A harness sets the+request-level `_meta.room` (a sibling of `arguments`) or the `X-Gbrain-Room`+header, and the response carries `_meta.room` back:++```jsonc+// request+{ "name": "search", "arguments": { "query": "launch plan" },+ "_meta": { "room": ["alice-example", "group:team-a"] } }++// response _meta+{ "room": { "principals": ["alice-example", "group:team-a"], "declared_by": "harness",+ "complete": true, "counts": { "items": 3, "readable": 2, "above": 1, "unknown": 0 },+ "by_reason": { "readers": 1 }, "above": [{ "source_id": "default", "slug": "notes/owner-plan", "reason": "readers" }] } }+```++A room never changes the body's items or their order; it only adds+`room_access` to each item. A call with no room carries no `room` key. The+model-visible counterparts are the `room_above_level`,+`room_hints_unavailable` and `room_conflict` notice blocks. Full guide:+[rooms](../guides/rooms.md).+## Degraded stamp codesThe codes in `_meta.degraded.reasons` ([AGENT_OPERATOR_v1.md, Degraded stamp](AGENT_OPERATOR_v1.md#degraded-stamp)). The list grows; a code never changes meaning.diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex 058f82c525..513a9c7487 100644--- a/docs/tutorials/company-brain.md+++ b/docs/tutorials/company-brain.md@@ -165,7 +165,7 @@ X-Gbrain-On-Behalf-Of: alice-example, bob-example, guest # a channel with a no"_meta": { "on_behalf_of": ["alice-example"] } # request-level _meta, a sibling of arguments (stdio and HTTP)```-A page is returned only when every audience entry may read it (`guest` reads no restricted page, `group:team-a` counts as one entry for a large channel), within the agent's own source grant. The agent's `--private-pages granted-sources` and the operator hatches relax `visibility: private` only when the audience is exactly one member; a channel never sees a private page. The audience is read on every call, so a DM followed by a channel turn gets each its own view. An entry outside `may_act_for` refuses `on_behalf_of_not_permitted` (the operator widens the list with the command it prints), a disabled or unknown member refuses `on_behalf_of_unknown_member`, and an audience inside tool arguments, where conversation text could set it, refuses `on_behalf_of_in_arguments`. Every response carries the applied view in `_meta.access`, and `whoami` returns it as `access.applied` for a model whose harness hides `_meta`. Writes and `submit_agent` jobs keep the audience they were made for and re-check it before they commit or call a tool. A local stdio server takes its list from `gbrain config set mcp.stdio_may_act_for <list>`. `*` permits any member, lets the harness learn which member and group ids exist from the refusals, and `gbrain doctor` warns about it (`access_may_act_for_wildcard`). Each assertion is appended to `~/.gbrain/audit/access-audience-YYYY-Www.jsonl`. Where each person runs their own agent, a credential bound to that person's member stays the simpler setup. Shared agents work the same on a repo-less brain: `may_act_for` and the audience are database and request state.+A page is returned only when every audience entry may read it (`guest` reads no restricted page, `group:team-a` counts as one entry for a large channel), within the agent's own source grant. The agent's `--private-pages granted-sources` and the operator hatches relax `visibility: private` only when the audience is exactly one member; a channel never sees a private page. The audience is read on every call, so a DM followed by a channel turn gets each its own view. An entry outside `may_act_for` refuses `on_behalf_of_not_permitted` (the operator widens the list with the command it prints), a disabled or unknown member refuses `on_behalf_of_unknown_member`, and an audience inside tool arguments, where conversation text could set it, refuses `on_behalf_of_in_arguments`. Every response carries the applied view in `_meta.access`, and `whoami` returns it as `access.applied` for a model whose harness hides `_meta`. Writes and `submit_agent` jobs keep the audience they were made for and re-check it before they commit or call a tool. A local stdio server takes its list from `gbrain config set mcp.stdio_may_act_for <list>`. `*` permits any member, lets the harness learn which member and group ids exist from the refusals, and `gbrain doctor` warns about it (`access_may_act_for_wildcard`). Each assertion is appended to `~/.gbrain/audit/access-audience-YYYY-Www.jsonl`. Where each person runs their own agent, a credential bound to that person's member stays the simpler setup. Shared agents work the same on a repo-less brain: `may_act_for` and the audience are database and request state. When the brain's owner asks the agent something in a channel, the harness declares the channel as a room (`X-Gbrain-Room` or `_meta.room`) instead: the owner gets the whole answer and every item says whether the room could have read it ([rooms](../guides/rooms.md)).**A trusted system that names the person (QM).** When a system such as QM already authenticates each person, it names one person per call instead of an audience. Grant its client-credentials client the attest right and link each person's canonical id to their member:diff --git a/llms-full.txt b/llms-full.txtindex 6832112cc9..1ff5762d62 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3524,7 +3524,8 @@ except the notices that describe one call's result. HTTP is stateless, sodedupe is per authenticated client and session, and `degraded` and `safety`notices ride every affected call. At most 2 `coaching` notices per session.Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,-`listing_truncated`, `delta_incomplete`, `facts_unembedded`)+`listing_truncated`, `delta_incomplete`, `facts_unembedded`, and the room+notices `room_above_level`, `room_hints_unavailable` and `room_conflict`)are never deduped on any transport, with one exception: a `degraded_recall`whose only stages come from the brain's configuration (`embed_unavailable` ona keyless brain, which degrades every search the same way) shows once per@@ -3637,6 +3638,19 @@ nothing; it returns in the next session until the decision is answered`gbrain onboard --check` list decisions that are open but muted, with the`gbrain notices unmute first_run_decisions` command.+### Room notices++A harness that declares the shared chat an answer goes into (`X-Gbrain-Room`,+`_meta.room` or a `room` argument) gets the caller's full answer with each+item marked `room_access` ([rooms](../guides/rooms.md)). Three notices ride it,+and none of them ever refuses the work:++| Code | Kind | What you do |+|---|---|---|+| `room_above_level` | `safety` | some items are `readable: false` or `unknown` for the room: use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a direct message |+| `room_hints_unavailable` | `degraded` | the room could not be judged (`_meta.room.unavailable` names why): the answer is complete, treat every item as above the room, and follow `fix` when one is given |+| `room_conflict` | `safety` | the `room` argument named a different room than the harness did: the answer was marked for everyone either names; trust the harness's room |+## Degraded stampEvery successful read whose result is partial or degraded carries one stamp,diff --git a/llms.txt b/llms.txtindex 90c0f3838a..9901c7a68a 100644--- a/llms.txt+++ b/llms.txt@@ -10,6 +10,7 @@ Repo: https://github.com/garrytan/gbrain- [Grok Bot](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/grok-bot.md): Recommended: keep the brain on your computer, publish it with `gbrain mcp expose --funnel`, grant the Bot a client and install the thin CLI; local in-Bot memory as the no-host alternative. Native skill activation, shared-computer trust and dated evidence.- [Muse personal agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/muse.md): Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP.- [Inside an existing agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/in-agent-setup.md): Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration.+- [Owner turns in a shared room](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/rooms.md): Declare the group chat an answer goes into (X-Gbrain-Room, _meta.room, a room argument): the owner's read is unchanged and every page and fact is marked room_access with whether the room could have read it; reasons, notices, who may ask, and keeping raw results out of the group transcript.- [Memory boundaries](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/memory-boundaries.md): Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits; large pages (segmented storage up to 256 MiB on Postgres, append_page / gbrain append, upload sessions, windowed reads, limits per entry point).- [Page history](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/page-history.md): Why a page changed: an optional reason on page writes, replaced_because in get_versions, the gbrain-reason commit trailer, remote visibility and repo-less brains.- [Brain versus session memory](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/brain-vs-memory.md): Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.mdindex 15c2e58882..ac48892f98 100644--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md@@ -755,7 +755,8 @@ except the notices that describe one call's result. HTTP is stateless, sodedupe is per authenticated client and session, and `degraded` and `safety`notices ride every affected call. At most 2 `coaching` notices per session.Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,-`listing_truncated`, `delta_incomplete`, `facts_unembedded`)+`listing_truncated`, `delta_incomplete`, `facts_unembedded`, and the room+notices `room_above_level`, `room_hints_unavailable` and `room_conflict`)are never deduped on any transport, with one exception: a `degraded_recall`whose only stages come from the brain's configuration (`embed_unavailable` ona keyless brain, which degrades every search the same way) shows once per@@ -868,6 +869,19 @@ nothing; it returns in the next session until the decision is answered`gbrain onboard --check` list decisions that are open but muted, with the`gbrain notices unmute first_run_decisions` command.+### Room notices++A harness that declares the shared chat an answer goes into (`X-Gbrain-Room`,+`_meta.room` or a `room` argument) gets the caller's full answer with each+item marked `room_access` ([rooms](https://github.com/garrytan/gbrain/blob/master/docs/guides/rooms.md)). Three notices ride it,+and none of them ever refuses the work:++| Code | Kind | What you do |+|---|---|---|+| `room_above_level` | `safety` | some items are `readable: false` or `unknown` for the room: use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a direct message |+| `room_hints_unavailable` | `degraded` | the room could not be judged (`_meta.room.unavailable` names why): the answer is complete, treat every item as above the room, and follow `fix` when one is given |+| `room_conflict` | `safety` | the `room` argument named a different room than the harness did: the answer was marked for everyone either names; trust the harness's room |+## Degraded stampEvery successful read whose result is partial or degraded carries one stamp,diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.mdindex 15c2e58882..ac48892f98 100644--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md@@ -755,7 +755,8 @@ except the notices that describe one call's result. HTTP is stateless, sodedupe is per authenticated client and session, and `degraded` and `safety`notices ride every affected call. At most 2 `coaching` notices per session.Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,-`listing_truncated`, `delta_incomplete`, `facts_unembedded`)+`listing_truncated`, `delta_incomplete`, `facts_unembedded`, and the room+notices `room_above_level`, `room_hints_unavailable` and `room_conflict`)are never deduped on any transport, with one exception: a `degraded_recall`whose only stages come from the brain's configuration (`embed_unavailable` ona keyless brain, which degrades every search the same way) shows once per@@ -868,6 +869,19 @@ nothing; it returns in the next session until the decision is answered`gbrain onboard --check` list decisions that are open but muted, with the`gbrain notices unmute first_run_decisions` command.+### Room notices++A harness that declares the shared chat an answer goes into (`X-Gbrain-Room`,+`_meta.room` or a `room` argument) gets the caller's full answer with each+item marked `room_access` ([rooms](https://github.com/garrytan/gbrain/blob/master/docs/guides/rooms.md)). Three notices ride it,+and none of them ever refuses the work:++| Code | Kind | What you do |+|---|---|---|+| `room_above_level` | `safety` | some items are `readable: false` or `unknown` for the room: use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a direct message |+| `room_hints_unavailable` | `degraded` | the room could not be judged (`_meta.room.unavailable` names why): the answer is complete, treat every item as above the room, and follow `fix` when one is given |+| `room_conflict` | `safety` | the `room` argument named a different room than the harness did: the answer was marked for everyone either names; trust the harness's room |+## Degraded stampEvery successful read whose result is partial or degraded carries one stamp,diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.mdindex 15c2e58882..ac48892f98 100644--- a/plugin/skills/conventions/agent-operator-protocol.md+++ b/plugin/skills/conventions/agent-operator-protocol.md@@ -755,7 +755,8 @@ except the notices that describe one call's result. HTTP is stateless, sodedupe is per authenticated client and session, and `degraded` and `safety`notices ride every affected call. At most 2 `coaching` notices per session.Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,-`listing_truncated`, `delta_incomplete`, `facts_unembedded`)+`listing_truncated`, `delta_incomplete`, `facts_unembedded`, and the room+notices `room_above_level`, `room_hints_unavailable` and `room_conflict`)are never deduped on any transport, with one exception: a `degraded_recall`whose only stages come from the brain's configuration (`embed_unavailable` ona keyless brain, which degrades every search the same way) shows once per@@ -868,6 +869,19 @@ nothing; it returns in the next session until the decision is answered`gbrain onboard --check` list decisions that are open but muted, with the`gbrain notices unmute first_run_decisions` command.+### Room notices++A harness that declares the shared chat an answer goes into (`X-Gbrain-Room`,+`_meta.room` or a `room` argument) gets the caller's full answer with each+item marked `room_access` ([rooms](https://github.com/garrytan/gbrain/blob/master/docs/guides/rooms.md)). Three notices ride it,+and none of them ever refuses the work:++| Code | Kind | What you do |+|---|---|---|+| `room_above_level` | `safety` | some items are `readable: false` or `unknown` for the room: use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a direct message |+| `room_hints_unavailable` | `degraded` | the room could not be judged (`_meta.room.unavailable` names why): the answer is complete, treat every item as above the room, and follow `fix` when one is given |+| `room_conflict` | `safety` | the `room` argument named a different room than the harness did: the answer was marked for everyone either names; trust the harness's room |+## Degraded stampEvery successful read whose result is partial or degraded carries one stamp,diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex a395eb06b3..25843bd3e6 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -45,6 +45,7 @@ export const SECTIONS: DocSection[] = [{ title: "Grok Bot", path: "docs/guides/grok-bot.md", description: "Recommended: keep the brain on your computer, publish it with `gbrain mcp expose --funnel`, grant the Bot a client and install the thin CLI; local in-Bot memory as the no-host alternative. Native skill activation, shared-computer trust and dated evidence.", includeInFull: false },{ title: "Muse personal agent", path: "docs/guides/muse.md", description: "Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP.", includeInFull: false },{ title: "Inside an existing agent", path: "docs/guides/in-agent-setup.md", description: "Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration.", includeInFull: false },+ { title: "Owner turns in a shared room", path: "docs/guides/rooms.md", description: "Declare the group chat an answer goes into (X-Gbrain-Room, _meta.room, a room argument): the owner's read is unchanged and every page and fact is marked room_access with whether the room could have read it; reasons, notices, who may ask, and keeping raw results out of the group transcript.", includeInFull: false },{ title: "Memory boundaries", path: "docs/guides/memory-boundaries.md", description: "Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits; large pages (segmented storage up to 256 MiB on Postgres, append_page / gbrain append, upload sessions, windowed reads, limits per entry point).", includeInFull: false },{ title: "Page history", path: "docs/guides/page-history.md", description: "Why a page changed: an optional reason on page writes, replaced_because in get_versions, the gbrain-reason commit trailer, remote visibility and repo-less brains.", includeInFull: false },{ title: "Brain versus session memory", path: "docs/guides/brain-vs-memory.md", description: "Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.", includeInFull: false },diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.mdindex 15c2e58882..ac48892f98 100644--- a/skills/conventions/agent-operator-protocol.md+++ b/skills/conventions/agent-operator-protocol.md@@ -755,7 +755,8 @@ except the notices that describe one call's result. HTTP is stateless, sodedupe is per authenticated client and session, and `degraded` and `safety`notices ride every affected call. At most 2 `coaching` notices per session.Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,-`listing_truncated`, `delta_incomplete`, `facts_unembedded`)+`listing_truncated`, `delta_incomplete`, `facts_unembedded`, and the room+notices `room_above_level`, `room_hints_unavailable` and `room_conflict`)are never deduped on any transport, with one exception: a `degraded_recall`whose only stages come from the brain's configuration (`embed_unavailable` ona keyless brain, which degrades every search the same way) shows once per@@ -868,6 +869,19 @@ nothing; it returns in the next session until the decision is answered`gbrain onboard --check` list decisions that are open but muted, with the`gbrain notices unmute first_run_decisions` command.+### Room notices++A harness that declares the shared chat an answer goes into (`X-Gbrain-Room`,+`_meta.room` or a `room` argument) gets the caller's full answer with each+item marked `room_access` ([rooms](https://github.com/garrytan/gbrain/blob/master/docs/guides/rooms.md)). Three notices ride it,+and none of them ever refuses the work:++| Code | Kind | What you do |+|---|---|---|+| `room_above_level` | `safety` | some items are `readable: false` or `unknown` for the room: use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a direct message |+| `room_hints_unavailable` | `degraded` | the room could not be judged (`_meta.room.unavailable` names why): the answer is complete, treat every item as above the room, and follow `fix` when one is given |+| `room_conflict` | `safety` | the `room` argument named a different room than the harness did: the answer was marked for everyone either names; trust the harness's room |+## Degraded stampEvery successful read whose result is partial or degraded carries one stamp,diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 559783ceeb..478408a661 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -44,7 +44,7 @@"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e","context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",- "conventions/agent-operator-protocol.md": "feefde8f9b02060747c63e5a97bde4f5f1e868d5cfe54746f94bc598e3aa65b6",+ "conventions/agent-operator-protocol.md": "eb87070d4ab1492b94f9e85b59aaa3dbf9ee0f484686d06b548c1a0ef14c845e","conventions/brain-first.md": "f84f03b9619a1c9302a231bd43957c6987d55084f56eee351434b85ec2646a5c","conventions/brain-routing.md": "c325dacde22e6df12b8c90decd92b5cb1845f2c9b9e211ea8ee0ac5ee1c9f390","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex af239ac466..2079ecaf28 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -46,6 +46,7 @@ import {} from '../mcp/surface.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';+import { ROOM_HEADER } from '../core/access/room.ts';import { ACTOR_HEADER, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER } from '../core/access/actor-model.ts';import { parseAgentLabel, AGENT_LABEL_HEADER } from '../core/persistence/attribution.ts';import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';@@ -76,6 +77,8 @@ interface McpRequestState {thinClient: boolean;/** GBRA-231: the X-Gbrain-On-Behalf-Of header (a shared agent's audience); bounded by the credential's may_act_for in dispatch. */onBehalfOfHeader: string | undefined;+ /** GBRA-498: the X-Gbrain-Room header (the room an answer goes into); it only marks results, never narrows or widens them. */+ roomHeader: string | undefined;/** GST-359 C1: the x-qm-actor header (a trusted system names the person); honoured in dispatch only for an attest credential. */actorHeader: string | undefined;/** GST-359 D: the x-qm-audience header (QM's channel audience, wave 2); any request carrying it is refused before any work. */@@ -201,7 +204,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient,- onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER),+ onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), roomHeader: req.get(ROOM_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER),userAgent: req.get('user-agent'), agentLabel: parseAgentLabel(req.get(AGENT_LABEL_HEADER)) };const server = createMcpRequestServer(ctx, state, writeback, writeback?.enabled ? await engine.getConfig(OWNER_MEMBER_KEY).catch(() => null) : null);await serveMcpRequest(server, req, res);@@ -456,6 +459,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques...(sessionId ? { sessionId } : {}),...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },+ room: { header: state.roomHeader, requestMeta: (request.params as { _meta?: unknown })._meta },mcpCaller: { client: authInfo.clientName, userAgent: state.userAgent, meta: (request.params as { _meta?: Record<string, unknown> })._meta },actor: { header: state.actorHeader, audience: state.audienceHeader },...(state.agentLabel ? { agentLabel: state.agentLabel } : {}),diff --git a/src/core/access/audience.ts b/src/core/access/audience.tsindex 90d115f4c8..451a9d4008 100644--- a/src/core/access/audience.ts+++ b/src/core/access/audience.ts@@ -37,20 +37,30 @@ function invalid(what: string): never {const shown = (value: unknown) => JSON.stringify(typeof value === 'string' && value.length > 64 ? `${value.slice(0, 64)}...` : value);-function entries(list: readonly unknown[], channel: string): AudiencePrincipal[] {- if (list.length === 0) invalid(`${channel} names nobody`);- if (list.length > MAX_AUDIENCE) invalid(`${channel} names ${list.length} entries (at most ${MAX_AUDIENCE}; name a group:<id> for a large channel)`);+/**+ * The normalized principals of one channel (sorted, distinct), or the reason it is invalid: empty, over+ * MAX_AUDIENCE, or an entry that is not a member id, group:<id> or guest. Shared by on_behalf_of and room.+ */+export function normalizePrincipals(list: readonly unknown[], channel: string): AudiencePrincipal[] | { invalid: string } {+ if (list.length === 0) return { invalid: `${channel} names nobody` };+ if (list.length > MAX_AUDIENCE) return { invalid: `${channel} names ${list.length} entries (at most ${MAX_AUDIENCE}; name a group:<id> for a large channel)` };const out = new Set<AudiencePrincipal>();for (const raw of list) {- if (typeof raw !== 'string') invalid(`${channel} holds ${shown(raw)}, which is not a string`);+ if (typeof raw !== 'string') return { invalid: `${channel} holds ${shown(raw)}, which is not a string` };if (raw.trim().toLowerCase() === GUEST) { out.add(GUEST); continue; }const p = normalizePrincipal(raw);- if (!p) invalid(`${channel} holds ${shown(raw)}, which is not a member id, group:<id> or guest`);+ if (!p) return { invalid: `${channel} holds ${shown(raw)}, which is not a member id, group:<id> or guest` };out.add(p);}return [...out].sort();}+function entries(list: readonly unknown[], channel: string): AudiencePrincipal[] {+ const parsed = normalizePrincipals(list, channel);+ if ('invalid' in parsed) invalid(parsed.invalid);+ return parsed;+}+/*** The normalized audience a request asserts (sorted, distinct), or null when it asserts none. A present but empty,* oversized or malformed channel, or a header and _meta that disagree, refuse on_behalf_of_invalid_audience.@@ -108,9 +118,13 @@ export interface AudienceAuditEvent {/** GST-363: a read from a connection bound to nobody on a brain that serves several people, refused before any work. */| 'requester_scope_required'/** GST-363: the same read when whom the brain serves could not be read (even after one re-read): refused as retryable. */- | 'requester_scope_unknown';+ | 'requester_scope_unknown'+ /** GBRA-498: an answer marked for a room (counts only, never refs or content; access/room.ts). */+ | 'room_marked';/** GST-359 C1: an attested actor's system, the id it named (only when well-formed) and a refusal's reason. */actor?: { system: string; external_id?: string; reason?: string };+ /** GBRA-498: a room_marked row's counts: items readable by the room, above it, undecided, and above by reason class. */+ room?: { readable: number; above: number; unknown: number; by_reason: Record<string, number>; declared_by: string; unavailable?: string };}const audit = createAuditWriter<AudienceAuditEvent>({ featureName: 'access-audience', errorLabel: 'access-audience-audit', errorTrailer: '; continuing' });diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex ea12903bed..c681d5a43f 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -235,10 +235,15 @@ function audienceUnknown(principal: string) {* or an existing group (on_behalf_of_unknown_member). Read on every call, so a revoked permission or a disabled* member takes effect at once.*/-export async function resolveAudienceIdentities(engine: Pick<BrainEngine, 'executeRaw'>, caller: AudienceCaller, audience: readonly AudiencePrincipal[]): Promise<string[][]> {- const mayActFor = await mayActForOf(engine, caller);- const missing = audience.filter(p => !mayActForCovers(mayActFor, p));- if (missing.length) throw audienceNotPermitted(caller, audience, mayActFor, missing);+export async function resolveAudienceIdentities(engine: Pick<BrainEngine, 'executeRaw'>, caller: AudienceCaller, audience: readonly AudiencePrincipal[],+ opts: { mayActFor?: 'enforce' | 'owner_room_assessment' } = {}): Promise<string[][]> {+ // GBRA-498: only room.ts passes owner_room_assessment, after it checked that the caller reads as the brain owner; it+ // marks results for a room and never reads as the room, so the owner's credential needs no may_act_for for it.+ if (opts.mayActFor !== 'owner_room_assessment') {+ const mayActFor = await mayActForOf(engine, caller);+ const missing = audience.filter(p => !mayActForCovers(mayActFor, p));+ if (missing.length) throw audienceNotPermitted(caller, audience, mayActFor, missing);+ }const memberIds = audience.filter(p => p.startsWith('member:')).map(p => p.slice('member:'.length));const groupIds = audience.filter(p => p.startsWith('group:')).map(p => p.slice('group:'.length));const members = new Map<string, string[]>();@@ -282,29 +287,7 @@ export async function resolveAudienceIdentities(engine: Pick<BrainEngine, 'execuexport async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string, audience?: readonly AudiencePrincipal[] | null, stdioMember?: string, readOnly = false): Promise<Partial<CallerAccess>> {const [relaxed, remotePolicy] = await Promise.all([remotePrivacyRelaxed(engine), requestRemotePolicy(engine)]);const restricted = remotePolicy.restricted;- if (audience?.length) {- const identities = await resolveAudienceIdentities(engine, { auth, transport }, audience);- const single = singleMemberAudience(audience);- const owner = single && audience[0] === `member:${remotePolicy.ownerMember}`- && isOwner(await boundIdentity(engine, auth, transport, stdioMember), remotePolicy);- const lineage = readOnly && single && identities.length === 1 && (owner || remotePolicy.membersReadLineage === true);- return {- identity: identities.length === 1 ? identities[0]! : [],- audience: [...audience],- audienceIdentities: identities.length > 1 ? identities : [],- ...(restricted ? await folderAccessForAll(engine, identities) : { satisfiedRuleIds: [], folderCoverage: [] }),- privateReadableSources: single ? privateSources ?? [] : [],- hidePrivate: single ? !relaxed && !owner : true,- owner,- lineage,- ownerReadsRestricted: owner && lineage && remotePolicy.ownerReadsRestricted === true,- audienceKindMembers: owner && lineage ? await audienceMemberIds(engine) : [],- labelledOnly: !owner && restricted && await labelledOnlyFor(engine, [...identities, await boundIdentity(engine, auth, transport, stdioMember)]),- applyRemoteReadPolicy: false,- restricted,- remotePolicy,- };- }+ if (audience?.length) return audienceCallerAccess(engine, auth, privateSources, transport, audience, await resolveAudienceIdentities(engine, { auth, transport }, audience), stdioMember, readOnly, relaxed, remotePolicy);const identity = restricted || remotePolicy.ownerMember ? await boundIdentity(engine, auth, transport, stdioMember) : [];const owner = isOwner(identity, remotePolicy);const lineage = readOnly && identity.some(p => p.startsWith('member:')) && (owner || remotePolicy.membersReadLineage === true);@@ -326,6 +309,38 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | u};}+/**+ * GBRA-231: the access record of an audience whose identities resolveAudienceIdentities resolved. GBRA-498: room.ts+ * builds a room's record with it, so a room mark and an on_behalf_of read of the same audience judge pages alike.+ */+export async function audienceCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport: string | undefined,+ audience: readonly AudiencePrincipal[], identities: string[][], stdioMember?: string, readOnly = false,+ relaxed?: boolean, policy?: RemotePolicy): Promise<Partial<CallerAccess>> {+ const remotePolicy = policy ?? await requestRemotePolicy(engine);+ const restricted = remotePolicy.restricted;+ if (relaxed === undefined) relaxed = await remotePrivacyRelaxed(engine);+ const single = singleMemberAudience(audience);+ const owner = single && audience[0] === `member:${remotePolicy.ownerMember}`+ && isOwner(await boundIdentity(engine, auth, transport, stdioMember), remotePolicy);+ const lineage = readOnly && single && identities.length === 1 && (owner || remotePolicy.membersReadLineage === true);+ return {+ identity: identities.length === 1 ? identities[0]! : [],+ audience: [...audience],+ audienceIdentities: identities.length > 1 ? identities : [],+ ...(restricted ? await folderAccessForAll(engine, identities) : { satisfiedRuleIds: [], folderCoverage: [] }),+ privateReadableSources: single ? privateSources ?? [] : [],+ hidePrivate: single ? !relaxed && !owner : true,+ owner,+ lineage,+ ownerReadsRestricted: owner && lineage && remotePolicy.ownerReadsRestricted === true,+ audienceKindMembers: owner && lineage ? await audienceMemberIds(engine) : [],+ labelledOnly: !owner && restricted && await labelledOnlyFor(engine, [...identities, await boundIdentity(engine, auth, transport, stdioMember)]),+ applyRemoteReadPolicy: false,+ restricted,+ remotePolicy,+ };+}+/** The member identity a remote caller's credential (or, unauthenticated over stdio, serve --stdio-member, else config mcp.stdio_member) is bound to. */async function boundIdentity(engine: BrainEngine, auth: AuthInfo | undefined, transport?: string, stdioMember?: string): Promise<string[]> {return !auth && transport === 'stdio' ? stdioMemberIdentity(engine, stdioMember) : memberIdentityFor(engine, auth);diff --git a/src/core/access/room.ts b/src/core/access/room.tsnew file mode 100644index 0000000000..fc345b3027--- /dev/null+++ b/src/core/access/room.ts@@ -0,0 +1,334 @@+/**+ * GBRA-498: room-aware results. When a harness says an answer is going into a shared room (a group chat), a read+ * still returns exactly what the caller reads; every returned item gains `room_access`, saying whether the room's+ * audience could have read it itself and, when not, why. One notice tells the agent to use everything for the work,+ * keep what the room cannot read out of the reply unless the ask needs it, and offer the rest in a private chat.+ *+ * Three rules hold everywhere in this module: a room never refuses, shortens or fails a read (every problem becomes+ * `readable: "unknown"` plus a degraded notice); with no room the result is untouched; and nothing here changes what+ * any caller reads. The decision per page is the same predicate an on_behalf_of read of the room applies+ * (privatePagesFilterForCaller under the room's own access record), so "readable: true" means exactly "a read as the+ * room would have returned it". Channels: request-level `_meta.room` or the X-Gbrain-Room header (the harness's,+ * authoritative), or a `room` tool argument, which can only add people to the harness's room.+ */+import type { BrainEngine } from '../engine.ts';+import type { AuthInfo } from '../ops/contract.ts';+import type { Action, Notice } from '../agent-output.ts';+import { logAudienceAssertion, normalizePrincipals, type AudiencePrincipal } from './audience.ts';+import { audienceCallerAccess, resolveAudienceIdentities } from './caller.ts';+import { factVisibilitySql } from './member-facts.ts';+import {+ callerIdentities, currentCallerAccess, folderRulesAllowedSql, labelledOnlyForSql, privacyForCaller, privacyPartSql,+ privatePagesFilterForCaller, privateProvenanceFilterUnderPolicy, readersAllowedSql, withCallerAccess, worldOnlyFacts,+ type CallerAccess,+} from '../search/private-visibility.ts';++export const ROOM_HEADER = 'X-Gbrain-Room';+export const ROOM_ARGUMENT = 'room';+/** The per-item key. Namespaced so it never collides with a page field or frontmatter key named room. */+export const ROOM_ACCESS_KEY = 'room_access';+/** Assessment budget per call: past it every item is unknown and the read goes out unchanged otherwise. */+export const ROOM_DEADLINE_MS = 3_000;+/** At most this many distinct refs are judged per call; the rest are unknown. */+export const ROOM_MAX_REFS = 2_000;++/** Why the room could not read an item. */+export type RoomReason = 'readers' | 'folder_rule' | 'labelled_only' | 'private_label' | 'derived';+/** Why an item, or the whole answer, could not be judged. */+export type RoomUnknownReason = 'invalid' | 'not_permitted' | 'unknown_principal' | 'unbound' | 'mark_failed' | 'deadline'+ | 'op_not_covered' | 'not_found' | 'not_identified' | 'over_limit';+export type RoomAccess = { readable: true } | { readable: false; reason: RoomReason } | { readable: 'unknown'; reason: RoomUnknownReason };++/** The room channels a transport saw: the header and request-level _meta (its `room` key). */+export interface RoomChannels { header?: string | null; requestMeta?: unknown }++export interface RoomDeclaration {+ /** The effective room: the harness's room plus any principal the argument adds (never fewer). */+ principals: AudiencePrincipal[];+ declared_by: 'harness' | 'argument';+ /** The argument (or the two harness channels) named a different room than the harness; the union was used. */+ conflict: boolean;+ /** A channel was malformed (or present but empty): every item is unknown. */+ invalid: string | null;+}++const isObj = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);++function parseChannel(value: unknown, channel: string): AudiencePrincipal[] | { invalid: string } {+ if (typeof value === 'string') return normalizePrincipals(value.trim() === '' ? [] : value.split(',').map(s => s.trim()), channel);+ if (Array.isArray(value)) return normalizePrincipals(value, channel);+ return { invalid: `${channel} is not a list of member ids, group:<id> or guest` };+}++/**+ * The room a call declares, or null when it declares none, and the tool arguments with `room` removed (so no+ * handler, cache, retry call or stored write intent ever sees it). Never throws: a malformed or empty channel is a+ * declared room that could not be read (`invalid`), so the answer is still marked, all unknown.+ */+export function readRoomDeclaration(channels: RoomChannels | undefined, args: Record<string, unknown> | undefined): { declaration: RoomDeclaration | null; args: Record<string, unknown> | undefined } {+ const meta = isObj(channels?.requestMeta) ? channels!.requestMeta as Record<string, unknown> : null;+ const metaPresent = !!meta && Object.prototype.hasOwnProperty.call(meta, ROOM_ARGUMENT);+ const headerPresent = channels?.header !== undefined && channels?.header !== null;+ const argPresent = !!args && Object.prototype.hasOwnProperty.call(args, ROOM_ARGUMENT);+ let rest = args;+ if (argPresent) { const { [ROOM_ARGUMENT]: _dropped, ...others } = args!; rest = others; }+ if (!metaPresent && !headerPresent && !argPresent) return { declaration: null, args: rest };+ const parsed: Array<{ from: 'harness' | 'argument'; value: AudiencePrincipal[] | { invalid: string } }> = [];+ if (headerPresent) parsed.push({ from: 'harness', value: parseChannel(channels!.header, `the ${ROOM_HEADER} header`) });+ if (metaPresent) parsed.push({ from: 'harness', value: parseChannel(meta![ROOM_ARGUMENT], '_meta.room') });+ if (argPresent) parsed.push({ from: 'argument', value: parseChannel(args![ROOM_ARGUMENT], 'the room argument') });+ const invalid = parsed.find(p => 'invalid' in p.value);+ const lists = parsed.filter(p => Array.isArray(p.value)) as Array<{ from: 'harness' | 'argument'; value: AudiencePrincipal[] }>;+ const harness = lists.filter(p => p.from === 'harness');+ const principals = [...new Set(lists.flatMap(p => p.value))].sort() as AudiencePrincipal[];+ const keys = lists.map(p => p.value.join(','));+ return {+ declaration: {+ principals,+ declared_by: headerPresent || metaPresent ? 'harness' : 'argument',+ conflict: new Set(keys).size > 1 && (harness.length > 0 || lists.length > 1),+ invalid: invalid ? (invalid.value as { invalid: string }).invalid : null,+ },+ args: rest,+ };+}++type PageRef = { kind: 'page'; source_id: string; slug: string } | { kind: 'page_id'; id: number };+type FactRef = { kind: 'fact'; id: number };+type Ref = PageRef | FactRef;+interface Slot { holder: Record<string, unknown>; ref: Ref | null }++const str = (v: unknown) => typeof v === 'string' && v ? v : undefined;+const arr = (v: unknown): unknown[] => Array.isArray(v) ? v : [];+function pageSlot(o: unknown, src: string): Slot | null {+ if (!isObj(o)) return null;+ return { holder: o, ref: typeof o.slug === 'string' ? { kind: 'page', source_id: str(o.source_id) ?? src, slug: o.slug } : null };+}+function pageIdSlot(o: unknown): Slot | null {+ if (!isObj(o)) return null;+ return { holder: o, ref: typeof o.page_id === 'number' ? { kind: 'page_id', id: o.page_id } : null };+}+function factSlot(o: unknown): Slot | null {+ if (!isObj(o)) return null;+ return { holder: o, ref: typeof o.id === 'number' ? { kind: 'fact', id: o.id } : null };+}+function listOf(r: unknown): unknown[] {+ if (Array.isArray(r)) return r;+ if (isObj(r)) return Array.isArray(r.pages) ? r.pages : Array.isArray(r.results) ? r.results : [];+ return [];+}+const SKIP_KEYS = new Set(['next', 'arguments', 'fix', 'verify', 'coverage', '_meta', ROOM_ACCESS_KEY]);+/** entity and other composites: every object naming a page by slug, and every fact row in a `facts` list. */+function walk(v: unknown, src: string, out: Slot[], depth = 0): void {+ if (depth > 8) return;+ if (Array.isArray(v)) { for (const x of v) walk(x, src, out, depth + 1); return; }+ if (!isObj(v)) return;+ if (typeof v.slug === 'string') out.push(pageSlot(v, src)!);+ for (const [k, x] of Object.entries(v)) {+ if (SKIP_KEYS.has(k)) continue;+ if (k === 'facts' && Array.isArray(x)) { for (const f of x) { const s = factSlot(f); if (s) out.push(s); } continue; }+ walk(x, src, out, depth + 1);+ }+}++/** Read ops whose items room marking covers, and where their items are. Every other op answers op_not_covered. */+const EXTRACTORS: Record<string, (result: unknown, src: string) => Array<Slot | null>> = {+ get_page: (r, src) => [pageSlot(r, src)],+ search: (r, src) => listOf(r).map(i => pageSlot(i, src)),+ query: (r, src) => listOf(r).map(i => pageSlot(i, src)),+ list_pages: (r, src) => listOf(r).map(i => pageSlot(i, src)),+ find_pages: (r, src) => listOf(r).map(i => pageSlot(i, src)),+ get_chunks: r => arr(r).map(pageIdSlot),+ get_timeline: r => arr(r).map(pageIdSlot),+ get_backlinks: (r, src) => arr(r).map(i => isObj(i) && typeof i.from_slug === 'string'+ ? { holder: i, ref: { kind: 'page', source_id: str(i.from_source_id) ?? src, slug: i.from_slug } } : pageSlot(i, src)),+ recall: (r, src) => isObj(r) ? [...arr(r.facts).map(factSlot), ...arr(r.results).map(i => pageSlot(i, src))] : [],+ entity: (r, src) => { const out: Slot[] = []; walk(r, src, out); return out; },+};+export const ROOM_COVERED_OPS: ReadonlySet<string> = new Set(Object.keys(EXTRACTORS));++const refKey = (r: Ref) => r.kind === 'page' ? `p:${r.source_id}:${r.slug}` : r.kind === 'page_id' ? `i:${r.id}` : `f:${r.id}`;+const refOut = (r: Ref) => r.kind === 'page' ? { source_id: r.source_id, slug: r.slug } : r.kind === 'page_id' ? { page_id: r.id } : { fact_id: r.id };++interface PageRow { id: number; source_id: string; slug: string; ok: boolean; readers_ok: boolean; folder_ok: boolean; labelled_ok: boolean; privacy_ok: boolean }+interface FactRow { id: number; ok: boolean; world: boolean }++function pageReason(r: PageRow): RoomAccess {+ if (r.ok) return { readable: true };+ const reason: RoomReason = !r.readers_ok ? 'readers' : !r.folder_ok ? 'folder_rule' : !r.labelled_ok ? 'labelled_only' : !r.privacy_ok ? 'private_label' : 'derived';+ return { readable: false, reason };+}++/** The room's decisions for the refs, judged under the room's own access record (the same predicates its reads use). */+async function decide(engine: BrainEngine, access: Partial<CallerAccess>, refs: Ref[]): Promise<Map<string, RoomAccess>> {+ const pages = refs.filter((r): r is Extract<Ref, { kind: 'page' }> => r.kind === 'page');+ const ids = refs.filter((r): r is Extract<Ref, { kind: 'page_id' }> => r.kind === 'page_id').map(r => r.id);+ const facts = refs.filter((r): r is FactRef => r.kind === 'fact').map(r => r.id);+ const { pageSql, factSql } = withCallerAccess(access, () => {+ const room = currentCallerAccess();+ const readers = callerIdentities().map(identity => readersAllowedSql('p', identity)).join(' AND ');+ const labelled = room.labelledOnly ? labelledOnlyForSql('p', callerIdentities(), room.satisfiedRuleIds) : 'TRUE';+ return {+ pageSql: `SELECT p.id, p.source_id, p.slug, (${privatePagesFilterForCaller('p')}) AS ok, (${readers}) AS readers_ok,+ (${folderRulesAllowedSql('p', room.satisfiedRuleIds)}) AS folder_ok, (${labelled}) AS labelled_ok,+ (${privacyForCaller('p', privacyPartSql('p'))}) AS privacy_ok+ FROM pages p WHERE p.id = ANY($3::int[]) OR (p.source_id, p.slug) IN (SELECT u.s, u.g FROM unnest($1::text[], $2::text[]) AS u(s, g))`,+ factSql: `SELECT f.id, (${worldOnlyFacts(true) ? factVisibilitySql('f', ['world']) : 'TRUE'} AND ${privateProvenanceFilterUnderPolicy('f')}) AS ok,+ f.visibility = 'world' AS world FROM facts f WHERE f.id = ANY($1::int[])`,+ };+ });+ const out = new Map<string, RoomAccess>();+ if (pages.length || ids.length) {+ for (const row of await engine.executeRaw<PageRow>(pageSql, [pages.map(p => p.source_id), pages.map(p => p.slug), ids])) {+ const access = pageReason(row);+ out.set(`p:${row.source_id}:${row.slug}`, access);+ out.set(`i:${row.id}`, access);+ }+ }+ if (facts.length) {+ for (const row of await engine.executeRaw<FactRow>(factSql, [facts])) {+ out.set(`f:${row.id}`, row.ok ? { readable: true } : { readable: false, reason: row.world ? 'derived' : 'private_label' });+ }+ }+ return out;+}++/** Who asks for the marks: the call's own access record (the owner is exempt from may_act_for), credential and transport. */+export interface RoomCaller {+ access: CallerAccess;+ auth?: AuthInfo;+ transport?: string;+ stdioMember?: string;+ privateSources?: readonly string[];+ /** An attested actor call (x-qm-actor): never marked. */+ attested?: boolean;+}++export interface RoomMeta {+ principals: AudiencePrincipal[];+ declared_by: 'harness' | 'argument';+ conflict?: true;+ /** Every item was judged (true), or at least one is unknown (false). */+ complete: boolean;+ counts: { items: number; readable: number; above: number; unknown: number };+ by_reason: Record<string, number>;+ /** The refs of every item the room could not read or that is unknown, for a harness that tracks what entered a room. */+ above: Array<Record<string, unknown>>;+ /** Why no item could be judged, when that is the case. */+ unavailable?: RoomUnknownReason;+}++export interface RoomOutcome {+ /** A detached copy of the result with room_access on every item (the original object is never written). */+ result: unknown;+ meta: RoomMeta;+ notices: Notice[];+}++class RoomUnavailable extends Error {+ constructor(readonly reason: RoomUnknownReason, readonly detail?: string, readonly fix?: Action) { super(reason); }+}++async function roomAccessFor(engine: BrainEngine, caller: RoomCaller, principals: AudiencePrincipal[]): Promise<Partial<CallerAccess>> {+ if (caller.attested) throw new RoomUnavailable('unbound', 'an attested actor call is not marked for a room');+ const bound = caller.access.owner || caller.access.identity.some(p => p.startsWith('member:'));+ if (!bound) throw new RoomUnavailable('unbound', 'this connection is bound to no member, so it cannot ask what a room may read');+ let identities: string[][];+ try {+ identities = await resolveAudienceIdentities(engine, { auth: caller.auth, transport: caller.transport }, principals,+ { mayActFor: caller.access.owner ? 'owner_room_assessment' : 'enforce' });+ } catch (e) {+ const code = String((e as { code?: unknown }).code ?? '');+ const detail = e instanceof Error ? e.message.replace('so nothing was read', 'so the answer carries no room marks') : undefined;+ if (code === 'on_behalf_of_not_permitted') throw new RoomUnavailable('not_permitted', detail, (e as { fix?: Action }).fix);+ if (code === 'on_behalf_of_unknown_member') throw new RoomUnavailable('unknown_principal', detail);+ throw new RoomUnavailable('mark_failed');+ }+ return audienceCallerAccess(engine, caller.auth, caller.privateSources, caller.transport, principals, identities, caller.stdioMember, true);+}++function withDeadline<T>(p: Promise<T>, ms: number): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new RoomUnavailable('deadline')), ms); });+ return Promise.race([p, timeout]).finally(() => clearTimeout(timer));+}++const UNAVAILABLE_WHY: Record<RoomUnknownReason, string> = {+ invalid: 'The room this call declared could not be read',+ not_permitted: 'This connection may not ask what that room may read',+ unknown_principal: 'The room names someone who is not a member or group on this brain',+ unbound: 'This connection is bound to no member, so it cannot ask what a room may read',+ mark_failed: 'Judging what the room may read failed (retrying is safe; nothing was changed)',+ deadline: 'Judging what the room may read took too long (retrying is safe; nothing was changed)',+ op_not_covered: 'This tool does not mark its results for a room',+ not_found: 'Some items could not be found again to judge',+ not_identified: 'Some items carry no page or fact id to judge',+ over_limit: `More than ${ROOM_MAX_REFS} items were returned, so the rest were not judged`,+};++function emptyMeta(d: RoomDeclaration): RoomMeta {+ return { principals: d.principals, declared_by: d.declared_by, ...(d.conflict ? { conflict: true as const } : {}), complete: true,+ counts: { items: 0, readable: 0, above: 0, unknown: 0 }, by_reason: {}, above: [] };+}++/**+ * Marks `result` (and the given hot-memory payload) for the declared room. Never throws and never changes what the+ * result holds apart from adding room_access to its items: on any failure the items are marked unknown and a+ * room_hints_unavailable notice says why. Writes one count-only audit row.+ */+export async function assessRoom(engine: BrainEngine, input: { op: string; result: unknown; hotMemory?: unknown; declaration: RoomDeclaration; caller: RoomCaller; sourceId: string; deadlineMs?: number }): Promise<RoomOutcome & { hotMemory?: unknown }> {+ const { op, declaration: d, caller } = input;+ const meta = emptyMeta(d);+ const extractor = EXTRACTORS[op];+ const result = structuredClone(input.result);+ const hot = input.hotMemory === undefined ? undefined : structuredClone(input.hotMemory);+ const slots: Slot[] = extractor ? extractor(result, input.sourceId).filter((s): s is Slot => !!s) : [];+ if (isObj(hot) && isObj(hot.brain_hot_memory)) for (const f of arr(hot.brain_hot_memory.facts)) { const s = factSlot(f); if (s) slots.push(s); }+ let unavailable: RoomUnavailable | null = !extractor ? new RoomUnavailable('op_not_covered')+ : d.invalid ? new RoomUnavailable('invalid', d.invalid) : null;+ let decisions = new Map<string, RoomAccess>();+ const refs = new Map<string, Ref>();+ for (const s of slots) if (s.ref && refs.size < ROOM_MAX_REFS) refs.set(refKey(s.ref), s.ref);+ if (!unavailable && slots.length) {+ try {+ decisions = await withDeadline((async () => decide(engine, await roomAccessFor(engine, caller, d.principals), [...refs.values()]))(), input.deadlineMs ?? ROOM_DEADLINE_MS);+ } catch (e) {+ unavailable = e instanceof RoomUnavailable ? e : new RoomUnavailable('mark_failed');+ }+ }+ const listed = new Set<string>();+ for (const s of slots) {+ const key = s.ref ? refKey(s.ref) : null;+ const access: RoomAccess = unavailable ? { readable: 'unknown', reason: unavailable.reason }+ : !s.ref ? { readable: 'unknown', reason: 'not_identified' }+ : !refs.has(key!) ? { readable: 'unknown', reason: 'over_limit' }+ : decisions.get(key!) ?? { readable: 'unknown', reason: 'not_found' };+ s.holder[ROOM_ACCESS_KEY] = access;+ meta.counts.items++;+ if (access.readable === true) { meta.counts.readable++; continue; }+ if (access.readable === false) { meta.counts.above++; meta.by_reason[access.reason] = (meta.by_reason[access.reason] ?? 0) + 1; }+ else meta.counts.unknown++;+ if (s.ref && !listed.has(refKey(s.ref))) {+ listed.add(refKey(s.ref));+ meta.above.push({ ...refOut(s.ref), ...(access.readable === 'unknown' ? { unknown: access.reason } : { reason: access.reason }) });+ }+ }+ if (unavailable) { meta.unavailable = unavailable.reason; meta.complete = false; }+ if (meta.counts.unknown > 0) meta.complete = false;+ const notices: Notice[] = [];+ if (d.conflict) notices.push({ code: 'room_conflict', kind: 'safety',+ why: `The room named in the tool arguments differs from the room the harness declared, so the answer was marked for everyone either names (${d.principals.join(', ')}). The arguments can add people to the harness's room, never remove them.` });+ if (unavailable) notices.push({ code: 'room_hints_unavailable', kind: 'degraded',+ why: `${UNAVAILABLE_WHY[unavailable.reason]}${unavailable.detail ? ` (${unavailable.detail})` : ''}. The answer is complete; every item is marked unknown, so treat all of it as above this room's level: use it for the work, keep it out of the reply unless the ask needs it, and offer it in a private chat. [reason: ${unavailable.reason}]`,+ ...(unavailable.fix ? { fix: unavailable.fix } : {}) });+ if (!unavailable && meta.counts.above + meta.counts.unknown > 0) {+ const reasons = Object.entries(meta.by_reason).map(([k, n]) => `${n} ${k}`).join(', ');+ notices.push({ code: 'room_above_level', kind: 'safety',+ why: `This answer goes into a room (${d.principals.join(', ')}). ${meta.counts.above} of ${meta.counts.items} items are above the room's level${reasons ? ` (${reasons})` : ''}${meta.counts.unknown ? ` and ${meta.counts.unknown} could not be judged` : ''}; their room_access says so. Use them to do the work. Keep them out of the reply unless the ask needs them, and offer the rest in a private chat. Never refuse the work because of them.` });+ }+ logAudienceAssertion({ outcome: 'room_marked', op, audience: [...d.principals], transport: caller.transport ?? 'unknown',+ principal: caller.auth?.principal ? `${caller.auth.principal.kind}:${caller.auth.principal.id}` : caller.transport === 'stdio' ? 'local_stdio' : 'unknown',+ room: { readable: meta.counts.readable, above: meta.counts.above, unknown: meta.counts.unknown, by_reason: { ...meta.by_reason }, declared_by: d.declared_by,+ ...(meta.unavailable ? { unavailable: meta.unavailable } : {}) } });+ return { result, meta, notices, ...(hot !== undefined ? { hotMemory: hot } : {}) };+}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 65213d05d6..3a46c8bbfa 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -1008,6 +1008,9 @@ export const NOTICE_CODES = {hosted_option: { kind: 'coaching', summary: 'Shown when gbrain setup or an in-agent install creates a brain, and when gbrain mcp expose writes its first receipt or stops at a Tailscale or service step: gbrain.io is hosted GBrain. Mute with `gbrain notices mute hosted_option`.' },backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },+ room_above_level: { kind: 'safety', summary: 'The answer goes into a shared room (a harness declared it with X-Gbrain-Room, _meta.room or a room argument) and some items carry room_access readable false or unknown: the room could not have read them itself. Use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a private chat; never refuse the work. docs/guides/rooms.md' },+ room_hints_unavailable: { kind: 'degraded', summary: 'A room was declared but its marks could not be computed (reason: invalid, not_permitted, unknown_principal, unbound, mark_failed, deadline, op_not_covered): the answer is complete and every item is marked unknown, so treat all of it as above the room. docs/guides/rooms.md#when-marks-are-unavailable' },+ room_conflict: { kind: 'safety', summary: 'The room argument named a different room than the harness declared (X-Gbrain-Room or _meta.room); the answer was marked for everyone either names, because an argument can only add people. docs/guides/rooms.md#channels' },first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex ecc329fec0..3d88daa730 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -34,7 +34,7 @@ export const COACHING_BUDGET_PER_SESSION = 2;/** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);/** Notices that describe THIS call's result (never deduped unless the notice carries a `dedupe_key`): the diagnosis must ride every affected call. */-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'graph_walk_truncated', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'references_unavailable', 'record_types_undeclared', 'alias_fanout', 'facts_unembedded', 'loops_no_google_in_scope', 'privacy_label_ignored', 'loops_source_read_failed']);+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'graph_walk_truncated', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'references_unavailable', 'record_types_undeclared', 'alias_fanout', 'facts_unembedded', 'loops_no_google_in_scope', 'privacy_label_ignored', 'loops_source_read_failed', 'room_above_level', 'room_hints_unavailable', 'room_conflict']);/** How long a shown coverage state (a notice's `escalation`) stays shown. */export const COVERAGE_NOTICE_WINDOW_MS = 30 * 60 * 1000;diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex 65d70d8c48..fd74444f6e 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -28,6 +28,9 @@ function managedLifecycleRefusal(ctx: OperationContext, args: string[]) {'With managed persistence on, adding or removing a source changes the brain\'s writer topology, which only its owner CLI may do.');}+/** GBRA-498: what this server supports, so a harness checks once per connection (room: room-aware results, access/room.ts). */+const WHOAMI_FEATURES = { room: true } as const;+const whoami: Operation = {name: 'whoami',mutating: false,@@ -62,7 +65,7 @@ const whoami: Operation = {// GBRA-218: a local --as <member> preview reports the member it reads as; the plain local CLI reads every page.const access = ctx.applyRemoteReadPolicy && ctx.accessIdentity?.length ? accessView(ctx.accessIdentity, 'as'): accessView([], 'none', null, 'The local CLI reads every page; pass --as <member> to preview what a member can read.');- return { transport: 'local', scopes: [], access, readiness: readiness('cli') };+ return { transport: 'local', scopes: [], features: WHOAMI_FEATURES, access, readiness: readiness('cli') };}// #1061: stdio MCP is remote/untrusted by design but has no per-token// auth (local pipe) — a known transport, not a bug. Report it instead of@@ -76,7 +79,7 @@ const whoami: Operation = {if (verified.remote) scopes = verified.grant.scopes;} catch { /* no registration: no scopes */ }const session = ctx.stdioSurface;- return { transport: 'stdio', scopes, ...(session ? { surface: session.surface, surface_source: session.source } : {}), access: await withApplied(await stdioAccessView(ctx.engine, ctx.stdioMember)), readiness: readiness('stdio') };+ return { transport: 'stdio', scopes, features: WHOAMI_FEATURES, ...(session ? { surface: session.surface, surface_source: session.source } : {}), access: await withApplied(await stdioAccessView(ctx.engine, ctx.stdioMember)), readiness: readiness('stdio') };}if (!ctx.auth) {throw opError(@@ -92,6 +95,7 @@ const whoami: Operation = {if (authTransport(ctx.auth) === 'oauth') {return {transport: 'oauth',+ features: WHOAMI_FEATURES,client_id: ctx.auth.clientId,client_name: ctx.auth.clientName ?? ctx.auth.clientId,...await resolveAuthCapabilities(ctx.auth, ctx.engine, ctx.config, { surfaceCeiling: ctx.surfaceCeiling }),@@ -100,6 +104,7 @@ const whoami: Operation = {}return {transport: 'legacy',+ features: WHOAMI_FEATURES,token_name: ctx.auth.clientName ?? ctx.auth.clientId,scopes: ctx.auth.scopes,expires_at: null,diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex f463d80116..145f072c6b 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -15,9 +15,10 @@ import { asSegmentedWriteRefusal } from '../core/page-body/page-shape.ts';import type { Operation, OperationMeta } from '../core/ops/contract.ts';import { loadConfig } from '../core/config.ts';import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';-import { withCallerAccess } from '../core/search/private-visibility.ts';+import { currentCallerAccess, withCallerAccess } from '../core/search/private-visibility.ts';import { appliedAccessSummary, folderAccessFor, identityLookupUnavailable, remoteCallerAccess } from '../core/access/caller.ts';import { credentialScopeFor, requesterScopeGate, requesterScopeRefuses, requiresRequesterScope, withServesReread, type RequesterScopeNotice } from '../core/access/requester-scope.ts';+import { assessRoom, readRoomDeclaration, type RoomChannels, type RoomDeclaration } from '../core/access/room.ts';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, scopeReadLabelledOnlyRefused, withReadMode, type ReadMode } from '../core/access/scope-read.ts';@@ -188,6 +189,17 @@ export interface DispatchOpts {* header, request-level `_meta`), set by harness code. Never populated from tool arguments, which are refused.*/onBehalfOf?: AudienceChannels;+ /**+ * GBRA-498: the room channels the transport read (the X-Gbrain-Room header, request-level _meta.room), set by harness+ * code. A `room` tool argument is read too, and can only add people (access/room.ts).+ */+ room?: RoomChannels;+ /** GBRA-498 (internal): the room this call declared, resolved by dispatchToolCall; never set by a transport. */+ roomDeclaration?: RoomDeclaration;+ /** GBRA-498 (internal): the call named an attested actor, so its answer is never marked for a room. */+ roomAttested?: boolean;+ /** GBRA-498 (internal): the private-readable sources of the call's grant, for the room's own access record. */+ roomPrivateSources?: readonly string[];/** #6696 (A5): set by the trusted transport for the user's own agent calls; never from wire params. */admissionOrigin?: OperationContext['admissionOrigin'];/** The caller's self-declared agent label (X-Gbrain-Agent-Label), parsed by the transport; recorded only, never authority. */@@ -1002,6 +1014,11 @@ export async function dispatchToolCall(// GBRA-156: a remote read sees private pages only in the sources its grant names under private_pages: granted_sources.// Writes, local callers and every path outside this call keep the empty set, so they hide or see exactly what they did.// context_pack and delta stay world-only for every caller unless a trusted local one passes include_private, so no grant widens them.+ // GBRA-498: a room declaration only marks the answer; its argument is taken out here, before any validation,+ // handler, cache, retry call or stored write intent sees it, and a trusted local caller's is ignored.+ const roomRead = readRoomDeclaration(opts.remote === false ? undefined : opts.room, params);+ params = roomRead.args;+ const roomDeclaration = opts.remote === false ? undefined : roomRead.declaration ?? undefined;const op = operations.find(o => o.name === name);const readOnly = op?.mutating === false;const args = op && params ? normalizeOptionalParams(op, params) : params;@@ -1035,6 +1052,7 @@ export async function dispatchToolCall(access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(engine, [])).folderCoverage } : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience, opts.transport === 'stdio' && !opts.auth ? opts.stdioMember : undefined, readOnly);// 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');+ if (roomDeclaration) scoped = { ...scoped, roomDeclaration, roomAttested: !!attested?.actor, ...(privateSources ? { roomPrivateSources: privateSources } : {}) };if (opts.enforcedMember) access = { ...access, hidePrivate: true, owner: false, privateReadableSources: [] };// GST-363: on a brain that serves several people, a read from a connection bound to nobody is refused (or, in its grace, noticed) before any work.// An op this connection cannot reach (hidden by its surface, localOnly off stdio, or cliOnly over MCP) keeps its own refusal instead.@@ -1139,6 +1157,42 @@ async function runMetaHook(hook: NonNullable<DispatchOpts['metaHook']>, name: stcatch (metaErr) { return { failure: metaErr instanceof Error ? metaErr.message : String(metaErr) }; }}+/**+ * GBRA-498: an answer going into a room is marked for it on a detached copy (hot memory too, so the hook runs first),+ * before the notices, the degraded stamp and the frame are built. Marking never fails the call.+ */+async function markForRoom(engine: BrainEngine, opts: DispatchOpts, name: string, result: unknown, ctx: OperationContext, hook: ReturnType<typeof runMetaHook> | undefined) {+ const hookOut = hook ? await hook : undefined;+ const room = await assessRoom(engine, { op: name, result, hotMemory: hookOut?.meta, declaration: opts.roomDeclaration!, sourceId: ctx.sourceId,+ caller: { access: currentCallerAccess(), auth: ctx.auth, transport: ctx.transport, stdioMember: opts.stdioMember, privateSources: opts.roomPrivateSources, attested: opts.roomAttested } });+ return { hookOut, room: room as Awaited<ReturnType<typeof assessRoom>> | null };+}++/** GBRA-498: room marks never cost a read: over the cap, the unmarked answer goes out with a one-key note, then without it. */+async function roomCapFallback(build: (meta: Record<string, unknown>) => ToolResult, cap: (built: ToolResult) => Promise<unknown>, responseMeta: Record<string, unknown>): Promise<ToolResult | null> {+ for (const meta of [{ ...responseMeta, room: { complete: false, unavailable: 'response_cap' } }, responseMeta]) {+ const fallback = build(meta);+ if (!await cap(fallback)) return fallback;+ }+ return null;+}++function assembleToolResult(+ call: { name: string; result: unknown; batchError: boolean; evidenceBlocks: string[]; tail: ToolTail | undefined; opts: DispatchOpts },+ body: unknown, shown: Notice[], stamped: Notice[], meta: Record<string, unknown>, hook: Record<string, unknown> | undefined,+): ToolResult {+ const built: ToolResult = call.batchError ? toolErrorResult(body as never) : toolResultWithNotices(body, shown, dispatchRenderContext(call.opts));+ if (call.evidenceBlocks.length > 0) built.content.splice(1, 0, ...call.evidenceBlocks.map(text => ({ type: 'text' as const, text })));+ // _meta assembly (WP2 amendment 9): one producer per top-level key,+ // each isolated — handler-emitted keys (retrieval, warnings) attach+ // BEFORE and independently of the metaHook, so a hot-memory hook+ // failure can never drop the retrieval channel. Per-key merge, never+ // wholesale assignment. See docs/protocol/MCP_META_CHANNELS.md.+ attachResponseMeta(built, meta, degradedStampFor(call.name, call.result, meta, stamped)); if (call.tail) appendToolTail(built, call.tail);+ if (hook && Object.keys(hook).length > 0) built._meta = { ...(built._meta ?? {}), ...hook };+ return built;+}+async function dispatchResolvedCall(engine: BrainEngine,name: string,@@ -1399,28 +1453,27 @@ async function dispatchResolvedCall(if (opts.transport === 'stdio' && opts.remote !== false && !batchError) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));if (opts.transport === 'stdio' && opts.remote !== false && !batchError) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drainif (!batchError) notices.push(...await sessionSafetyNotices(engine, opts, ctx.config), ...await grantBlockedNotices(engine, opts, false));- const out: ToolResult = batchError ? toolErrorResult(result as never) : toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));- if (evidenceBlocks.length > 0) out.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));+ let { hookOut, room } = opts.roomDeclaration && ctx.remote !== false && !batchError ? await markForRoom(engine, opts, name, result, ctx, metaHook && (earlyMeta ?? runMetaHook(metaHook, name, ctx))) : { hookOut: undefined, room: null };+ const admitted = admitNotices(room ? [...notices, ...room.notices] : notices, opts);+ const assemble = (body: unknown, shown: Notice[], stamped: Notice[], meta: Record<string, unknown>, hook: Record<string, unknown> | undefined) =>+ assembleToolResult({ name, result, batchError, evidenceBlocks, tail, opts }, body, shown, stamped, meta, hook);if (opts.transport === 'stdio') {maybeRefreshBackupStatusInProcess(engine);}- // _meta assembly (WP2 amendment 9): one producer per top-level key,- // each isolated — handler-emitted keys (retrieval, warnings) attach- // BEFORE and independently of the metaHook, so a hot-memory hook- // failure can never drop the retrieval channel. Per-key merge, never- // wholesale assignment. See docs/protocol/MCP_META_CHANNELS.md.- attachResponseMeta(out, responseMeta, degradedStampFor(name, result, responseMeta, notices)); if (tail) appendToolTail(out, tail);// v0.31 (eD3 + eE4): best-effort _meta.brain_hot_memory injection.// The hook is wrapped in its own try/catch — any DB blip / cache miss /// helper crash degrades to no hook keys rather than flipping the whole// tool call to error.- if (metaHook) {- const { meta, failure } = await (earlyMeta ?? runMetaHook(metaHook, name, ctx));- if (meta && Object.keys(meta).length > 0) out._meta = { ...(out._meta ?? {}), ...meta };- if (failure !== undefined) ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${failure}; degrading to no hook keys`);- }+ if (metaHook && !hookOut) hookOut = await (earlyMeta ?? runMetaHook(metaHook, name, ctx));+ if (hookOut?.failure !== undefined) ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${hookOut.failure}; degrading to no hook keys`);+ const cap = (built: ToolResult) => op.mutating ? Promise.resolve(null) : frameOverCap(built, { remote: ctx.remote, transport: ctx.transport, engine, config: ctx.config });+ const out = room+ ? assemble(room.result, admitted, [...notices, ...room.notices], { ...responseMeta, room: room.meta }, (room.hotMemory ?? hookOut?.meta) as Record<string, unknown> | undefined)+ : assemble(result, admitted, notices, responseMeta, hookOut?.meta);// Large pages: the egress backstop measures the final frame; a read over the connection's cap is refused whole, never cut.- const over = op.mutating ? null : await frameOverCap(out, { remote: ctx.remote, transport: ctx.transport, engine, config: ctx.config });+ const over = await cap(out);+ const fallback = over && room ? await roomCapFallback(meta => assemble(result, admitted.filter(n => !n.code.startsWith('room_')), notices, meta, hookOut?.meta), cap, responseMeta) : null;+ if (fallback) return fallback;if (over) return errorResult(resultTooLargeError(name, safeParams, over), opts, { op: name, mutating: false, idempotent: op.idempotent === true });return out;} catch (thrown: unknown) {diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 1b56cb1c34..9ca29ef2c0 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -40,6 +40,7 @@ import { OWNER_MEMBER_KEY } from '../core/search/private-visibility.ts';import { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';import { scopeDeniedError } from '../core/ops/op-fix.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';+import { ROOM_HEADER } from '../core/access/room.ts';import { ACTOR_HEADER, QM_AUDIENCE_HEADER, withAttestRight } from '../core/access/actor-model.ts';import { parseAgentLabel, AGENT_LABEL_HEADER } from '../core/persistence/attribution.ts';import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';@@ -570,7 +571,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {transport: 'http', inboundFrameBytes: bodyCap,takesHoldersAllowList: auth.takesHoldersAllowList,sourceId: auth.sourceId, agentLabel: parseAgentLabel(req.headers.get(AGENT_LABEL_HEADER)),- ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta }, mcpCaller: { client: auth.auth?.clientName, userAgent: req.headers.get('user-agent') ?? undefined, meta: params?._meta },+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta }, room: { header: req.headers.get(ROOM_HEADER) ?? undefined, requestMeta: params?._meta }, mcpCaller: { client: auth.auth?.clientName, userAgent: req.headers.get('user-agent') ?? undefined, meta: params?._meta },actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined, audience: req.headers.get(QM_AUDIENCE_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope// to the operator-granted sources via sourceScopeOpts.auth: auth.auth,diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 5df052d2c5..b2a9dd8efe 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -511,7 +511,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// stdio stays remote/untrusted.transport: 'stdio', inboundFrameBytes: MCP_STDIO_MAX_MESSAGE_BYTES,takesHoldersAllowList: ['world'],- ...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}), onBehalfOf: { requestMeta: request.params?._meta },+ ...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}), onBehalfOf: { requestMeta: request.params?._meta }, room: { requestMeta: request.params?._meta },mcpCaller: { client: server?.getClientVersion()?.name, meta: request.params?._meta },sourceId: sourceScope.sourceId,...(sourceScope.localFederatedSourceIdsdiff --git a/src/mcp/tool-defs.ts b/src/mcp/tool-defs.tsindex c80a337ed8..635ad6d3db 100644--- a/src/mcp/tool-defs.ts+++ b/src/mcp/tool-defs.ts@@ -74,6 +74,13 @@ function strictPassthroughProperties(op: OperationMeta): Record<string, unknown>},}),...('dry_run' in op.params ? {} : { dry_run: { type: 'boolean' } }),+ ...('room' in op.params ? {} : {+ room: {+ type: 'array',+ items: { type: 'string' },+ description: 'Set by the harness: who is in the shared chat this answer goes to. Hints only; never changes what is read.',+ },+ }),};}diff --git a/test/access-room.test.ts b/test/access-room.test.tsnew file mode 100644index 0000000000..e08d1c5bf6--- /dev/null+++ b/test/access-room.test.ts@@ -0,0 +1,310 @@+/**+ * GBRA-498: room-aware results. The owner's own turn in a shared room reads at the owner's scope; the harness names+ * the room (X-Gbrain-Room, request-level _meta.room, or a room argument that can only add people) and every returned+ * item carries room_access: whether the room could have read it itself, and why not.+ *+ * 1. Protects: the three rules no change may bend (a room never refuses, shortens or fails a read; with no room the+ * answer is unchanged; nothing changes what any caller reads), the decision matching an on_behalf_of read of the+ * same room exactly, the reason classes, the owner's exemption from may_act_for staying out of on_behalf_of,+ * injected argument text never shrinking the harness's room, the room argument never reaching a handler or a+ * write, the count-only audit row, and whoami advertising the feature.+ * 2. Fails when: a room drops, reorders or refuses an item; an item the room cannot read reads as readable; a room+ * argument naming a smaller room changes a mark; the owner's room exemption lets on_behalf_of through; the audit+ * row carries a slug; a write rejects or stores the room argument.+ * 3. Real seams: legacy tokens minted and bound by the member functions, verified by the OAuth provider, dispatched+ * through MCP dispatch on a repo-less brain (no git checkout; folder rules in the database store); embeddings stubbed.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readdirSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+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 { mintLegacyToken } from '../src/core/token-mint.ts';+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { buildToolDefs } from '../src/mcp/tool-defs.ts';+import { operations } from '../src/core/operations.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { addGroup, addMember, bindCredential } from '../src/core/access/members.ts';+import { setOwner } from '../src/core/access/owner.ts';+import { setMemberLabelledOnly } from '../src/core/access/labelled-only.ts';+import { proposeRevision } from '../src/core/access/policy.ts';+import { readRoomDeclaration, ROOM_COVERED_OPS } from '../src/core/access/room.ts';+import { EGRESS_CAP_MIN, encodedFrameBytes } from '../src/core/egress-budget.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.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 = 'room-team';+const PAGES = {+ open: { slug: 'notes/open-plan', fm: [] as string[] },+ quiet: { slug: 'notes/quiet-plan', fm: ['visibility: private'] },+ mine: { slug: 'notes/owner-plan', fm: ['readable_by: [owner-example]'] },+ team: { slug: 'notes/team-plan', fm: ['readable_by: [group:team-a]'] },+ folder: { slug: 'partners/owner-example/brief', fm: [] as string[] },+ derived: { slug: 'notes/derived-plan', fm: ['derived_from: [notes/owner-plan]'], type: 'concept' },+} as const;+type Key = keyof typeof PAGES;+const page = (key: Key) => ['---', 'type: ' + ('type' in PAGES[key] ? (PAGES[key] as { type: string }).type : 'note'), 'title: ' + key + ' plan', ...PAGES[key].fm, '---',+ '# ' + key + ' plan', '', 'Harbor ledger planning notes for the roadmap.'].join('\n');++type Channels = { header?: string; meta?: unknown };+type Called = { isError: boolean; text: string; json: unknown; meta: Record<string, unknown> | undefined; blocks: string[]; raw: ToolResult };++/** content[0] with every room_access key removed, so a marked answer compares with an unmarked one. */+function unmarked(v: unknown): unknown {+ if (Array.isArray(v)) return v.map(unmarked);+ if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).filter(([k]) => k !== 'room_access').map(([k, x]) => [k, unmarked(x)]));+ return v;+}+/** slug -> room_access for every top-level item (an array, or an object's pages/results list, or the object itself). */+function marks(json: unknown): Record<string, unknown> {+ const items = Array.isArray(json) ? json : json && typeof json === 'object' ? ((json as { pages?: unknown[]; results?: unknown[] }).pages ?? (json as { results?: unknown[] }).results ?? [json]) : [];+ return Object.fromEntries((items as Array<Record<string, unknown>>).filter(i => typeof i?.slug === 'string').map(i => [i.slug as string, i.room_access]));+}++for (const kind of testBackends()) {+ describe('room-aware results (' + kind + ', repo-less)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let auditDir: string;+ const tokens: Record<string, { id: string; token: string }> = {};+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const verify = async (who: string) => await provider().verifyAccessToken(tokens[who]!.token) as unknown as AuthInfo;++ async function call(who: string | null, op: string, params: Record<string, unknown>, opts: { room?: Channels; obo?: Channels } = {}): Promise<Called> {+ const auth = who ? await verify(who) : undefined;+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: who ? 'http' : 'stdio', auth, sourceId: SRC, takesHoldersAllowList: ['world'],+ ...(opts.room ? { room: { header: opts.room.header, requestMeta: opts.room.meta === undefined ? undefined : { room: opts.room.meta } } } : {}),+ ...(opts.obo ? { onBehalfOf: { header: opts.obo.header, requestMeta: opts.obo.meta === undefined ? undefined : { on_behalf_of: opts.obo.meta } } } : {}),+ });+ const text = out.content[0]!.text;+ let json: unknown = null;+ try { json = JSON.parse(text); } catch { /* prose */ }+ return { isError: out.isError === true, text, json, meta: out._meta, blocks: out.content.slice(1).map(c => c.text), raw: out };+ }++ const READS: Array<[string, Record<string, unknown>]> = [+ ['search', { query: 'harbor ledger planning', match: 'keyword', limit: 20 }],+ ['list_pages', { limit: 50 }],+ ['find_pages', { pattern: 'notes/' }],+ ['get_page', { slug: PAGES.mine.slug }],+ ['get_chunks', { slug: PAGES.quiet.slug }],+ ['recall', { entity: PAGES.open.slug }],+ ];++ beforeAll(async () => {+ auditDir = mkdtempSync(join(tmpdir(), 'gbrain-room-audit-'));+ 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();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ for (const id of ['owner-example', 'alice-example', 'bob-example', 'carol-example']) await addMember(engine, id);+ await addGroup(engine, 'team-a', ['bob-example', 'owner-example']);+ await setOwner(engine, 'owner-example');+ await setMemberLabelledOnly(engine, 'carol-example', true, { remote: false });+ await proposeRevision(engine, SRC, [{ id: 'owner-partners', prefix: 'partners/owner-example/', readable_by: ['member:owner-example'] }], { origin: 'cli', store: 'database' });+ for (const key of Object.keys(PAGES) as Key[]) await importFromContent(engine, PAGES[key].slug, page(key), { sourceId: SRC });+ const mint = async (name: string, binding: { member?: string; mayActFor?: string[] }, scopes = ['read', 'write']) => {+ const minted = await mintLegacyToken(engine, { name, scopes, takesHolders: ['world'], sourceGrant: [SRC] });+ tokens[name] = { id: minted.id, token: minted.token };+ if (binding.member || binding.mayActFor) await bindCredential(engine, { kind: 'token', id: minted.id }, binding);+ if (!binding.member) await readsUnscopedOnPurpose(engine, minted.id);+ };+ await mint('owner', { member: 'owner-example' });+ await mint('bot', { mayActFor: ['*'] });+ await mint('bob', { member: 'bob-example' });+ await mint('bob-room', { member: 'bob-example', mayActFor: ['group:team-a'] });+ await mint('plain', {});+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ for (const visibility of ['world', 'private']) {+ const out = await call('owner', 'remember', { fact: 'Harbor ledger ' + visibility + ' note', entity: PAGES.open.slug, visibility, provenance: 'room test', content_origin: 'user_said' });+ expect(out.isError).toBe(false);+ }+ });+ }, 240_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('rule 1: a room never refuses, shortens, reorders or fails a read, whatever the room or the caller', async () => {+ const rooms: Array<[string, { room: Channels }]> = [+ ['owner, group room', { room: { header: 'group:team-a' } }],+ ['owner, guest', { room: { meta: ['guest'] } }],+ ['owner, malformed', { room: { header: 'Not Valid' } }],+ ['owner, empty', { room: { meta: [] } }],+ ['owner, null', { room: { meta: null } }],+ ['owner, unknown member', { room: { header: 'zed-example' } }],+ ];+ for (const [op, params] of READS) {+ const plain = await call('owner', op, params);+ expect({ op, isError: plain.isError }).toEqual({ op, isError: false });+ for (const [label, opts] of rooms) {+ const marked = await call('owner', op, params, opts);+ expect({ op, label, isError: marked.isError }).toEqual({ op, label, isError: false });+ expect({ op, label, body: unmarked(marked.json) }).toEqual({ op, label, body: plain.json });+ }+ for (const who of ['bob', 'plain']) {+ const base = await call(who, op, params);+ const marked = await call(who, op, params, { room: { header: 'group:team-a' } });+ expect({ op, who, isError: marked.isError, body: unmarked(marked.json) }).toEqual({ op, who, isError: base.isError, body: base.json });+ }+ }+ }, 240_000);++ test('rule 2: with no room the answer carries no room key, mark or notice', async () => {+ for (const [op, params] of READS) {+ const out = await call('owner', op, params);+ expect({ op, marked: out.text.includes('room_access'), meta: out.meta?.room, notice: out.blocks.some(b => b.includes('notice room_')) })+ .toEqual({ op, marked: false, meta: undefined, notice: false });+ }+ const defs = buildToolDefs(operations.filter(o => ROOM_COVERED_OPS.has(o.name)));+ for (const def of defs) expect({ tool: def.name, room: 'room' in def.inputSchema.properties }).toEqual({ tool: def.name, room: false });+ for (const def of buildToolDefs(operations.filter(o => ROOM_COVERED_OPS.has(o.name)), { strictParams: true })) expect({ tool: def.name, room: 'room' in def.inputSchema.properties }).toEqual({ tool: def.name, room: true });+ }, 120_000);++ test('the owner reads everything; each item says whether the room could have read it, and why not', async () => {+ const out = await call('owner', 'list_pages', { limit: 50 }, { room: { header: 'group:team-a' } });+ expect(marks(out.json)).toEqual({+ 'memory/members/owner-example': { readable: false, reason: 'readers' },+ [PAGES.open.slug]: { readable: true },+ [PAGES.team.slug]: { readable: true },+ [PAGES.quiet.slug]: { readable: false, reason: 'private_label' },+ [PAGES.mine.slug]: { readable: false, reason: 'readers' },+ [PAGES.folder.slug]: { readable: false, reason: 'folder_rule' },+ [PAGES.derived.slug]: { readable: false, reason: 'derived' },+ });+ const room = out.meta?.room as Record<string, unknown>;+ expect(room).toMatchObject({ principals: ['group:team-a'], declared_by: 'harness', complete: true, counts: { items: 7, readable: 2, above: 5, unknown: 0 } });+ expect(out.blocks.find(b => b.startsWith('[gbrain notice room_above_level kind=safety]'))).toContain('Use them to do the work');+ const labelled = await call('owner', 'list_pages', { limit: 50 }, { room: { header: 'carol-example' } });+ expect(marks(labelled.json)[PAGES.open.slug]).toEqual({ readable: false, reason: 'labelled_only' });+ const facts = await call('owner', 'recall', { entity: PAGES.open.slug }, { room: { header: 'group:team-a' } });+ const rows = (facts.json as { facts: Array<{ visibility: string; room_access: unknown }> }).facts;+ expect(rows.map(f => [f.visibility, f.room_access]).sort()).toEqual([['private', { readable: false, reason: 'private_label' }], ['world', { readable: true }]]);+ }, 120_000);++ test('readable: true means exactly what an on_behalf_of read of the same room returns', async () => {+ const rooms = ['group:team-a', 'carol-example', 'guest', 'alice-example, group:team-a', 'owner-example'];+ for (const room of rooms) {+ for (const [op, params] of [['list_pages', { limit: 50 }], ['search', { query: 'harbor ledger planning', match: 'keyword', limit: 20 }]] as const) {+ const marked = await call('owner', op, params, { room: { header: room } });+ const readable = Object.entries(marks(marked.json)).filter(([, a]) => (a as { readable: unknown }).readable === true).map(([s]) => s).sort();+ // A room of the owner alone is a direct chat: the owner's own read is the reference.+ const asRoom = room === 'owner-example' ? await call('owner', op, params) : await call('bot', op, params, { obo: { header: room } });+ expect({ room, op, readable }).toEqual({ room, op, readable: Object.keys(marks(asRoom.json)).sort() });+ }+ for (const key of Object.keys(PAGES) as Key[]) {+ const marked = await call('owner', 'get_page', { slug: PAGES[key].slug }, { room: { header: room } });+ const asRoom = room === 'owner-example' ? await call('owner', 'get_page', { slug: PAGES[key].slug }) : await call('bot', 'get_page', { slug: PAGES[key].slug }, { obo: { header: room } });+ expect({ room, key, readable: ((marked.json as { room_access: { readable: unknown } }).room_access.readable === true) }).toEqual({ room, key, readable: !asRoom.isError });+ }+ }+ }, 240_000);++ test('injected argument text naming a smaller room changes nothing but the notice', async () => {+ const harness = await call('owner', 'list_pages', { limit: 50 }, { room: { header: 'group:team-a' } });+ const injected = await call('owner', 'list_pages', { limit: 50, room: ['owner-example'] }, { room: { header: 'group:team-a' } });+ expect(injected.json).toEqual(harness.json);+ expect((injected.meta?.room as { conflict?: boolean }).conflict).toBe(true);+ expect(injected.blocks.some(b => b.startsWith('[gbrain notice room_conflict kind=safety]'))).toBe(true);+ const both = await call('owner', 'list_pages', { limit: 50 }, { room: { header: 'group:team-a', meta: ['owner-example'] } });+ expect(both.json).toEqual(harness.json);+ const argumentOnly = await call('owner', 'list_pages', { limit: 50, room: ['group:team-a'] });+ expect(argumentOnly.json).toEqual(harness.json);+ expect((argumentOnly.meta?.room as { declared_by: string }).declared_by).toBe('argument');+ expect(readRoomDeclaration({ header: 'group:team-a' }, { room: ['alice-example'] }).declaration?.principals).toEqual(['group:team-a', 'member:alice-example']);+ }, 120_000);++ test('who may ask: the owner needs no may_act_for, a member needs it, an unbound connection gets no marks', async () => {+ const bob = await call('bob', 'list_pages', { limit: 50 }, { room: { header: 'group:team-a' } });+ expect((bob.meta?.room as { unavailable?: string }).unavailable).toBe('not_permitted');+ expect(Object.values(marks(bob.json)).every(a => (a as { readable: unknown }).readable === 'unknown')).toBe(true);+ expect(bob.blocks.some(b => b.startsWith('[gbrain notice room_hints_unavailable kind=degraded]'))).toBe(true);+ const bobRoom = await call('bob-room', 'list_pages', { limit: 50 }, { room: { header: 'group:team-a' } });+ expect((bobRoom.meta?.room as { complete: boolean }).complete).toBe(true);+ const plain = await call('plain', 'list_pages', { limit: 50 }, { room: { header: 'group:team-a' } });+ expect((plain.meta?.room as { unavailable?: string }).unavailable).toBe('unbound');+ }, 120_000);++ test('rule 3: the owner\'s room exemption never lets an on_behalf_of read through', async () => {+ const out = await call('owner', 'get_page', { slug: PAGES.team.slug }, { obo: { header: 'group:team-a' } });+ expect({ isError: out.isError, code: (out.json as { code?: string }).code }).toEqual({ isError: true, code: 'on_behalf_of_not_permitted' });+ }, 60_000);++ test('the room argument never reaches a handler: a write with one succeeds and stores nothing of it', async () => {+ const out = await call('owner', 'remember', { fact: 'Harbor ledger room argument note', entity: PAGES.open.slug, visibility: 'world', provenance: 'room test', content_origin: 'user_said', room: ['group:team-a'] });+ expect(out.isError).toBe(false);+ expect((out.meta?.room as { unavailable?: string }).unavailable).toBe('op_not_covered');+ const [row] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE '%room argument note%' AND context IS NULL");+ expect(row!.n).toBe(1);+ }, 60_000);++ test('the audit row counts what entered the room and never names it', async () => {+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await call('owner', 'list_pages', { limit: 50 }, { room: { header: 'group:team-a' } });+ });+ const rows = readdirSync(auditDir).filter(f => f.startsWith('access-audience')).flatMap(f => readFileSync(join(auditDir, f), 'utf8').trim().split('\n')).map(l => JSON.parse(l));+ const marked = rows.filter(r => r.outcome === 'room_marked' && r.op === 'list_pages');+ expect(marked.length).toBeGreaterThan(0);+ expect(marked.at(-1).room).toMatchObject({ readable: 2, above: 5, unknown: 0, declared_by: 'harness', by_reason: { readers: 2, private_label: 1, folder_rule: 1, derived: 1 } });+ const text = readdirSync(auditDir).map(f => readFileSync(join(auditDir, f), 'utf8')).join('\n');+ for (const key of Object.keys(PAGES) as Key[]) expect({ key, named: text.includes(PAGES[key].slug) }).toEqual({ key, named: false });+ }, 60_000);++ test('rule 1 at the response cap: marks that would push a read over the cap are dropped, never the read', async () => {+ const slug = 'notes/wide-owner-plan';+ const body = Array.from({ length: 2600 }, (_, i) => 'Harbor ledger planning line ' + i + ' ' + 'x'.repeat(80)).join('\n');+ await importFromContent(engine, slug, '---\ntitle: Wide owner plan\nreadable_by: [owner-example]\n---\n' + body + '\n', { sourceId: SRC });+ await call('owner', 'get_chunks', { slug, limit: 500 });+ // Measured on a repeat call, so a notice shown once per session does not count.+ const plain = await call('owner', 'get_chunks', { slug, limit: 500 });+ expect(plain.isError).toBe(false);+ // The cap is checked before dispatch adds _meta.access, so measure the frame without it.+ const { access: _applied, ...plainMeta } = plain.raw._meta ?? {};+ const plainBytes = encodedFrameBytes({ ...plain.raw, _meta: plainMeta });+ expect(plainBytes).toBeGreaterThan(EGRESS_CAP_MIN);+ await engine.setConfig('mcp.max_result_bytes_http', String(plainBytes + 120));+ try {+ const marked = await call('owner', 'get_chunks', { slug, limit: 500 }, { room: { header: 'group:team-a' } });+ expect(marked.isError).toBe(false);+ expect(marked.text).toBe(plain.text);+ expect(marked.meta?.room).toEqual({ complete: false, unavailable: 'response_cap' });+ await engine.setConfig('mcp.max_result_bytes_http', String(plainBytes + 1));+ const bare = await call('owner', 'get_chunks', { slug, limit: 500 }, { room: { header: 'group:team-a' } });+ expect({ isError: bare.isError, text: bare.text === plain.text, room: bare.meta?.room }).toEqual({ isError: false, text: true, room: undefined });+ } finally {+ await engine.unsetConfig('mcp.max_result_bytes_http');+ }+ }, 120_000);++ test('whoami advertises room support', async () => {+ const out = await call('owner', 'whoami', {});+ expect((out.json as { features?: unknown }).features).toEqual({ room: true });+ }, 60_000);+ });+}diff --git a/test/mcp-tool-defs.test.ts b/test/mcp-tool-defs.test.tsindex 82855ffd77..9b3bd6f905 100644--- a/test/mcp-tool-defs.test.ts+++ b/test/mcp-tool-defs.test.ts@@ -283,7 +283,7 @@ describe('buildToolDefs strictParams emission (WP3/D14.1)', () => {expect(props.dry_run.description).toBe(op.params.dry_run.description);});- test('strict mode changes ONLY additionalProperties + the two passthrough keys', () => {+ test('strict mode changes ONLY additionalProperties + the passthrough keys (_meta, dry_run, room)', () => {const base = buildToolDefs(operations);for (let i = 0; i < base.length; i++) {const strict = strictDefs[i];@@ -295,7 +295,7 @@ describe('buildToolDefs strictParams emission (WP3/D14.1)', () => {}const extraKeys = Object.keys(strict.inputSchema.properties).filter(k => !(k in loose.inputSchema.properties));- expect(extraKeys.sort()).toEqual(['_meta', 'dry_run'].filter(k => !(k in loose.inputSchema.properties)).sort());+ expect(extraKeys.sort()).toEqual(['_meta', 'dry_run', 'room'].filter(k => !(k in loose.inputSchema.properties)).sort());expect(strict.inputSchema.required).toEqual(loose.inputSchema.required);}});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex d8ba90e4a9..16b6a56750 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -33,6 +33,7 @@ test/access-page-indexes-online.test.tstest/access-page-rule-fileless.test.tstest/access-qm-actor.test.tstest/access-raw-only-rules.test.ts+test/access-room.test.tstest/access-token-grant-columns.test.tstest/access-ungranted-member-writes.test.tstest/access-writes.test.ts