Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: adversarial review fixes
garrytancc1b8186c48f
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex bdc9756c6c..00ed3a4db6 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`, `personal_source` (a page the room could otherwise read that sits in someone's personal source while the room holds anyone else: `hiddenPersonalSources`). 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). GST-2670: `src/core/access/open-pages.ts` counts the pages every member's key reads (`openPages`: `accessAllowedSql` with the empty identity under `withoutCallerAccess`, so it never depends on the caller; private pages split out unless `search.remote_private_pages` relaxes them; throws `open_pages_unknown` when `gbrain_access_state_unreadable()`; Postgres runs it under `SET LOCAL statement_timeout`), over the sources the bound tokens and OAuth clients of enabled, non-labelled-only members other than the owner read (`credentialReadSources`); `SENSITIVE_PAGE_TYPES` (`grants/shared-exposure.ts`) is the DM, chat, conversation and mail tier. `readOpenPages` never throws; `ServesReceipt.open_pages` / `open_pages_error` carry it in the preview and receipt (planned members counted against the source their keys will read, this run's `people/<member>/` rules excluded), `gbrain access serves` prints it, `--labelled-only` calls `setMemberLabelledOnly` after the members step (the owner in the roster is BLOCKED), doctor `checks/open-shared-pages.ts` warns on sensitive pages, and `printOpenPagesUpgradeNotice` runs in post-upgrade. Callers gate on `brainServes`, so a one-person brain runs no query. Test: `test/open-shared-pages.test.ts` (both engines, repo-less).+- `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). GST-2670: `src/core/access/open-pages.ts` counts the pages every member's key reads (`openPages`: `accessAllowedSql` with the empty identity under `withoutCallerAccess`, so it never depends on the caller; private pages split out unless `remotePrivacyRelaxed` or a reading member's `private_pages` grant opens their source; throws `open_pages_unknown` when `gbrain_access_state_unreadable()`; Postgres runs it read-only under `SET LOCAL statement_timeout`), over the sources the bound tokens, OAuth clients and config `mcp.stdio_member` binding of enabled, non-labelled-only members other than the owner read (`credentialReadSources`, `stdioReadSources`), or every source when none reads one (doctor then reports information); `SENSITIVE_PAGE_TYPES` (`grants/shared-exposure.ts`) is the DM, chat, conversation and mail tier. `readOpenPages` never throws; `ServesReceipt.open_pages` / `open_pages_error` carry it in the preview and receipt (planned members counted against the source their keys will read, this run's `people/<member>/` rules excluded), `gbrain access serves` prints it, `--labelled-only` calls `setMemberLabelledOnly` after the members step (the owner in the roster is BLOCKED), doctor `checks/open-shared-pages.ts` warns on sensitive pages, and `printOpenPagesUpgradeNotice` runs in post-upgrade. Callers gate on `brainServes`, so a one-person brain runs no query. Test: `test/open-shared-pages.test.ts` (both engines, repo-less).- `gbrain serve --stdio-member <id>` (GST-363 PR 3) — `parseStdioMemberFlag`, `registeredStdioMember` and `withStdioMember` live in `src/core/stdio-member-flag.ts` (kept out of `mcp-registration.ts` so serve and doctor pick up no registration flags); serve passes the value to `startMcpServer`, dispatch sets `OperationContext.stdioMember` only for an unauthenticated stdio call, and `caller.ts` resolves it live ahead of config `mcp.stdio_member` (a disabled or unknown member reads as nobody, no fallback). Stored writes stamp it on `WriteAuthority.stdioMember` (jsonb, no migration); a stdio watch uses principal id `registration` so the wake drain re-checks that member. Setup writes it into one claude-code or codex entry (`ClaudeSetupPlan`/`CodexSetupPlan.stdioMember`); inspection reports an owned entry's member so setup re-runs and `refreshHookLaunchers` carry it, and `setupRerunArgv` never names it.- `src/core/access/requester-scope.ts` + `src/commands/doctor/checks/unscoped-shared-reads.ts` (GST-363 PR 2) — on a brain that serves several people (`servesPolicyFrom` in `search/private-visibility.ts`, read from the request config snapshot: explicit `access.serves` wins, else `access.serves_derived`; a brain pinned `one` never gates) a remote read from a connection bound to no member (no member identity, no audience, not attested, no `reads_unscoped`) is refused `requester_scope_required` before any work. Deny by default: every op not `mutating: true`, and every read-scope one (`think`), except `REQUESTER_SCOPE_EXEMPT` and `OWN_JOB_OPS` for a non-admin credential; `test/requester-scope.test.ts` pins the list and spies every handler. `requesterScopeGate` runs in `dispatchToolCall` after access resolves (attested calls exempt; an unreachable op keeps the unknown-tool envelope) and in `brain-allowlist.ts` `scopedJobAccess` per job tool call; a bound caller's access is never changed. `readsUnscoped`/`createdAt` come from the verifiers (`token-binding.ts` `credentialScopeFields`), else `credentialScopeFor`. Grace: 14 days from `access.serves_since` (migration v309's trigger sets it once) for connections created at or before it (unknown creation and stdio count as old), with `_meta.access.requester_scope`; `access.requester_scope_enforce false` (hosted) gives the notice only. An unreadable policy (`servesUnknown`) is read once more (`withServesReread`); a second failure refuses `requester_scope_unknown` (retryable). `assertCredentialScoped` refuses unbound `auth create`/`register-client` and `POST /admin/api/api-keys` (`credential_scope_required`); `--reads-unscoped [none]` changes go to the `access-reads-unscoped` audit file. `unscopedConnections` feeds doctor `unscoped_shared_reads`, `whoami` (`requesterScopeView`) and post-upgrade.- `src/core/access/stdio-bind-route.ts` + `src/commands/doctor/checks/shared-stdio-binding.ts` (GST-363 PR 2) — `stdioBindRoute()` is the one place that says how to bind an unbound stdio connection: `gbrain setup claude-code|codex --stdio-member <id>` for a harness one person uses (that harness entry, either engine), else a per-person `serve --http` key. The requester-scope refusal and notice, `gbrain access owner`'s Bind-one line and whoami's unbound note read it. Doctor `shared_stdio_binding` fails when `mcp.stdio_member` is set and `sharedStdioHarness()` (`setup-serves.ts`; a `hermes` on PATH counts only as a script, not React Native's compiled engine) finds OpenClaw or Hermes on a brain that serves several people (not applicable on a one-person brain); fix `gbrain config unset mcp.stdio_member`. `requesterScopeRefuses()` lets dispatch drop hot memory from the ops the gate does not cover for a connection it would refuse. Tests: `test/shared-stdio-binding.test.ts`.diff --git a/src/commands/doctor/checks/open-shared-pages.ts b/src/commands/doctor/checks/open-shared-pages.tsindex 19e48637a8..06f263afe4 100644--- a/src/commands/doctor/checks/open-shared-pages.ts+++ b/src/commands/doctor/checks/open-shared-pages.ts@@ -24,25 +24,30 @@ async function runOpenSharedPages(ctx: DoctorContext): Promise<Check[]> {const read = await readOpenPages(engine);const o = read.open_pages;if (!o) {- checks.push(checkError(NAME, "count the pages every member's key can read", new Error(read.open_pages_error!.message), { details: { open_pages: null, open_pages_error: read.open_pages_error } }));+ const error = read.open_pages_error!;+ checks.push(ctx.remote+ ? checkError(NAME, "count the pages every member's key can read", new Error(`${error.code}; ask the brain host's operator to run gbrain doctor --only open_shared_pages`), { details: { open_pages: null, code: error.code } })+ : checkError(NAME, "count the pages every member's key can read", new Error(error.message), { details: { open_pages: null, open_pages_error: error } }));return checks;}- const details = ctx.remote ? { total: o.total, sensitive: o.sensitive, private: o.private, members: o.members } : { open_pages: o };+ const details = ctx.remote ? { total: o.total, sensitive: o.sensitive, members: o.members } : { open_pages: o };const message = `This brain serves several people. ${openPagesHeadline(o)}`;if (!o.total) {checks.push({ name: 'open_shared_pages', status: 'ok', message, details });return checks;}- if (!o.sensitive) {+ if (!o.sensitive || !o.members.reading) {checks.push({ name: 'open_shared_pages', status: 'ok', severity: 'info', readiness_state: 'ok', details,- message: `${message} A team may share these on purpose; to keep a folder to some members, name its readers (gbrain access rule add --prefix <folder>/ --readers <list>).` });+ message: o.members.reading+ ? `${message} A team may share these on purpose; to keep a folder to some members, name its readers (gbrain access rule add --prefix <folder>/ --readers <list>).`+ : `${message} A member key made later will read them unless they name their readers first.` });return checks;}const top = o.top_sensitive!;checks.push({ name: 'open_shared_pages', status: 'warn', details,message: ctx.remote ? `${message} Ask the brain host's operator to run gbrain doctor --only open_shared_pages.` : `${message} A key bound to a member reads a page with no readers like any other key.`,...(ctx.remote ? {} : { fix: agentFix(['gbrain', 'list', '--type', top.type, '--source-id', top.source, '--json'],- 'Read-only: lists the open pages of the largest DM, chat or mail type, so the user can say who should read them.', NAME,+ 'Read-only: lists the pages of the largest open DM, chat or mail type (pages that already name readers are listed too, 50 at a time), so the user can say who should read the open ones.', NAME,{ ask_user: true, docs: 'docs/guides/access-designations.md#pages-every-members-key-can-read', user_message: openPagesLines(read, { prefix: '' }).join('\n') }) }) });} catch (error) {checks.push(checkError(NAME, `run ${NAME}`, error));diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.tsindex e7519c1a83..9ad6edfa8e 100644--- a/src/commands/setup-serves.ts+++ b/src/commands/setup-serves.ts@@ -209,7 +209,7 @@ function openTail(r: ServesReceipt | undefined, member: string): string {if (!r || r.open_pages === undefined) return '';if (!open) return '; open pages unknown';if (!open.total || r.members.find(m => m.id === member)?.labelled_only || member === open.owner) return '';- return `; it also reads the ${open.total} open page(s) listed above`;+ return `; its keys can also read open pages listed above (${open.total} across the members' sources)`;}export function servesLines(o: ServesOutcome, dryRun: boolean): string[] {diff --git a/src/core/access/open-pages.ts b/src/core/access/open-pages.tsindex 1b8e327a38..5eb7558513 100644--- a/src/core/access/open-pages.ts+++ b/src/core/access/open-pages.ts@@ -4,7 +4,7 @@* reads it like an unbound one (requester-scope.ts gates who may ask; only labels decide what a member reads). The* count is the read path's own floor (accessAllowedSql with an empty identity, built outside any caller record, so it* never depends on who asks), split into the pages members read and the visibility: private pages they do not- * (unless the operator relaxed search.remote_private_pages). "Members" are the enabled members other than the owner;+ * (unless this process sees remote privacy relaxed, or a reading member's grant opens that source's private pages). "Members" are the enabled members other than the owner;* a labelled-only member reads no open page, and each other member reads the sources its bound tokens and OAuth* clients read. Read-only and best effort everywhere it is shown: access serves several (preview and receipt),* gbrain access serves, doctor open_shared_pages and post-upgrade. Callers gate on brainServes first, so a@@ -12,9 +12,10 @@* brain gets it unchanged.*/import type { BrainEngine } from '../engine.ts';-import { accessAllowedSql, privacyPartSql, readHonorAliases, resolveExcludePrivatePages, withoutCallerAccess } from '../search/private-visibility.ts';-import { credentialReadSources, SENSITIVE_PAGE_TYPES } from '../grants/shared-exposure.ts';-import { grantFromClient, grantFromRow, grantFromTokenRow, type PrincipalGrant } from '../grants/model.ts';+import { accessAllowedSql, privacyPartSql, readHonorAliases, remotePrivacyRelaxed, withoutCallerAccess } from '../search/private-visibility.ts';+import { credentialReadSources, SENSITIVE_PAGE_TYPES, stdioReadSources } from '../grants/shared-exposure.ts';+import { grantFromClient, grantFromRow, grantFromTokenRow, privatePagesSources, type PrincipalGrant } from '../grants/model.ts';+import { stdioMemberId } from './caller.ts';import { localFederatedSourceIds } from '../source-resolver.ts';import { isStatementTimeout } from '../persistence/bounded-reads.ts';import { agentBlock } from '../agent-markers.ts';@@ -29,13 +30,14 @@ export interface OpenFolder { source: string; folder: string; pages: number; senexport interface OpenPages {/** The brain owner (access.owner_member), whom every printed reader list starts with; null when none is set. */owner: string | null;- /** reading: members other than the owner, not labelled-only, whose keys read a counted source; counted: members other than the owner. */+ /** reading: members other than the owner, not labelled-only, whose keys (or config mcp.stdio_member binding) read a source; counted: members other than the owner. */members: { reading: number; counted: number };+ /** The sources counted: those the reading members read, or every source when no member reads one. */sources: string[];total: number;/** Open pages of a DM, chat, conversation or mail type (SENSITIVE_PAGE_TYPES). */sensitive: number;- /** Open pages that visibility: private (or a privacy alias) keeps from members; counted in total when the operator relaxed remote privacy. */+ /** Open pages that visibility: private (or a privacy alias) keeps from members; counted in total instead where remote privacy is relaxed or a reading member's grant opens private pages. */private: number;folders: OpenFolder[];other: { folders: number; pages: number; sensitive: number };@@ -57,9 +59,14 @@ async function mintedReadSources(engine: BrainEngine, source: string): Promise<sreturn await localFederatedSourceIds(engine, 'default', 'seed_default').catch(() => undefined) ?? ['default'];}-/** Each counted member (enabled, not the owner) with the sources its keys read; empty for a labelled-only member. */-async function memberReads(engine: BrainEngine, owner: string | null, planned: OpenPagesOptions['planned']): Promise<Map<string, Set<string>>> {+/**+ * Each counted member (enabled, not the owner) with the sources its keys and a config mcp.stdio_member binding read+ * (empty for a labelled-only member), and the sources whose private pages some reading member's grant opens. A harness+ * entry's serve --stdio-member is not in the database, so it is not seen here.+ */+async function memberReads(engine: BrainEngine, owner: string | null, planned: OpenPagesOptions['planned']): Promise<{ reads: Map<string, Set<string>>; privateSources: Set<string> }> {const reads = new Map<string, Set<string>>();+ const privateOf = new Map<string, Set<string>>();const labelledOnly = new Set<string>();for (const m of await engine.executeRaw<{ id: string; labelled_only: unknown }>('SELECT id, labelled_only FROM access_members WHERE disabled_at IS NULL AND tombstoned_at IS NULL ORDER BY id')) {@@ -81,8 +88,15 @@ async function memberReads(engine: BrainEngine, owner: string | null, planned: O];for (const { member, grant } of credentials) {const set = reads.get(member);- if (set) for (const s of await sourcesOf(grant)) set.add(s);+ if (!set) continue;+ for (const s of await sourcesOf(grant)) set.add(s);+ const priv = privateOf.get(member) ?? new Set<string>();+ privateOf.set(member, priv);+ for (const s of privatePagesSources(grant)) priv.add(s);}+ const stdio = await stdioMemberId(engine);+ const stdioSet = stdio ? reads.get(stdio) : undefined;+ if (stdioSet) for (const s of await stdioReadSources(engine)) stdioSet.add(s);if (planned) {const minted = await mintedReadSources(engine, planned.source);for (const id of planned.members) {@@ -94,7 +108,9 @@ async function memberReads(engine: BrainEngine, owner: string | null, planned: O}}for (const id of labelledOnly) reads.get(id)?.clear();- return reads;+ const privateSources = new Set<string>();+ for (const [id, set] of reads) if (set.size) for (const s of privateOf.get(id) ?? []) privateSources.add(s);+ return { reads, privateSources };}async function bounded<T>(engine: BrainEngine, fn: (e: BrainEngine) => Promise<T>): Promise<T> {@@ -102,7 +118,7 @@ async function bounded<T>(engine: BrainEngine, fn: (e: BrainEngine) => Promise<Treturn engine.transaction(async (tx) => {await tx.executeRaw(`SET LOCAL statement_timeout = ${OPEN_PAGES_TIMEOUT_MS}`);return fn(tx);- });+ }, { readOnly: true });}/** The open pages the counted members' keys read (OpenPages); throws when the access state cannot be read. */@@ -113,14 +129,15 @@ export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}throw Object.assign(new Error('the folder-rule state cannot be read, so every page reads as covered and a count would say 0'), { code: 'open_pages_unknown' });}const owner = await ownerMemberId(engine);- const reads = await memberReads(engine, owner, opts.planned);+ const { reads, privateSources } = await memberReads(engine, owner, opts.planned);const reading = [...reads.values()].filter(s => s.size > 0);- const sources = [...new Set(reading.flatMap(s => [...s]))].sort();+ const read = [...new Set(reading.flatMap(s => [...s]))].sort();+ const sources = read.length ? read : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(s => s.id);const result: OpenPages = { owner, members: { reading: reading.length, counted: reads.size }, sources, total: 0, sensitive: 0, private: 0,folders: [], other: { folders: 0, pages: 0, sensitive: 0 }, top_sensitive: null };if (!sources.length) return result;await readHonorAliases(engine);- const hidePrivate = await resolveExcludePrivatePages(engine, true);+ const relaxed = await remotePrivacyRelaxed(engine);const params: unknown[] = [sources];const exclude = (opts.exclude ?? []).map(x => {params.push(x.source, x.prefix);@@ -136,7 +153,7 @@ export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}const byType = new Map<string, { source: string; type: string; pages: number }>();for (const row of rows) {const n = Number(row.pages);- if (row.visible !== true && hidePrivate) { result.private += n; continue; }+ if (row.visible !== true && !relaxed && !privateSources.has(row.source)) { result.private += n; continue; }const key = `${row.source}/${row.folder}`;const f = folders.get(key) ?? { source: row.source, folder: row.folder, pages: 0, sensitive: 0 };folders.set(key, f);@@ -190,7 +207,7 @@ export function openPagesLines(read: OpenPagesRead, opts: { prefix?: string; labif (!o) return [`${head}count unknown (${read.open_pages_error?.message ?? 'not read'}); retry with ${read.open_pages_error?.retry ?? RETRY}`];if (!o.total) return [head + openPagesHeadline(o)];const readers = `${o.owner ? `${o.owner},` : ''}<list>`;- const shared = o.folders.find(f => !f.sensitive && f.folder !== '(root)');+ const shared = o.folders.find(f => !f.sensitive && f.folder !== '(root)' && f.folder !== 'people');const where = [...o.folders.map(f => `${folderName(f)} ${f.pages}${f.sensitive ? ` (${f.sensitive} of them DMs, chat or mail)` : ''}`),...(o.other.folders ? [`${o.other.folders} more ${o.other.folders === 1 ? 'folder' : 'folders'} ${o.other.pages}`] : [])].join(', ');return [@@ -207,7 +224,7 @@ export async function printOpenPagesUpgradeNotice(engine: BrainEngine): Promise<try {if ((await brainServes(engine)).serves !== 'several') return;const read = await readOpenPages(engine);- if (!read.open_pages?.sensitive) return;+ if (!read.open_pages?.sensitive || !read.open_pages.members.reading) return;console.log('');console.log(agentBlock({why: `This brain serves several people. ${openPagesHeadline(read.open_pages)} A key bound to a member reads a page with no readers like any other key.`,diff --git a/test/open-shared-pages.test.ts b/test/open-shared-pages.test.tsindex ffbc88b0ba..fb7975d439 100644--- a/test/open-shared-pages.test.ts+++ b/test/open-shared-pages.test.ts@@ -209,12 +209,12 @@ for (const kind of testBackends()) {test('a member already labelled-only keeps that mark on a re-run without the flag and gets no open-pages tail', async () => {const proof = [{ member: 'bob-example', own: 1, leaked: [] }];const open = await label(ROSTER, false);- expect(servesLines({ mode: 'several', receipt: open, proof } as never, false).join('\n')).toContain('also reads the');+ expect(servesLines({ mode: 'several', receipt: open, proof } as never, false).join('\n')).toContain('can also read open pages');await setMemberLabelledOnly(engine, 'bob-example', true, { remote: false });try {const r = await label(ROSTER, false);expect(r.members.find(m => m.id === 'bob-example')).toMatchObject({ labelled_only: 'keep' });- expect(servesLines({ mode: 'several', receipt: r, proof } as never, false).join('\n')).not.toContain('also reads the');+ expect(servesLines({ mode: 'several', receipt: r, proof } as never, false).join('\n')).not.toContain('can also read open pages');expect(receiptLines(r).join('\n')).not.toContain('--labelled-only --yes');} finally { await setMemberLabelledOnly(engine, 'bob-example', false, { remote: false }); }}, 60_000);@@ -263,6 +263,42 @@ for (const kind of testBackends()) {}}, 60_000);+ test('relaxed remote privacy counts the private pages a member key then lists', async () => {+ const before = await openPages(engine);+ expect(before.private).toBeGreaterThan(0);+ await withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, async () => {+ expect(await listedAs('bob-example')).toContain('private/diary');+ const relaxed = await openPages(engine);+ expect(relaxed.private).toBe(0);+ expect(relaxed.total).toBe(before.total + before.private);+ });+ }, 60_000);++ test('a member bound through config mcp.stdio_member counts as reading, with no key', async () => {+ await addMember(engine, 'carol-example');+ const before = await openPages(engine);+ await engine.setConfig('mcp.stdio_member', 'carol-example');+ try {+ const r = await openPages(engine);+ expect(r.members).toEqual({ reading: before.members.reading + 1, counted: before.members.counted });+ } finally {+ await engine.unsetConfig('mcp.stdio_member');+ await engine.executeRaw("UPDATE access_members SET disabled_at = now() WHERE id = 'carol-example'");+ }+ }, 60_000);++ test('with no member key reading anything, the open pages are still counted and doctor reports information', async () => {+ await setMemberLabelledOnly(engine, 'bob-example', true, { remote: false });+ try {+ const r = await openPages(engine);+ expect(r.members.reading).toBe(0);+ expect(r.total).toBeGreaterThan(0);+ expect(r.sensitive).toBeGreaterThan(0);+ expect(await doctor()).toMatchObject({ status: 'ok', severity: 'info' });+ expect(receiptLines(await label(['bob-example'], false)).join('\n')).toContain("No member's key reads");+ } finally { await setMemberLabelledOnly(engine, 'bob-example', false, { remote: false }); }+ }, 60_000);+test('labelling a page lowers the count by that page', async () => {const before = (await openPages(engine)).total;await importFromContent(engine, 'chats/dm-1', fm('dm', 'readable_by: [alice-example, bob-example]\n'), { sourceId: 'default', noEmbed: true });