Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Show the pages every member's key can still read on a brain that serves several people (GST-2670)
garrytan2aa54d96015e
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex 3965a4bfd7..58cb3afaff 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).+- `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).- `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/docs/guides/access-designations.md b/docs/guides/access-designations.mdindex df6cf27e4d..ad92037665 100644--- a/docs/guides/access-designations.md+++ b/docs/guides/access-designations.md@@ -253,6 +253,30 @@ refused (`permission_denied`). `gbrain access member list` and `gbrain access chwhich labelled-only members a page leaves out, and doctor's `access_labelled_only_members` lists them. An older gbrainbinary sharing the same database ignores the grant, so upgrade every binary that serves the brain before turning it on.+### Pages every member's key can read++On a brain that serves several people, a key bound to a member reads a page with no label like any other key: the+binding says who is asking, and only labels decide what that person reads. So a chat export or mail import loaded+before anyone named its readers is open to every member's key, and so are the facts drawn from it. gbrain counts those+pages, read-only, wherever you set up or check such a brain: the `gbrain access serves several` preview and receipt+(also shown by `gbrain setup <harness> --serves several`), `gbrain access serves`, doctor's `open_shared_pages` and+`gbrain post-upgrade`. Each shows how many members' keys read them ("the keys of 2 of 3 members"; the owner and+labelled-only members are never counted), the top folders, and the commands that close them, with the owner already in+every reader list:++- DMs, chat and mail: keep members to labelled pages (`gbrain access serves several --members <ids> --labelled-only`+ or `gbrain access member labelled-only <id> on`), then name each page set's readers with+ `gbrain repair visibility --source <id> --slugs-file <file> --readers <owner>,<list>` (preview, then+ `--apply --expect <hash>`). A folder rule can't do this, because one chats/ folder holds DMs between different pairs.+- A folder its readers share: `gbrain access rule add --prefix meetings/ --readers <owner>,<list> --source <id>`.+- New pages: `readable_by: [<owner>, <list>]` in their frontmatter.++The count never depends on who runs it, changes nothing, and never changes an exit code. Doctor warns while DM, chat,+conversation or mail pages are open and reports other open folders as information, since a team may share them on+purpose. A count that fails prints "count unknown" with `gbrain doctor --only open_shared_pages --json` to retry, and+setup carries on. A one-person brain, or one with `access.serves` set to `one`, runs no count. `--labelled-only` is+opt-in and never applies to the owner: with the owner in the roster the run is BLOCKED before anything is written.+## Related- [Multi-source brains](multi-source-brains.md): sources and grants.diff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex 78cae21d90..8a96d68eb9 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -172,7 +172,11 @@ receipt prints the path, never the key). It sets `access.serves = several` last,then proves the labels by reading every other member's folder as each member(`gbrain find people/<other>/ --as <member>`): none may return a page.The receipt also lists any other `people/<name>/` folder that no rule covers, since-every member reads it, and the run is not OK until it has a rule.+every member reads it, and the run is not OK until it has a rule. It then counts the+other pages no rule or `readable_by` restricts, which every member's key still reads,+by folder, with the commands that label them; `--labelled-only` keeps each member to+the pages labelled for it instead (never the owner). See+[pages every member's key can read](access-designations.md#pages-every-members-key-can-read).Setup leaves the stdio server unbound: stdio sessions read only pages no rulerestricts, and the harness's instructions keep the one-person scoping lines.For a Claude Code or Codex install only one person uses, bind that harness alone:diff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.mdindex 038194855e..78bb3284f3 100644--- a/plugin/skills/setup/SKILL.md+++ b/plugin/skills/setup/SKILL.md@@ -40,7 +40,7 @@ Use the user's existing context; do not repeat choices they already made.| --- | --- || Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. || Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |-| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word). Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). || Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. || Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. || Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.mdindex 6e7803b0a2..e6dab2ad0e 100644--- a/skills/setup/SKILL.md+++ b/skills/setup/SKILL.md@@ -39,7 +39,7 @@ Use the user's existing context; do not repeat choices they already made.| --- | --- || Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. || Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |-| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word). Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). || Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. || Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. || Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |diff --git a/skills/skills.lock.history.json b/skills/skills.lock.history.jsonindex 8f296b5f6f..8e22e6a526 100644--- a/skills/skills.lock.history.json+++ b/skills/skills.lock.history.json@@ -1063,6 +1063,7 @@"03216a34292ccc44984bca614d5dcf5f2afd1d762a0222c603dd2bc67f047a22","1cfb85220ef53a8575a54137ab45296a36e5d00652d1e71e8f569315b425b027","322faf7099afd71f9add0f6dbe4d2bf9686df54c521a29e018f4ab25608e3dc0",+ "427f8703034bf220b87698d0a6b66a74fe767180ba0bd9108d56e781facd679b","4a47a5f6ee99ac8a2649a304abb261fd34810cf6185fd7d6a53e1b6c4cbc0764","4e8830f839472359a72a65fbd2a8b53f7c7fdc3823ad0049c5201a6f6480b006","681574af925998a2b9b363eb8e16c178e891612f4750fed942f4b8efa7335edc",diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex ba3ec304d1..a358f0f995 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -212,7 +212,7 @@"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489","schema-author/SKILL.md": "38efb8b48399a2dc526d7084579aa265b2ab232882605bc2f86f6ba2869619f5","schema-unify/SKILL.md": "36259f1510fd693253535bd203e32db1bfa24aaae7278c7a2e8b7d6859022708",- "setup/SKILL.md": "987ed3621d335ea8aef704e24e2f2eb4d9558802aff2c8216a230d3ac82aaddd",+ "setup/SKILL.md": "427f8703034bf220b87698d0a6b66a74fe767180ba0bd9108d56e781facd679b","signal-detector/SKILL.md": "426a8a3b01a007dd25638e61adef510c18c3d9ce6f1c18ba3d77fdfcd3281d60","skill-autobench/SKILL.md": "29f5760dcfd823c5f7d4fb50a3cf4e36601b1b8125e57d6bf83645a41f97f613","skill-autobench/routing-eval.jsonl": "8d961ed6403b7e2f690948e4c18529d40f26f6f21064befc56d465966b1a9ec0",@@ -226,7 +226,7 @@"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e","skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb","skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",- "skills.lock.history.json": "ac900fd266e707da08a83c204b00dfc03e7634499ebd574a6f39fb3a224e8101",+ "skills.lock.history.json": "f5ee7a6cb69f97d23141a9fdf5beae0b305070c1cd6981be55edbe116c6df90b","smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5","soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8","strategic-reading/SKILL.md": "ab2cd3adc79289374cfbc5cb3d5ee17f962fd8f7f3c997a1da708da0ed67797c",diff --git a/src/commands/access-serves.ts b/src/commands/access-serves.tsindex 74c826ce4a..cee4c001b6 100644--- a/src/commands/access-serves.ts+++ b/src/commands/access-serves.ts@@ -2,7 +2,7 @@* GST-363 (PR 1): `gbrain access serves`, the labelling half of a brain that serves several people.** gbrain access serves [--json] Read-only: one or several, why, owner, stdio member- * gbrain access serves several --members a,b [--members-file f] [--source id] [--yes] [--json]+ * gbrain access serves several --members a,b [--members-file f] [--source id] [--labelled-only] [--yes] [--json]** `several` previews, then with --yes: writes config access.serves = several, adds each member (existing ones are* kept), adds one folder rule per member (people/<member>/ readable by that member) through the folder-rule path@@ -12,6 +12,9 @@* A preview with any BLOCKED line writes nothing; config access.serves is written last, once members, rules and keys* are in place. Every step is idempotent on the member id, so a re-run after a partial failure converges; the receipt names paths,* never key values. `gbrain setup <harness> --serves several` runs this as a child and adds the bound-read proof.+ * GST-2670: the preview, the receipt and the read-only status also count the pages every member's key can still read+ * (core/access/open-pages.ts, best effort: a failed count never stops the run), and --labelled-only marks each member+ * of the roster labelled-only after the members step (never the owner, refused before anything is written).*/import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';import { dirname, join, relative } from 'node:path';@@ -26,6 +29,9 @@ import { addMember, getMember, parseIdList } from '../core/access/members.ts';import { ownerMemberId } from '../core/access/owner.ts';import { stdioMemberId } from '../core/access/caller.ts';import { brainServes, SERVES_KEY, unlabeledPeopleFolders, type PeopleFolder, type ServesView } from '../core/access/serves.ts';+import { setMemberLabelledOnly } from '../core/access/labelled-only.ts';+import { openPagesLines, readOpenPages, type OpenPagesError, type OpenPagesRead } from '../core/access/open-pages.ts';+import type { OpenPages } from '../core/access/open-pages.ts';import { addFolderRules, currentFolderRules } from './access-rules.ts';import { mintToken } from './auth-mint.ts';@@ -33,21 +39,24 @@ export const MEMBER_KEY_DIR = 'member-keys';export const memberKeyName = (member: string): string => `member-${member}`;export const memberKeyDir = (): string => join(configDir(), MEMBER_KEY_DIR);-export interface ServesStatus extends ServesView { owner: string | null; stdio_member: string | null }+export interface ServesStatus extends ServesView { owner: string | null; stdio_member: string | null; open_pages?: OpenPages | null; open_pages_error?: OpenPagesError }-type Step = 'members' | 'rules' | 'keys' | 'config';+type Step = 'members' | 'labelled_only' | 'rules' | 'keys' | 'config';export interface ServesReceipt {serves: 'several';source_id: string;applied: boolean;config: { key: string; value: 'several'; action: 'write' | 'keep' };- members: Array<{ id: string; action: 'add' | 'keep' | 'blocked'; detail?: string }>;+ members: Array<{ id: string; action: 'add' | 'keep' | 'blocked'; detail?: string; labelled_only?: 'set' | 'keep' }>;rules: Array<{ id: string; prefix: string; readers: string[]; action: 'add' | 'keep' | 'blocked'; detail?: string }>;rule_write?: { store: string; revision: number | null; state: string; git_commit?: string | null };keys: Array<{ member: string; token_name: string; path: string; action: 'mint' | 'keep' | 'blocked'; detail?: string }>;key_dir: string;/** People folders with pages that no rule covers once this run's rules are in place: every member reads them. */unlabeled: PeopleFolder[];+ /** GST-2670: the pages no rule or readable_by restricts that the members' keys read, once this run's rules are in place; null when the count failed. */+ open_pages: OpenPages | null;+ open_pages_error?: OpenPagesError;/** The steps finished before a failure (partial-failure report); every one is idempotent, so a re-run converges. */completed: Step[];error?: { code: string; message: string };@@ -79,10 +88,11 @@ function gitRootAbove(dir: string): string | null {export async function servesStatus(engine: BrainEngine): Promise<ServesStatus> {const view = await brainServes(engine);const live = (id: string | null) => (id && view.enabled_members.includes(id) ? id : null);- return { ...view, owner: live(await ownerMemberId(engine)), stdio_member: live(await stdioMemberId(engine)) };+ const status: ServesStatus = { ...view, owner: live(await ownerMemberId(engine)), stdio_member: live(await stdioMemberId(engine)) };+ return view.serves === 'several' ? { ...status, ...await readOpenPages(engine) } : status;}-async function plan(engine: BrainEngine, roster: string[], sourceId: string): Promise<ServesReceipt> {+async function plan(engine: BrainEngine, roster: string[], sourceId: string, labelledOnly: boolean): Promise<ServesReceipt> {const keyDir = memberKeyDir();const gitRoot = gitRootAbove(keyDir);if (gitRoot) {@@ -91,11 +101,17 @@ async function plan(engine: BrainEngine, roster: string[], sourceId: string): Pr{ why: 'Key files hold live credentials and must never sit where a commit could pick them up.' });}const explicit = (await engine.getConfig(SERVES_KEY))?.trim();+ const owner = labelledOnly ? await ownerMemberId(engine) : null;const members: ServesReceipt['members'] = [];for (const id of roster) {const m = await getMember(engine, id);- members.push(!m ? { id, action: 'add' } : m.status === 'enabled' ? { id, action: 'keep' }- : { id, action: 'blocked', detail: m.status === 'disabled' ? `member is disabled: enable it with gbrain access member enable ${id}` : 'member id was removed and can never be reused; use a new id' });+ const entry: ServesReceipt['members'][number] = !m ? { id, action: 'add' } : m.status === 'enabled' ? { id, action: 'keep' }+ : { id, action: 'blocked', detail: m.status === 'disabled' ? `member is disabled: enable it with gbrain access member enable ${id}` : 'member id was removed and can never be reused; use a new id' };+ if (labelledOnly && entry.action !== 'blocked') {+ if (id === owner) Object.assign(entry, { action: 'blocked', detail: `${id} is the brain owner, who reads the whole brain, so it is never labelled-only: leave it out of this run or name another owner first (gbrain access owner set <member>)` });+ else entry.labelled_only = m?.labelled_only ? 'keep' : 'set';+ }+ members.push(entry);}const base = await currentFolderRules(engine, sourceId);const rules: ServesReceipt['rules'] = roster.map((id) => {@@ -122,7 +138,15 @@ async function plan(engine: BrainEngine, roster: string[], sourceId: string): Prelse keys.push({ member: id, token_name: name, path, action: 'keep' });}return { serves: 'several', source_id: sourceId, applied: false, config: { key: SERVES_KEY, value: 'several', action: explicit === 'several' ? 'keep' : 'write' },- members, rules, keys, key_dir: keyDir, unlabeled: await unlabeledOutside(engine, sourceId, rules), completed: [] };+ members, rules, keys, key_dir: keyDir, unlabeled: await unlabeledOutside(engine, sourceId, rules), ...await openPagesFor(engine, sourceId, members, rules, labelledOnly), completed: [] };+}++/** The open pages once this run's members, keys and rules are in place (the preview counts what it is about to add). */+function openPagesFor(engine: BrainEngine, sourceId: string, members: ServesReceipt['members'], rules: ServesReceipt['rules'], labelledOnly: boolean): Promise<OpenPagesRead> {+ return readOpenPages(engine, {+ planned: { members: members.filter(m => m.action !== 'blocked').map(m => m.id), source: sourceId, labelledOnly },+ exclude: rules.filter(r => r.action !== 'blocked').map(r => ({ source: sourceId, prefix: r.prefix })),+ });}/** Unlabeled people folders, not counting the ones this run's rules cover. */@@ -147,14 +171,19 @@ function abortAfter(step: string): void {}/** Plans, and with `apply` writes, the several-people labelling; a failure is reported in the receipt, never thrown. */-export async function labelSeveral(engine: BrainEngine, roster: string[], sourceId: string, apply: boolean, json: boolean): Promise<ServesReceipt> {- const receipt = await plan(engine, roster, sourceId);+export async function labelSeveral(engine: BrainEngine, roster: string[], sourceId: string, apply: boolean, json: boolean, opts: { labelledOnly?: boolean } = {}): Promise<ServesReceipt> {+ const labelledOnly = opts.labelledOnly === true;+ const receipt = await plan(engine, roster, sourceId, labelledOnly);if (!apply || blocked(receipt)) return receipt;receipt.applied = true;try {for (const m of receipt.members.filter(x => x.action === 'add')) await addMember(engine, m.id);receipt.completed.push('members');abortAfter('serves-members');+ if (labelledOnly) {+ for (const m of receipt.members.filter(x => x.labelled_only === 'set')) await setMemberLabelledOnly(engine, m.id, true, { remote: false });+ receipt.completed.push('labelled_only');+ }const added = receipt.rules.filter(r => r.action === 'add').map((r): FolderRule => ({ id: r.id, prefix: r.prefix, readable_by: r.readers }));if (added.length) {const { result } = await addFolderRules(engine, sourceId, added, { apply: true, json });@@ -177,6 +206,9 @@ export async function labelSeveral(engine: BrainEngine, roster: string[], sourceif (receipt.config.action === 'write') await engine.setConfig(SERVES_KEY, 'several');receipt.completed.push('config');receipt.unlabeled = await unlabeledOutside(engine, sourceId, receipt.rules);+ const { open_pages, open_pages_error } = await openPagesFor(engine, sourceId, receipt.members, receipt.rules, labelledOnly);+ receipt.open_pages = open_pages;+ if (open_pages_error) receipt.open_pages_error = open_pages_error; else delete receipt.open_pages_error;} catch (e) {receipt.error = { code: (e as { code?: string }).code ?? 'internal_error', message: e instanceof Error ? e.message : String(e) };}@@ -190,12 +222,13 @@ export function receiptLines(r: ServesReceipt): string[] {return [`Serves several people (source ${r.source_id}):`,` config ${r.config.key} = ${r.config.value} (${verb(r.config.action)})`,- ...r.members.map(m => ` member ${m.id} (${verb(m.action)})${m.detail ? `: ${m.detail}` : ''}`),+ ...r.members.map(m => ` member ${m.id} (${verb(m.action)}${m.labelled_only ? `; labelled-only ${m.labelled_only === 'keep' ? 'kept' : r.applied ? 'set' : 'will set'}` : ''})${m.detail ? `: ${m.detail}` : ''}`),...r.rules.map(x => ` rule ${x.prefix} readable by ${x.readers.map(p => p.replace(/^member:/, '')).join(', ')} (${verb(x.action)})${x.detail ? `: ${x.detail}` : ''}`),...(r.rule_write ? [` ${r.rule_write.store} store, revision ${r.rule_write.revision ?? '-'} ${r.rule_write.state}${r.rule_write.git_commit ? `, committed ${r.rule_write.git_commit.slice(0, 12)}` : ''}`] : []),...r.keys.map(k => ` key ${k.member}: ${k.path} (${verb(k.action)}${k.action === 'blocked' ? '' : ', 0600'}; token ${k.token_name})${k.detail ? `: ${k.detail}` : ''}`),...(ruleWritePending(r) ? [` The rules are not enforced yet: finish with gbrain access resume --source ${r.source_id}`] : []),...r.unlabeled.map(u => ` unlabeled ${u.source}:${u.prefix} (${u.pages} page(s)) has no folder rule, so every member reads it: name its readers with gbrain access rule add --prefix ${u.prefix} --readers <list> --source ${u.source}, or add the person with --members`),+ ...openPagesLines(r, { labelledOnly: `gbrain access serves several --members ${r.members.map(m => m.id).join(',')}${r.source_id === 'default' ? '' : ` --source ${r.source_id}`} --labelled-only --yes` }),...(r.error ? [`Stopped: ${r.error.message}`, ` Finished before it stopped: ${r.completed.join(', ') || 'nothing'}. Every step is idempotent: run the same command again to finish.`] : []),...(r.applied ? [] : [blocked(r) ? 'Nothing written: fix each BLOCKED line, then run this again.' : 'Nothing written. Add --yes to apply.']),];@@ -209,13 +242,14 @@ export async function runAccessServes(engine: BrainEngine, mode: string | undeficonsole.log(json ? JSON.stringify(s, null, 2) : [`This brain serves ${s.serves === 'several' ? 'several people' : 'one person'} (${s.from === 'config' ? `config ${SERVES_KEY}` : `${s.enabled_members.length} enabled member(s)`}).`,` Enabled members: ${s.enabled_members.join(', ') || 'none'}`,- ` Owner: ${s.owner ?? 'none'}; stdio server reads as: ${s.stdio_member ?? 'nobody in particular (unbound)'}`].join('\n'));+ ` Owner: ${s.owner ?? 'none'}; stdio server reads as: ${s.stdio_member ?? 'nobody in particular (unbound)'}`,+ ...(s.serves === 'several' ? openPagesLines({ open_pages: s.open_pages ?? null, ...(s.open_pages_error ? { open_pages_error: s.open_pages_error } : {}) }) : [])].join('\n'));return;}if (mode !== 'several') throw usageError(`Unknown access serves mode: ${mode}.`, 'gbrain access serves (read-only), or gbrain access serves several --members <id,...>. A one-person brain needs no step.');const roster = readRoster(flagValue(args, '--members'), flagValue(args, '--members-file'));if (!roster.length) throw rosterEmpty('gbrain access serves several');- const r = await labelSeveral(engine, roster, flagValue(args, '--source') ?? 'default', args.includes('--yes'), json);+ const r = await labelSeveral(engine, roster, flagValue(args, '--source') ?? 'default', args.includes('--yes'), json, { labelledOnly: args.includes('--labelled-only') });console.log(json ? JSON.stringify(r, null, 2) : receiptLines(r).join('\n'));if (!receiptOk(r)) setCliExitVerdict(1);}diff --git a/src/commands/access.ts b/src/commands/access.tsindex 4620033b69..d77b8517c0 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -88,10 +88,13 @@ Owner (one member who owns this brain; credentials bound to it read every page,Serves several people (GST-363):gbrain access serves One or several, and why (config access.serves, else 2+ enabled members)- gbrain access serves several --members a,b [--members-file <file>] [--source <id>] [--yes]+ gbrain access serves several --members a,b [--members-file <file>] [--source <id>] [--labelled-only] [--yes]Preview first; --yes writes access.serves = several, adds each member,a folder rule people/<member>/ read only by that member, and one key- bound to each member in a 0600 file under <config>/member-keys/+ bound to each member in a 0600 file under <config>/member-keys/.+ Both list the pages every member's key can still read (no rule or+ readable_by restricts them); --labelled-only keeps each member to the+ pages labelled for it (never the owner)Folder rules (one rulebook per source; the database store on a repo-less source, .gbrain/access.yml on a git one):gbrain access rule add --prefix <folder/> | --slug <page> --readers a,group:b [--raw-only] [--id <rule>] [--source <id>] [--yes]diff --git a/src/commands/doctor/checks/open-shared-pages.ts b/src/commands/doctor/checks/open-shared-pages.tsnew file mode 100644index 0000000000..19e48637a8--- /dev/null+++ b/src/commands/doctor/checks/open-shared-pages.ts@@ -0,0 +1,57 @@+/**+ * GST-2670 (GBRA-502): open_shared_pages. On a brain that serves several people, the pages no rule or readable_by+ * restricts are read by every member's key (core/access/open-pages.ts). Warns while any of them is a DM, chat,+ * conversation or mail page; reports other open pages as information, since a team may share them on purpose.+ * Read-only: the fix asks the user who should read them and lists the pages with a read-only command. A remote caller+ * (run_doctor) gets totals only, never folder names. Not applicable on a brain that serves one person.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { brainServes } from '../../../core/access/serves.ts';+import { openPagesHeadline, openPagesLines, readOpenPages } from '../../../core/access/open-pages.ts';++const NAME = 'open_shared_pages';++async function runOpenSharedPages(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ try {+ if ((await brainServes(engine)).serves === 'one') {+ checks.push(infoCheck(NAME, 'Not applicable: this brain serves one person, so its own keys read its own pages.', 'not_applicable'));+ return checks;+ }+ 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 } }));+ return checks;+ }+ const details = ctx.remote ? { total: o.total, sensitive: o.sensitive, private: o.private, 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) {+ 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>).` });+ 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,+ { 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));+ }+ return checks;+}++export const openSharedPagesEntry: DoctorEntry = {+ name: 'open_shared_pages',+ emits: ['open_shared_pages'],+ run: runOpenSharedPages,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex ebdf124bcb..08a01262f7 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -150,6 +150,7 @@ import { ghostPagesEntry } from './checks/ghost-pages.ts';import { memberAccessEntry } from './checks/member-access.ts';import { folderAccessEntry } from './checks/folder-access.ts';import { unlabeledPeopleFoldersEntry } from './checks/unlabeled-people-folders.ts';+import { openSharedPagesEntry } from './checks/open-shared-pages.ts';import { unscopedSharedReadsEntry } from './checks/unscoped-shared-reads.ts';import { sharedStdioBindingEntry } from './checks/shared-stdio-binding.ts';import { sharedAgentAccessEntry } from './checks/shared-agent-access.ts';@@ -243,6 +244,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [memberAccessEntry,folderAccessEntry,unlabeledPeopleFoldersEntry,+ openSharedPagesEntry,unscopedSharedReadsEntry,sharedStdioBindingEntry,sharedAgentAccessEntry,diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.tsindex 28e76604ff..60686fd7ea 100644--- a/src/commands/setup-serves.ts+++ b/src/commands/setup-serves.ts@@ -22,7 +22,7 @@ import { opError, OperationError } from '../core/ops/contract.ts';import { bunSpawnSync } from '../core/spawn.ts';import { readRoster, rosterEmpty, type ServesReceipt, type ServesStatus, receiptLines, receiptOk } from './access-serves.ts';-export interface ServesFlags { serves?: 'one' | 'several'; members?: string; membersFile?: string; source?: string; stdioMember?: string; dryRun: boolean }+export interface ServesFlags { serves?: 'one' | 'several'; members?: string; membersFile?: string; source?: string; stdioMember?: string; labelledOnly?: boolean; dryRun: boolean }/** GST-363: the --stdio-member this harness entry will carry (member) and the one it carries now (previous). */export interface EntryBinding { member: string | null; previous: string | null }@@ -109,7 +109,7 @@ export function servesOneRefusal(status: ServesStatus | null, harness: string, e/** --serves several: the labelling child (preview on a dry run) and, when applied, one bound read per member. */function runServesSeveral(launcher: string, roster: string[], flags: ServesFlags): Omit<ServesOutcome, 'brain_serves'> {- const r = child(launcher, ['access', 'serves', 'several', '--members', roster.join(','), ...(flags.source ? ['--source', flags.source] : []), ...(flags.dryRun ? [] : ['--yes']), '--json']);+ const r = child(launcher, ['access', 'serves', 'several', '--members', roster.join(','), ...(flags.source ? ['--source', flags.source] : []), ...(flags.labelledOnly ? ['--labelled-only'] : []), ...(flags.dryRun ? [] : ['--yes']), '--json']);const receipt = parsed<ServesReceipt>(r.stdout);if (!receipt || !('members' in receipt)) return { mode: 'several', error: (r.stderr || r.stdout).trim() || 'gbrain access serves several failed' };if (flags.dryRun || receipt.error || !receipt.applied) return { mode: 'several', receipt };@@ -203,12 +203,21 @@ export function servesOk(o: ServesOutcome | null): boolean {return !o || (!o.error && (!o.receipt || receiptOk(o.receipt)) && (o.proof ?? []).every(p => p.leaked.length === 0));}+/** GST-2670 (F9): the proof covers the people/ folders only, so it names the open pages that member's key still reads. */+function openTail(r: ServesReceipt | undefined, member: string): string {+ const open = r?.open_pages;+ 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`;+}+export function servesLines(o: ServesOutcome, dryRun: boolean): string[] {return [...(o.receipt ? receiptLines(o.receipt).filter(l => !(dryRun && l.startsWith('Nothing written'))) : []),...(o.proof ?? []).map(p => p.leaked.length? ` proof ${p.member} reads pages of another member's folder: ${p.leaked.join(', ')}`- : ` proof a read bound to ${p.member} sees its own folder (${p.own} page(s)) and no page of another member's folder`),+ : ` proof a read bound to ${p.member} sees its own folder (${p.own} page(s)) and no page of another member's folder${openTail(o.receipt, p.member)}`),...(o.stdio ? [` stdio ${o.stdio.detail}`] : []),...(o.note ? [` labels ${o.note}`] : []),...(o.error ? [` error ${o.error}`] : []),diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 51b05be4f7..de28a8b9ec 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -162,6 +162,8 @@ Flags:people (2+ enabled members) refuses rather than write a connection boundto nobody, unless this harness's entry or config mcp.stdio_member binds it.--members IDS The people of --serves several, comma-separated (e.g. alice-example,bob-example).+ --labelled-only With --serves several: each member's key reads only pages labelled for+ that member (readable_by or a rule), never the owner's. Opt-in.--members-file PATH The same, one id per line.--stdio-member ID claude-code or codex: write serve --stdio-member ID into this harness'sMCP entry, so only its sessions read as ID (an enabled member, or one@@ -270,6 +272,8 @@ interface SetupFlags {serves?: 'one' | 'several';members?: string;membersFile?: string;+ /** GST-2670: --labelled-only, passed to access serves several. */+ labelledOnly?: boolean;/** GST-363: written into this harness's MCP entry as serve --stdio-member; never into config. */stdioMember?: string;noStdioMember: boolean;@@ -297,6 +301,7 @@ function parseFlags(args: string[]): SetupFlags | string {const serves = value('--serves');if (serves !== undefined && serves !== 'one' && serves !== 'several') return `unknown --serves '${serves}'; pass one or several`;if ((args.includes('--members') || args.includes('--members-file')) && serves !== 'several') return '--members and --members-file name the people of --serves several';+ if (args.includes('--labelled-only') && serves !== 'several') return '--labelled-only applies to the people of --serves several';let stdioMember: string | undefined;try { stdioMember = parseStdioMemberFlag(args); } catch (e) { return `${(e as Error).message}; nothing was written`; }const noStdioMember = args.includes('--no-stdio-member');@@ -356,6 +361,7 @@ function parseFlags(args: string[]): SetupFlags | string {...(serves ? { serves: serves as 'one' | 'several' } : {}),...(value('--members') !== undefined ? { members: value('--members') } : {}),...(value('--members-file') !== undefined ? { membersFile: value('--members-file') } : {}),+ ...(args.includes('--labelled-only') ? { labelledOnly: true } : {}),...(stdioMember !== undefined ? { stdioMember } : {}),noStdioMember,};diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 0e846faec2..5057d6ea1b 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -967,6 +967,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {// #5575 memory trust: [AGENT] ask_user while unclaimed sources hold legacy rows; never claims or scans (best-effort).await (await import('../core/trust/claim-notice.ts')).printTrustClaimUpgradeNotice(engine);await (await import('../core/access/requester-scope.ts')).printUnscopedReadsUpgradeNotice(engine); // GST-363: credentials bound to nobody on a several-people brain+ await (await import('../core/access/open-pages.ts')).printOpenPagesUpgradeNotice(engine); // GST-2670: open DM, chat and mail pages on a several-people brain// Ambient-writeback consent ask (WP8): one-shot for EXISTING installs// upgrading into the feature. Personal brains only; double-gated ondiff --git a/src/core/access/open-pages.ts b/src/core/access/open-pages.tsnew file mode 100644index 0000000000..1b8e327a38--- /dev/null+++ b/src/core/access/open-pages.ts@@ -0,0 +1,220 @@+/**+ * GST-2670 (GBRA-502): the pages every member's key can read on a brain that serves several people. A page is open+ * when no readable_by names readers and no applied or pending folder or page rule covers it: a key bound to a member+ * 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;+ * 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+ * one-person brain, or one pinned to access.serves one, never runs it. Everything is database state, so a repo-less+ * 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 { localFederatedSourceIds } from '../source-resolver.ts';+import { isStatementTimeout } from '../persistence/bounded-reads.ts';+import { agentBlock } from '../agent-markers.ts';+import { ownerMemberId } from './owner.ts';+import { brainServes } from './serves.ts';++export const OPEN_PAGES_TOP = 10;+export const OPEN_PAGES_TIMEOUT_MS = 30_000;+const RETRY = 'gbrain doctor --only open_shared_pages --json';++export interface OpenFolder { source: string; folder: string; pages: number; sensitive: number }+export 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. */+ members: { reading: number; counted: number };+ 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. */+ private: number;+ folders: OpenFolder[];+ other: { folders: number; pages: number; sensitive: number };+ top_sensitive: { source: string; type: string; pages: number } | null;+}+export interface OpenPagesError { code: string; message: string; retry: string }+export interface OpenPagesRead { open_pages: OpenPages | null; open_pages_error?: OpenPagesError }++export interface OpenPagesOptions {+ /** Members a run is about to add or keep, the source their new keys write (access serves several), and whether it marks them labelled-only. */+ planned?: { members: readonly string[]; source: string; labelledOnly: boolean };+ /** Prefixes a rule the run adds will cover, left out of the count. */+ exclude?: ReadonlyArray<{ source: string; prefix: string }>;+}++/** The sources a key minted for `source` reads: that source, or for default the default source and every federated one. */+async function mintedReadSources(engine: BrainEngine, source: string): Promise<string[]> {+ if (source !== 'default') return [source];+ return 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>>> {+ const reads = 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')) {+ if (m.id === owner) continue;+ reads.set(m.id, new Set());+ if (m.labelled_only === true) labelledOnly.add(m.id);+ }+ const memo = new Map<string, Promise<string[]>>();+ const sourcesOf = (grant: PrincipalGrant) => {+ const key = JSON.stringify([grant.principal.kind, grant.scopes, grant.sources]);+ if (!memo.has(key)) memo.set(key, credentialReadSources(engine, grant));+ return memo.get(key)!;+ };+ const credentials: Array<{ member: string; grant: PrincipalGrant }> = [+ ...(await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE revoked_at IS NULL AND member_id IS NOT NULL'))+ .map(row => ({ member: String(row.member_id), grant: grantFromTokenRow(row as never) })),+ ...(await engine.executeRaw<Record<string, unknown>>('SELECT * FROM oauth_clients WHERE deleted_at IS NULL AND member_id IS NOT NULL'))+ .map(row => ({ member: String(row.member_id), grant: grantFromClient(grantFromRow(row)) })),+ ];+ for (const { member, grant } of credentials) {+ const set = reads.get(member);+ if (set) for (const s of await sourcesOf(grant)) set.add(s);+ }+ if (planned) {+ const minted = await mintedReadSources(engine, planned.source);+ for (const id of planned.members) {+ if (id === owner) continue;+ const set = reads.get(id) ?? new Set<string>();+ reads.set(id, set);+ for (const s of minted) set.add(s);+ if (planned.labelledOnly) labelledOnly.add(id);+ }+ }+ for (const id of labelledOnly) reads.get(id)?.clear();+ return reads;+}++async function bounded<T>(engine: BrainEngine, fn: (e: BrainEngine) => Promise<T>): Promise<T> {+ if (engine.kind !== 'postgres') return fn(engine);+ return engine.transaction(async (tx) => {+ await tx.executeRaw(`SET LOCAL statement_timeout = ${OPEN_PAGES_TIMEOUT_MS}`);+ return fn(tx);+ });+}++/** The open pages the counted members' keys read (OpenPages); throws when the access state cannot be read. */+export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}): Promise<OpenPages> {+ return withoutCallerAccess(async () => {+ const [state] = await engine.executeRaw<{ unreadable: unknown }>('SELECT gbrain_access_state_unreadable() AS unreadable');+ if (state?.unreadable === true) {+ 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 reading = [...reads.values()].filter(s => s.size > 0);+ const sources = [...new Set(reading.flatMap(s => [...s]))].sort();+ 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 params: unknown[] = [sources];+ const exclude = (opts.exclude ?? []).map(x => {+ params.push(x.source, x.prefix);+ return ` AND NOT (p.source_id = $${params.length - 1} AND starts_with(p.slug, $${params.length}))`;+ }).join('');+ const rows = await bounded(engine, e => e.executeRaw<{ source: string; folder: string; type: string | null; visible: unknown; pages: number | string }>(+ `SELECT p.source_id AS source, CASE WHEN strpos(p.slug, '/') > 0 THEN split_part(p.slug, '/', 1) ELSE '(root)' END AS folder,+ p.type AS type, (${privacyPartSql('p')}) AS visible, count(*)::int AS pages+ FROM pages p+ WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND ${accessAllowedSql('p', [], [])}${exclude}+ GROUP BY 1, 2, 3, 4`, params));+ const folders = new Map<string, OpenFolder>();+ 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; }+ 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);+ f.pages += n;+ result.total += n;+ if (!row.type || !SENSITIVE_PAGE_TYPES.includes(row.type)) continue;+ f.sensitive += n;+ result.sensitive += n;+ const t = byType.get(`${row.source}/${row.type}`) ?? { source: row.source, type: row.type, pages: 0 };+ byType.set(`${row.source}/${row.type}`, t);+ t.pages += n;+ }+ const sorted = [...folders.values()].sort((a, b) => b.pages - a.pages || a.source.localeCompare(b.source) || a.folder.localeCompare(b.folder));+ result.folders = sorted.slice(0, OPEN_PAGES_TOP);+ for (const f of sorted.slice(OPEN_PAGES_TOP)) { result.other.folders++; result.other.pages += f.pages; result.other.sensitive += f.sensitive; }+ result.top_sensitive = [...byType.values()].sort((a, b) => b.pages - a.pages || a.type.localeCompare(b.type))[0] ?? null;+ return result;+ });+}++/** openPages that never throws: the count, or null with what went wrong and the command that retries it. */+export async function readOpenPages(engine: BrainEngine, opts: OpenPagesOptions = {}): Promise<OpenPagesRead> {+ try {+ return { open_pages: await openPages(engine, opts) };+ } catch (e) {+ const code = (e as { code?: string }).code === 'open_pages_unknown' ? 'open_pages_unknown' : isStatementTimeout(e) ? 'open_pages_timeout' : 'open_pages_failed';+ return { open_pages: null, open_pages_error: { code, message: e instanceof Error ? e.message : String(e), retry: RETRY } };+ }+}++const folderName = (f: OpenFolder) => f.folder === '(root)' ? `${f.source}:(root)` : `${f.source}:${f.folder}/`;++/** The headline: whose keys read how many open pages. */+export function openPagesHeadline(o: OpenPages): string {+ if (!o.total) return "Every page the members' keys read names its readers (readable_by or a rule).";+ const pages = `${o.total} ${o.total === 1 ? 'page' : 'pages'}, and the facts drawn from them, that no rule or readable_by restricts`;+ const sensitive = o.sensitive ? `, ${o.sensitive} of them DMs, chat or mail` : '';+ return o.members.reading+ ? `The keys of ${o.members.reading} of ${o.members.counted} members can read ${pages}${sensitive}.`+ : `No member's key reads the ${pages}${sensitive}: every member other than the owner is labelled-only or has no key.`;+}++/**+ * The lines that show the open pages and the commands that label them, the owner first in every reader list.+ * labelledOnly: the command that keeps members to labelled pages where the lines are shown.+ */+export function openPagesLines(read: OpenPagesRead, opts: { prefix?: string; labelledOnly?: string } = {}): string[] {+ const head = opts.prefix ?? ' open pages ';+ const pad = ' '.repeat(head.length);+ const o = read.open_pages;+ if (!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 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 [+ head + openPagesHeadline(o),+ `${pad}${where}.`,+ ...(o.top_sensitive ? [`${pad}DMs, chat and mail: keep members to pages labelled for them (${opts.labelledOnly ?? 'gbrain access member labelled-only <member> on'}), then name each page set's readers: gbrain repair visibility --source ${o.top_sensitive.source} --slugs-file <file> --readers ${readers} (preview, then --apply --expect <hash>).`] : []),+ ...(shared ? [`${pad}A folder its readers share: gbrain access rule add --prefix ${shared.folder}/ --readers ${readers} --source ${shared.source} (preview, then --yes).`] : []),+ `${pad}New pages: put readable_by: [${o.owner ? `${o.owner}, ` : ''}<list>] in their frontmatter.`,+ ];+}++/** gbrain post-upgrade: the open DM, chat and mail pages on a brain that serves several people. Best effort; prints nothing otherwise. */+export async function printOpenPagesUpgradeNotice(engine: BrainEngine): Promise<void> {+ try {+ if ((await brainServes(engine)).serves !== 'several') return;+ const read = await readOpenPages(engine);+ if (!read.open_pages?.sensitive) 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.`,+ actor: 'user',+ next: 'Relay the list below to the user and ask who should read each folder. Nothing was changed; each command previews first.',+ verify: RETRY,+ }).trimEnd());+ for (const line of openPagesLines(read, { prefix: ' ' })) console.log(line);+ } catch { /* cosmetic; never blocks the upgrade */ }+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 015349b4b7..175c30646c 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,7 +14,7 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--email', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--kind', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--raw-only', '--readers', '--reads-unscoped', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--slug', '--source', '--sources', '--stdio-member', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--email', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--kind', '--labelled-only', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--raw-only', '--readers', '--reads-unscoped', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--slug', '--source', '--sources', '--stdio-member', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -97,7 +97,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backend', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--synopsis', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backend', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expect', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--prefix', '--quiet', '--readers', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--slugs-file', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--synopsis', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--advertise', '--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],'protocol': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],@@ -123,8 +123,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--request-id', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--apply', '--backend', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],- 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--limit', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-providers', '--no-stdio-member', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--show-toplevel', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--surface', '--token', '--url', '--workspace', '--yes'],+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--labelled-only', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-providers', '--no-stdio-member', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--show-toplevel', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--surface', '--token', '--url', '--workspace', '--yes'],'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--no-extensions', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--show-toplevel', '--skill-loading', '--source', '--text', '--top-gate', '--top-k'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],@@ -140,7 +140,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],'trust': ['--accept-all', '--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--label-lowerings', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backend', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-downgrade', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--synopsis', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backend', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-downgrade', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expect', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--prefix', '--quiet', '--readers', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--slugs-file', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--synopsis', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'wakeshift': ['--apply', '--brain', '--expect', '--help', '--json', '--key-stdin', '--max-cost', '--max-usd', '--non-interactive', '--source', '--trust', '--url', '--yes'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 473abd0298..47df52e03f 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -102,6 +102,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['access_policy_store_mismatch',// GST-363: a brain that serves several people keeps each people/<name>/ folder to its readers (doctor/checks/unlabeled-people-folders.ts).'unlabeled_people_folders',+ // GST-2670: pages every member's key reads on a brain that serves several people (doctor/checks/open-shared-pages.ts).+ 'open_shared_pages',// GST-363: credentials bound to nobody on a brain that serves several people (doctor/checks/unscoped-shared-reads.ts).'unscoped_shared_reads',// GST-363: config mcp.stdio_member set on a host where OpenClaw or Hermes is installed (doctor/checks/shared-stdio-binding.ts).diff --git a/src/core/grants/shared-exposure.ts b/src/core/grants/shared-exposure.tsindex 6da4f79707..5bb2845a02 100644--- a/src/core/grants/shared-exposure.ts+++ b/src/core/grants/shared-exposure.ts@@ -40,6 +40,8 @@ export const CHANNEL_PLUGINS: readonly string[] = ['telegram', 'discord', 'slackconst DM_PAGE_TYPES: readonly string[] = ['slack-dm-day', 'dm', 'sms'];export const CHAT_PAGE_TYPES: readonly string[] = [...new Set([...pageTypesForAllowed(['slack', 'imessage', 'imessage-daily']), ...DM_PAGE_TYPES,'discord', 'telegram', 'whatsapp', 'signal', 'chat', 'channel'])];+/** GST-2670: the page types an open page counts as sensitive on a brain that serves several people (src/core/access/open-pages.ts). */+export const SENSITIVE_PAGE_TYPES: readonly string[] = [...new Set([...CHAT_PAGE_TYPES, 'email', 'conversation'])];export const MULTI_CHANNEL_MIN = 2;const DOCS = 'docs/mcp/ADMIN.md#one-token-several-people';diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 079ed9341b..aa393a601d 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -88,6 +88,7 @@" [INFO] access_policy_invalid: Not applicable: no source has a folder rule."," [INFO] access_policy_store_mismatch: Not applicable: no source has a folder rule."," [INFO] unlabeled_people_folders: Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ " [INFO] open_shared_pages: Not applicable: this brain serves one person, so its own keys read its own pages."," [INFO] unscoped_shared_reads: Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several)."," [INFO] shared_stdio_binding: Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member."," [INFO] access_may_act_for_wildcard: Not applicable: no page names readers and no member exists.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 4ce1f946c1..b25bf4b7c4 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1084,6 +1084,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex a1e2a02db9..79038dde89 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1155,6 +1155,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -6481,6 +6490,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex bcbb72de8b..a8e5e26961 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1151,6 +1151,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -6481,6 +6490,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 534415ee7a..baae681f73 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -997,6 +997,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex a41c98640d..a0220b28d0 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1044,6 +1044,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 0967acc272..b732261816 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1040,6 +1040,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person, so its own keys read its own pages.",+ "name": "open_shared_pages",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/open-shared-pages.test.ts b/test/open-shared-pages.test.tsnew file mode 100644index 0000000000..61e8d4c95d--- /dev/null+++ b/test/open-shared-pages.test.ts@@ -0,0 +1,249 @@+/**+ * GST-2670 (GBRA-502): pages every member's key can read on a brain that serves several people.+ *+ * 1. Protects: a brain that serves several people says how many pages no rule or readable_by restricts, per folder,+ * in the access serves several preview and receipt, gbrain access serves, doctor (open_shared_pages) and+ * post-upgrade, with the labelling commands (owner first in every reader list) and an opt-in --labelled-only flag.+ * A one-person brain, and one pinned to access.serves one, runs no query and prints nothing new. The count writes+ * nothing, never depends on who asks, and a failed count never stops setup.+ * 2. Fails when: the count differs from what a member key lists, depends on the caller record, counts labelled-only+ * members or the owner as readers, misses DM, chat, conversation or mail types, double-counts the people folders+ * this run covers, throws out of the preview, writes anything, or runs on a one-person brain.+ * 3. Existing coverage: setup-serves-several.test.ts (members, rules, keys, proof), access-labelled-only.test.ts (the grant).+ * 4. Real seams: PGLite repo-less (Postgres when DATABASE_URL is set); member keys verified by the serve --http verifier+ * and dispatched remote=true.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { labelSeveral, receiptLines, receiptOk } from '../src/commands/access-serves.ts';+import { openPages, readOpenPages, printOpenPagesUpgradeNotice } from '../src/core/access/open-pages.ts';+import { SENSITIVE_PAGE_TYPES } from '../src/core/grants/shared-exposure.ts';+import { openSharedPagesEntry } from '../src/commands/doctor/checks/open-shared-pages.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { addMember } from '../src/core/access/members.ts';+import { setOwner } from '../src/core/access/owner.ts';+import { setMemberLabelledOnly } from '../src/core/access/labelled-only.ts';+import { withCallerAccess } from '../src/core/search/private-visibility.ts';+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const ROSTER = ['alice-example', 'bob-example'];+const fm = (type: string, extra = '') => `---\ntype: ${type}\ntitle: t\n${extra}---\n# t\n\nHarbor ledger body.\n`;+const PAGES: Array<[string, string]> = [+ ['notes/world-topic', fm('note')],+ ['chats/dm-1', fm('dm')],+ ['emails/thread-1', fm('email')],+ ['chats/export-1', fm('conversation')],+ ['meetings/standup', fm('meeting')],+ ['root-page', fm('note')],+ ['labelled/secret', fm('note', 'readable_by: [alice-example]\n')],+ ['private/diary', fm('note', 'visibility: private\n')],+ ['people/alice-example/plan', fm('note')],+ ['people/bob-example/plan', fm('note')],+];+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });+const tempDir = (p: string) => { const d = mkdtempSync(join(tmpdir(), p)); roots.push(d); return d; };++/** Counts the queries over the pages table (the open-pages count is one). */+function spyPages(engine: BrainEngine): { count: () => number; restore: () => void } {+ const own = Object.prototype.hasOwnProperty.call(engine, 'executeRaw');+ const original = engine.executeRaw;+ let n = 0;+ (engine as any).executeRaw = function (this: BrainEngine, sql: string, params?: unknown[]) { if (/FROM pages p\b/.test(sql) && /folder/.test(sql)) n++; return original.call(this, sql, params as never); };+ return { count: () => n, restore: () => { if (own) (engine as any).executeRaw = original; else delete (engine as any).executeRaw; } };+}++async function stateHash(engine: BrainEngine): Promise<string> {+ const rows = await Promise.all([+ engine.executeRaw("SELECT slug, source_id, frontmatter::text AS f FROM pages ORDER BY source_id, slug"),+ engine.executeRaw("SELECT source_id, rule_id FROM access_rules ORDER BY 1, 2"),+ engine.executeRaw("SELECT key, value FROM config WHERE key NOT LIKE 'doctor.%' ORDER BY key"),+ engine.executeRaw("SELECT id, labelled_only, disabled_at FROM access_members ORDER BY id"),+ ]);+ return JSON.stringify(rows);+}++for (const kind of testBackends()) {+ describe(`open pages on a brain that serves several people (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let home: string;+ const label = (roster: string[], apply = true, opts: { labelledOnly?: boolean } = {}) =>+ withEnv({ GBRAIN_HOME: home, GBRAIN_SETUP_ABORT_AFTER: undefined }, () => labelSeveral(engine, roster, 'default', apply, true, opts));+ const doctor = async (remote = false) => (await openSharedPagesEntry.run({ engine, remote } as unknown as DoctorContext) as Array<Record<string, any>>)[0]!;+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ async function listedAs(member: string): Promise<string[]> {+ const token = readFileSync(join(home, '.gbrain', 'member-keys', `${member}.key`), 'utf8').trim();+ const auth = await provider().verifyAccessToken(token) as unknown as AuthInfo;+ const sourceId = auth.sourceId ?? 'default';+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);+ const out = await dispatchToolCall(engine, 'list_pages', { limit: 100 }, {+ remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'], ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });+ return (JSON.parse(out.content[0]!.text) as Array<{ slug: string }>).map(p => p.slug).sort();+ }++ beforeAll(async () => {+ 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(); }+ home = tempDir('gbrain-open-pages-');+ for (const [slug, text] of PAGES) await importFromContent(engine, slug, text, { sourceId: 'default', noEmbed: true });+ }, 120_000);+ afterAll(async () => { await close?.(); }, 60_000);++ test('sensitive types cover DMs, chat exports, conversations and mail, not meetings', () => {+ for (const t of ['dm', 'slack-dm-day', 'email', 'conversation', 'chat']) expect(SENSITIVE_PAGE_TYPES).toContain(t);+ expect(SENSITIVE_PAGE_TYPES).not.toContain('meeting');+ });++ test('a one-person brain runs no count and says nothing new', async () => {+ const spy = spyPages(engine);+ try {+ expect(await doctor()).toMatchObject({ name: 'open_shared_pages', status: 'ok', readiness_state: 'not_applicable' });+ const logs: string[] = [];+ const log = console.log; console.log = (...a: unknown[]) => { logs.push(a.join(' ')); };+ try { await printOpenPagesUpgradeNotice(engine); } finally { console.log = log; }+ expect(logs).toEqual([]);+ expect(spy.count()).toBe(0);+ } finally { spy.restore(); }+ }, 60_000);++ test('a brain pinned to access.serves one with two enabled members runs no count either', async () => {+ await addMember(engine, 'pin-a-example'); await addMember(engine, 'pin-b-example');+ await engine.setConfig('access.serves', 'one');+ const spy = spyPages(engine);+ try {+ expect(await doctor()).toMatchObject({ status: 'ok', readiness_state: 'not_applicable' });+ const logs: string[] = [];+ const log = console.log; console.log = (...a: unknown[]) => { logs.push(a.join(' ')); };+ try { await printOpenPagesUpgradeNotice(engine); } finally { console.log = log; }+ expect(logs).toEqual([]);+ expect(spy.count()).toBe(0);+ } finally { spy.restore(); await engine.unsetConfig('access.serves'); }+ await engine.executeRaw("UPDATE access_members SET disabled_at = now() WHERE id IN ('pin-a-example', 'pin-b-example')");+ }, 60_000);++ test('the preview counts open pages per folder, leaves out the people folders this run covers, and writes nothing', async () => {+ const before = await stateHash(engine);+ const r = await label(ROSTER, false);+ expect(r.applied).toBe(false);+ expect(r.open_pages).toMatchObject({ total: 6, sensitive: 3, private: 1, members: { reading: 2, counted: 2 } });+ const folders = Object.fromEntries(r.open_pages!.folders.map(f => [f.folder, [f.pages, f.sensitive]]));+ expect(folders).toEqual({ chats: [2, 2], emails: [1, 1], notes: [1, 0], meetings: [1, 0], '(root)': [1, 0] });+ expect(await stateHash(engine)).toBe(before);+ const text = receiptLines(r).join('\n');+ expect(text).toContain('The keys of 2 of 2 members can read 6 pages');+ expect(text).toContain('--labelled-only');+ }, 60_000);++ test('after apply the receipt carries the same count, the exit verdict is unchanged, and it matches what a member key lists', async () => {+ const r = await label(ROSTER);+ expect(r.error).toBeUndefined();+ expect(receiptOk(r)).toBe(true);+ expect(r.open_pages).toMatchObject({ total: 6, sensitive: 3 });+ const listed = await listedAs('bob-example');+ expect(listed.filter(s => s !== 'people/bob-example/plan')).toEqual(['chats/dm-1', 'chats/export-1', 'emails/thread-1', 'meetings/standup', 'notes/world-topic', 'root-page']);+ }, 60_000);++ test('the count is the same whoever asks: no caller, a member, a labelled-only member and the owner', async () => {+ const base = (await openPages(engine)).total;+ const as = (access: Record<string, unknown>) => withCallerAccess(access as never, () => openPages(engine));+ expect((await as({ identity: ['member:alice-example'] })).total).toBe(base);+ expect((await as({ identity: ['member:alice-example'], labelledOnly: true })).total).toBe(base);+ expect((await as({ identity: ['member:alice-example'], owner: true, lineage: true, ownerReadsRestricted: true })).total).toBe(base);+ }, 60_000);++ test('doctor warns while DM, chat or mail pages are open; remote callers get totals only; nothing is written', async () => {+ const before = await stateHash(engine);+ const c = await doctor();+ expect(c).toMatchObject({ name: 'open_shared_pages', status: 'warn' });+ expect(c.details.open_pages.total).toBe(6);+ expect(c.fix.ask_user).toBe(true);+ expect(c.fix.argv.slice(0, 3)).toEqual(['gbrain', 'list', '--type']);+ expect(c.fix.argv.join(' ')).not.toContain('<');+ const remote = await doctor(true);+ expect(JSON.stringify(remote.details)).not.toMatch(/chats|emails|notes|meetings/);+ expect(remote.details).toMatchObject({ total: 6, sensitive: 3 });+ expect(await stateHash(engine)).toBe(before);+ }, 60_000);++ test('post-upgrade prints the list while sensitive pages are open', async () => {+ const logs: string[] = [];+ const log = console.log; console.log = (...a: unknown[]) => { logs.push(a.join(' ')); };+ try { await printOpenPagesUpgradeNotice(engine); } finally { console.log = log; }+ expect(logs.join('\n')).toContain('chats/');+ }, 60_000);++ test('with an owner set, every printed reader list starts with the owner, and the flags exist', async () => {+ await setOwner(engine, 'alice-example');+ const text = receiptLines(await label(ROSTER, false)).join('\n');+ const lists = [...text.matchAll(/--readers (\S+)/g)].map(m => m[1]!);+ expect(lists.length).toBeGreaterThan(0);+ for (const l of lists) expect(l.startsWith('alice-example,')).toBe(true);+ expect(CLI_FLAG_REGISTRY.access).toContain('--labelled-only');+ expect(CLI_FLAG_REGISTRY.repair).toEqual(expect.arrayContaining(['--slugs-file', '--readers']));+ }, 60_000);++ test('the owner and labelled-only members are never counted as readers', async () => {+ const r1 = await openPages(engine);+ expect(r1.members).toEqual({ reading: 1, counted: 1 });+ await setMemberLabelledOnly(engine, 'bob-example', true, { remote: false });+ const r2 = await openPages(engine);+ expect(r2.members).toEqual({ reading: 0, counted: 1 });+ await setMemberLabelledOnly(engine, 'bob-example', false, { remote: false });+ }, 60_000);++ test('--labelled-only marks the roster, refuses the owner before writing, and is idempotent', async () => {+ const blocked = await label(['alice-example', 'bob-example'], true, { labelledOnly: true });+ expect(blocked.applied).toBe(false);+ expect(blocked.members.find(m => m.id === 'alice-example')).toMatchObject({ action: 'blocked' });+ expect((await engine.executeRaw<{ labelled_only: boolean }>("SELECT labelled_only FROM access_members WHERE id = 'bob-example'"))[0]!.labelled_only).toBe(false);+ const r = await label(['bob-example'], true, { labelledOnly: true });+ expect(r.error).toBeUndefined();+ expect(r.members[0]).toMatchObject({ id: 'bob-example', labelled_only: 'set' });+ expect((await engine.executeRaw<{ labelled_only: boolean }>("SELECT labelled_only FROM access_members WHERE id = 'bob-example'"))[0]!.labelled_only).toBe(true);+ expect((await label(['bob-example'], true, { labelledOnly: true })).members[0]).toMatchObject({ labelled_only: 'keep' });+ expect(r.open_pages!.members.reading).toBe(0);+ 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 });+ expect((await openPages(engine)).total).toBe(before - 1);+ }, 60_000);++ test('a failed count is reported, never thrown: the preview, the receipt verdict and doctor go on', async () => {+ const original = engine.executeRaw;+ (engine as any).executeRaw = function (this: BrainEngine, sql: string, params?: unknown[]) { return /gbrain_access_state_unreadable\(\) AS unreadable/.test(sql) ? Promise.resolve([{ unreadable: true }]) : original.call(this, sql, params as never); };+ try {+ const r = await label(['bob-example'], false);+ expect(r.open_pages).toBeNull();+ expect(r.open_pages_error).toMatchObject({ code: 'open_pages_unknown' });+ expect(receiptOk(r)).toBe(true);+ expect(receiptLines(r).join('\n')).toContain('count unknown');+ expect((await readOpenPages(engine)).open_pages).toBeNull();+ expect((await doctor()).status).toBe('warn');+ } finally { delete (engine as any).executeRaw; }+ }, 60_000);++ test('doctor reports information, not a warning, once only non-sensitive pages are open', async () => {+ for (const slug of ['chats/export-1', 'emails/thread-1']) await importFromContent(engine, slug, fm(slug.startsWith('emails') ? 'email' : 'conversation', 'readable_by: [bob-example]\n'), { sourceId: 'default', noEmbed: true });+ const c = await doctor();+ expect(c).toMatchObject({ status: 'ok', severity: 'info' });+ expect(c.details.open_pages.sensitive).toBe(0);+ }, 60_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 83a1c88f68..ced7870407 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -367,6 +367,7 @@ test/notifier-retry-unwatched-gst2515.test.tstest/on-commit-embedding.serial.test.tstest/oneshot-consumer-direct-route.test.tstest/oneshot-housekeeping-cli.test.ts+test/open-shared-pages.test.tstest/origin-guard-6948.test.tstest/origin-twin-sequence-7150.test.tstest/origin-twins-6948.test.ts