Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Owner reads derived pages of origins it reads; operator opt-in for pages kept to other members (GST-2490)
garrytan9c2f649c0378
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ce18e08ba4..aa9c2ebd87 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**The brain owner reads the derived pages and facts of pages it can already read, and the operator can let the owner read pages kept to other members.** An atom, a synthesized concept, a Life Chronicle event, a page with `derived_from` or a fact made from a page under a folder rule, or from a page that names readers, was hidden from every remote caller, the owner included, even when the rule or the readers named the owner. Credentials bound to the owner now read them whenever they read every origin, with no setting. A new opt-in, `gbrain access owner reads-restricted on`, off by default and settable only by the operator on the brain host, lets the owner also read pages that readers lists, folder rules and page rules keep to other members, with their derived pages and facts, but never another member's own member page. Nothing changes for any other caller or for writes, and nothing changes on upgrade.++### Itemized changes++#### Owner reads and the owner opt-in (GST-2490)++- Migration v304 (`src/core/schema-migrations/v304-access-owner-origin.ts`): `gbrain_access_origin_closed_for()` and `gbrain_access_origin_hidden_for()`, the lineage arms of `gbrain_access_origin_restricted()` asked per origin for one caller. Only owner reads call them; `gbrain_access_origin_restricted()` is unchanged. Nothing is rewritten.+- `src/core/search/private-visibility.ts`: `ownerAccessSql` for owner reads (read-only operations only: `remoteCallerAccess` in `src/core/access/caller.ts`, `src/mcp/dispatch.ts`, `src/core/minions/tools/brain-allowlist.ts`, and `--as <owner>` in `src/cli/as-preview.ts`), fact provenance and the readers checks for single rows; the search cache key and the hot-memory key carry the owner mode.+- `src/core/access/owner.ts`, `src/commands/access.ts`: `gbrain access owner reads-restricted on|off` (refused for remote callers), shown by `gbrain access owner`, `access check` (`owner_reads_restricted`) and `who-can-read`; `whoami` adds `owner_reads_restricted` for every remote caller while it is on; doctor `access_owner_reads_restricted` (`src/commands/doctor/checks/owner-reads-restricted.ts`).+- Unchanged on purpose: what every other caller reads, every write and publication check, member private facts, personal sources, shared-room audiences and attested calls.+- Docs: `docs/guides/access-designations.md` (derived pages, member access, the owner opt-in), key-files entry.+- Tests: `test/owner-reads-restricted.test.ts` (opt-in off and on, owner, other members and unbound keys, `--as`, writes, the remote refusal; PGLite and Postgres, rules in the database and in `access.yml`); doctor goldens.+## [0.60.680.0] - 2026-11-11**gbrain now tells you when a privacy label it doesn't recognize leaves a page readable.** A page with no `visibility` counts as private only when `access` is private, restricted or confidential, or `confidentiality` is confidential, secret, private or restricted. Any other value, such as `access: personal` or a confidentiality value naming a health record, was ignored without a word, so the page read as world to every remote caller and could be committed to the brain's git remote. Writes and doctor now say so. Who can read a page does not change.diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex a6f502986b..58a7e9a960 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, 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. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) on the stored actor, else the stored audience, and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).+- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal). 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.ownerLineage`, read-only ops only) uses `ownerAccessSql`: 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). A derivative of a page that names readers is otherwise hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, 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. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) 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/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 2+ enabled members) 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).- `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.diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.mdindex 88b2598320..ef5490ccd9 100644--- a/docs/guides/access-designations.md+++ b/docs/guides/access-designations.md@@ -115,7 +115,9 @@ These rules follow the origin, so nobody writes them by hand:origin may be a private transcript);- an atom whose origin page is private, a concept with a private input, a chronicle event from a private meeting,and any page whose `derived_from` names a private page are private whatever their own field says;-- anything derived from a page that names `readable_by` is hidden from every remote caller.+- anything derived from a page that names `readable_by` or sits under a folder or page rule is hidden from every+ remote caller, except a credential bound to the owner: the owner reads a derived page or a fact when it reads every+ origin of it (a folder rule kept to the owner, or readers that list the owner).`gbrain repair visibility` stamps the explicit value on derived pages (tighten-only). The owner reads them all.@@ -129,8 +131,8 @@ Pinned-question pages are the owner's own and read as private. The owner reads tadd --prefix <folder>/ --readers <list>` does the same for a folder, and `--slug <page>` for exactly one page (a pageat the source root, or one whose file left git, which a `visibility` edit cannot reach; upgrade every host that sharesthe brain first, because an older one stops syncing a git-backed source that holds a page rule). This is the boundary between people in a-shared brain, and it binds the owner too: the owner reads such a page only when listed. No grant, hatch or owner-binding relaxes it. Use it for a page that belongs to specific people in a shared brain; a single-user brain needs+shared brain, and it binds the owner too: the owner reads such a page only when listed, unless the brain operator+turns on the owner opt-in (below). No grant or hatch relaxes it. Use it for a page that belongs to specific people in a shared brain; a single-user brain needsnone. The page's writers set it; widening a folder rule waits for `gbrain access apply`. A credential bound to amember with `default` or a federated source as its write source gets it on the pages it creates there (`readable_by: [member:<id>]`),except the owner's, whose new pages stay shared (`POST /ingest` still refuses both). See@@ -153,6 +155,17 @@ database, so a repo-less brain works the same. The owner relaxation applies to awhen it speaks for itself (no audience, or an audience of the owner alone); never to a shared-room audience or anattested call. `gbrain access owner clear` turns it off.+**The owner opt-in.** `gbrain access owner reads-restricted on` (config `access.owner_reads_restricted`, off by+default and unchanged on upgrade) lets the owner's credentials read the pages that `readable_by` lists, folder rules+and page rules keep to other members, and their derived pages and facts, on every read path: HTTP tokens, OAuth+clients, a stdio server bound to the owner, and `--as <owner>`. It never opens another member's own member page+(`memory/members/<id>`), its derived pages or its facts, never widens a write (the owner still writes only the pages+its readers and rules name), and changes nothing any other caller reads. Only the brain operator on the brain host+sets it; a remote caller is refused. While it is on, `gbrain access check` and `gbrain access who-can-read` show the+owner among the readers, every remote caller's `whoami` says so, and doctor reports `access_owner_reads_restricted`.+`gbrain access owner reads-restricted off` is the undo. Turn it on only when the members agree that the owner reads+what is kept to them, for example a brain where the members are the owner's own groups and assistants.+One owner credential both reads every private page and writes new `default` pages that other members read, so anowner agent can copy private content into a shared page. A prompt planted in a page that agent reads can ask it to.Bind only agents you trust with the whole brain as the owner; give every other agent its own member, whose new pagesdiff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex c4dd24559d..55ff7f067b 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -979,6 +979,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: the owner opt-in (access.owner_reads_restricted) is off; the owner reads a page that names readers or sits under a rule only when listed.",+ "name": "access_owner_reads_restricted",+ "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 3460dd34fb..aca0f06173 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1026,6 +1026,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: the owner opt-in (access.owner_reads_restricted) is off; the owner reads a page that names readers or sits under a rule only when listed.",+ "name": "access_owner_reads_restricted",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/owner-reads-restricted.test.ts b/test/owner-reads-restricted.test.tsnew file mode 100644index 0000000000..d9d80eb317--- /dev/null+++ b/test/owner-reads-restricted.test.ts@@ -0,0 +1,296 @@+/**+ * GST-2490 (G6 of GST-2476): what credentials bound to the brain owner read, and the operator's owner opt-in.+ *+ * 1. Protects: an owner read keeps a derived page (an atom, a synthesized concept, a Life Chronicle event, a derived_from+ * page) and a fact when the owner reads every origin of it, with no setting: an origin under an owner-only folder+ * rule, or one whose readers name the owner. With config access.owner_reads_restricted on (set only by the operator+ * on the brain host), the owner also reads pages that readers lists, folder rules and page rules keep to other+ * members, with their derived pages and facts, on every read path; never another member's own member page+ * (memory/members/<id>), its derived pages or its facts. What every other caller reads is identical with the opt-in+ * off and on, writes are not widened, and a remote caller cannot turn it on.+ * 2. Fails when: a derivative or fact of an origin the owner reads stays hidden from the owner; the opt-in is off and+ * the owner reads another member's page or its derivative; the opt-in is on and the owner misses one, or reads a+ * member page; any other caller's view changes with the opt-in; the publication gate lets the owner write a page the+ * opt-in only lets it read; a remote caller sets the key; or the local --as owner preview disagrees with the key.+ * 3. Real seams: tokens minted by the token service and verified by the serve --http verifier, dispatched through MCP+ * dispatch (remote: true, transport http); rules in the database (repo-less brain) and in a committed access.yml+ * read by sync (git source); PGLite, and Postgres with DATABASE_URL; embeddings stubbed.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { setOwner, setOwnerReadsRestricted, ownerView } from '../src/core/access/owner.ts';+import { bindCredential } from '../src/core/access/members.ts';+import { proposeRevision, policyStatus } from '../src/core/access/policy.ts';+import { POLICY_FILE } from '../src/core/access/policy-git.ts';+import { performSync } from '../src/commands/sync.ts';+import { openAsPreview } from '../src/cli/as-preview.ts';+import { authorizePageVisibility } from '../src/core/persistence/page-visibility.ts';+import type { WriteAuthority } from '../src/core/persistence/model.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const DIMS = 1536;+function vectorFor(text: string): number[] {+ const v = new Array<number>(DIMS).fill(0);+ for (const w of text.toLowerCase().match(/[a-z]+/g) ?? []) {+ let h = 0;+ for (const ch of w) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ v[h % DIMS] += 1;+ }+ const n = Math.hypot(...v) || 1;+ return v.map(x => x / n);+}++const SRC = 'optin-src';+const OWNER = 'owner-example';+const git = (dir: string, ...args: string[]) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();++/** Origins: what keeps each one, and whether its derived pages and facts are built. */+const ORIGINS = {+ health: { slug: 'health/origin-example', fm: [] as string[], derive: true },+ grp: { slug: 'email/grp-origin', fm: [`readable_by: [${OWNER}, group:team-a]`], derive: true },+ team: { slug: 'team/origin-example', fm: [] as string[], derive: true },+ readers: { slug: 'notes/alice-readers', fm: ['readable_by: [alice-example]'], derive: false },+ ledger: { slug: 'notes/alice-ledger', fm: [] as string[], derive: false },+ member: { slug: 'memory/members/alice-example', fm: ['readable_by: [alice-example]'], derive: true },+ open: { slug: 'notes/open-example', fm: [] as string[], derive: false },+} as const;+type Origin = keyof typeof ORIGINS;+const DERIVED = ['atom', 'df', 'concept', 'event'] as const;+const slugOf = (o: Origin, d: string) => ({ atom: `atoms/${o}-atom`, df: `notes/${o}-derived`, concept: `concepts/${o}-concept`, event: `events/${o}-event` })[d]!;+const canary = (key: string) => 'canaryoptin' + key.replace(/[^a-z]/g, '') + 'x';++/** Every key the fixtures answer: an origin, a derived page (origin.kind) or a fact (origin.fact). */+const KEYS: string[] = [];+for (const [o, spec] of Object.entries(ORIGINS) as Array<[Origin, (typeof ORIGINS)[Origin]]>) {+ KEYS.push(o);+ if (spec.derive) for (const d of DERIVED) KEYS.push(`${o}.${d}`);+ if (spec.derive) KEYS.push(`${o}.fact`);+}+if (!ORIGINS.grp.derive) throw new Error('unreachable');++const doc = (title: string, key: string, fm: readonly string[], type = 'note') =>+ ['---', `type: ${type}`, `title: ${title}`, ...fm, '---', `# ${title}`, '', `Harbor ledger planning notes ${canary(key)} here.`].join('\n');++const RULES = [+ { id: 'health', prefix: 'health/', readers: [OWNER] },+ { id: 'team', prefix: 'team/', readers: ['alice-example'] },+ { id: 'ledger', slug: 'notes/alice-ledger', readers: ['alice-example'] },+];+const policyYaml = () => ['version: 1', 'rules:', ...RULES.flatMap(r => [` - id: ${r.id}`, r.prefix ? ` prefix: ${r.prefix}` : ` slug: ${r.slug}`, ` readable_by: [${r.readers.join(', ')}]`])].join('\n') + '\n';++/** Read paths: each returns text that names a key's canary when the caller reads it. */+const READS: Array<[string, string, (slug: string) => Record<string, unknown>, boolean]> = [+ ['get_page', 'get_page', slug => ({ slug }), true],+ ['list_pages', 'list_pages', () => ({ limit: 100 }), false],+ ['search', 'search', () => ({ query: 'harbor ledger planning notes', fields: 'full', limit: 100 }), false],+ ['search keyword', 'search', () => ({ query: 'planning notes', match: 'keyword', fields: 'full', limit: 100 }), false],+ ['query', 'query', () => ({ query: 'harbor ledger planning notes', expand: false, fields: 'full', limit: 100 }), false],+ ['facts since', 'recall', () => ({ since: '2000-01-01', limit: 100 }), false],+ ['facts question', 'recall', () => ({ question: 'harbor fact planning' }), false],+];++for (const kind of testBackends()) {+ for (const store of ['database', 'git'] as const) {+ describe(`owner reads and the owner opt-in (${kind}, rules in ${store === 'git' ? 'access.yml' : 'the database, repo-less'})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let root = '';+ const tokens: Record<string, string> = {};+ const tokenIds: Record<string, string> = {};+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });++ async function call(who: string, op: string, params: Record<string, unknown>): Promise<string> {+ if (who === 'as-owner') {+ const preview = await openAsPreview(engine, OWNER, op);+ const out = await preview.run(() => dispatchToolCall(engine, op, { ...params }, preview.context({ remote: false, sourceId: SRC }) as never));+ return out.content.map(c => c.text).join('\n');+ }+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;+ const sourceId = auth.sourceId ?? 'default';+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);+ const out = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'],+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}),+ });+ return out.content.map(c => c.text).join('\n');+ }++ const pageSlug = (key: string): string | null => {+ const [o, d] = key.split('.') as [Origin, string | undefined];+ return d === undefined ? ORIGINS[o].slug : d === 'fact' ? null : slugOf(o, d);+ };+ /** The keys `who` reads on each path. */+ async function seenBy(who: string): Promise<Record<string, string[]>> {+ __resetPrivateVisibilityCacheForTests();+ const out: Record<string, string[]> = {};+ for (const [label, op, params, perPage] of READS) {+ const seen = new Set<string>();+ if (perPage) {+ for (const key of KEYS) { const slug = pageSlug(key); if (slug && (await call(who, op, params(slug))).includes(canary(key))) seen.add(key); }+ } else {+ const text = await call(who, op, params(''));+ for (const key of KEYS) if (op === 'list_pages' ? (pageSlug(key) !== null && text.includes(`"${pageSlug(key)}"`)) : text.includes(canary(key))) seen.add(key);+ }+ out[label] = KEYS.filter(k => seen.has(k));+ }+ for (const o of Object.keys(ORIGINS) as Origin[]) {+ if (!ORIGINS[o].derive) continue;+ if ((await call(who, 'recall', { entity: ORIGINS[o].slug })).includes(canary(`${o}.fact`))) (out['facts entity'] ??= []).push(`${o}.fact`);+ }+ out['facts entity'] ??= [];+ return out;+ }+ /** What a reader of exactly these origins sees on every path: pages on page paths, facts on fact paths. */+ const expected = (origins: Origin[], derivedOf: Origin[]) => {+ const pages = KEYS.filter(k => { const [o, d] = k.split('.') as [Origin, string | undefined]; return d === undefined ? origins.includes(o) : d !== 'fact' && derivedOf.includes(o); });+ const facts = KEYS.filter(k => { const [o, d] = k.split('.') as [Origin, string | undefined]; return d === 'fact' && derivedOf.includes(o); });+ const out: Record<string, string[]> = {};+ for (const [label, op] of READS) {+ // Search finds a remembered fact through its entity page's indexed facts fence on the repo-less brain; the git fixture never re-syncs that page.+ const withFacts = op === 'query' || (op === 'search' && store === 'database');+ out[label] = op === 'recall' ? facts : withFacts ? KEYS.filter(k => pages.includes(k) || facts.includes(k)) : pages;+ }+ out['facts entity'] = facts;+ return out;+ };+ const withOptIn = async <T>(fn: () => Promise<T>): Promise<T> => {+ await setOwnerReadsRestricted(engine, true, { remote: false });+ __resetPrivateVisibilityCacheForTests();+ try { return await fn(); } finally { await setOwnerReadsRestricted(engine, false, { remote: false }); __resetPrivateVisibilityCacheForTests(); }+ };++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ for (const id of [OWNER, 'alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);+ await engine.executeRaw("INSERT INTO access_groups (id) VALUES ('team-a')");+ await engine.executeRaw("INSERT INTO access_group_members (group_id, member_id) VALUES ('team-a', 'bob-example')");+ if (store === 'git') {+ root = mkdtempSync(join(tmpdir(), 'gbrain-optin-'));+ git(root, 'init', '-q', '-b', 'main');+ git(root, 'config', 'user.email', '[email protected]');+ git(root, 'config', 'user.name', 't');+ for (const [o, spec] of Object.entries(ORIGINS) as Array<[Origin, (typeof ORIGINS)[Origin]]>) {+ mkdirSync(join(root, spec.slug, '..'), { recursive: true });+ writeFileSync(join(root, `${spec.slug}.md`), doc(`${o} origin`, o, spec.fm) + '\n');+ }+ mkdirSync(join(root, '.gbrain'), { recursive: true });+ writeFileSync(join(root, POLICY_FILE), policyYaml());+ git(root, 'add', '-A');+ git(root, 'commit', '-q', '-m', 'pages and policy');+ await engine.executeRaw("INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, '{}')", [SRC, root]);+ await performSync(engine, { sourceId: SRC, repoPath: root, noPull: true, noEmbed: true, full: true, concurrency: 1 });+ expect((await policyStatus(engine, SRC)).store).toBe('git');+ } else {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ await proposeRevision(engine, SRC, RULES.map(r => ({ id: r.id, prefix: r.prefix ?? r.slug, readable_by: r.readers.map(m => `member:${m}`) }) as never), { origin: 'cli', store: 'database' });+ for (const [o, spec] of Object.entries(ORIGINS) as Array<[Origin, (typeof ORIGINS)[Origin]]>) await importFromContent(engine, spec.slug, doc(`${o} origin`, o, spec.fm), { sourceId: SRC });+ }+ for (const [o, spec] of Object.entries(ORIGINS) as Array<[Origin, (typeof ORIGINS)[Origin]]>) {+ if (!spec.derive) continue;+ await importFromContent(engine, slugOf(o, 'atom'), doc(`${o} atom`, `${o}.atom`, [`source_slug: ${spec.slug}`], 'atom'), { sourceId: SRC });+ await importFromContent(engine, slugOf(o, 'df'), doc(`${o} derived`, `${o}.df`, [`derived_from: [${spec.slug}]`]), { sourceId: SRC });+ await importFromContent(engine, slugOf(o, 'concept'), doc(`${o} concept`, `${o}.concept`, ['synthesized_by: fixture'], 'concept'), { sourceId: SRC });+ await engine.addLink(slugOf(o, 'concept'), slugOf(o, 'atom'), 'input', 'synthesized_from', 'concept-provenance', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });+ await importFromContent(engine, slugOf(o, 'event'), doc(`${o} event`, `${o}.event`, ['captured_via: life-chronicle:fixture', 'event:', ` depth: ${spec.slug}`], 'event'), { sourceId: SRC });+ if (store === 'git') {+ // A git source's pages change only through the checkout, so remember refuses there on Postgres; this is the row a facts fence on the origin would yield.+ await engine.executeRaw("INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_markdown_slug, valid_from) VALUES ($1, $2, $3, 'fact', 'world', 'fixture', $2, now())",+ [SRC, spec.slug, `Harbor fact planning ${canary(`${o}.fact`)}`]);+ continue;+ }+ const remembered = await dispatchToolCall(engine, 'remember', { fact: `Harbor fact planning ${canary(`${o}.fact`)}`, provenance: 'fixture', entity: spec.slug, visibility: 'world' }, { remote: false, sourceId: SRC });+ if (remembered.isError) throw new Error(`fixture remember: ${remembered.content.map(c => c.text).join(' ')}`);+ }+ for (const [name, member] of [['owner', OWNER], ['alice', 'alice-example'], ['bob', 'bob-example'], ['unbound', null]] as const) {+ const minted = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });+ tokens[name] = minted.token;+ tokenIds[name] = minted.id;+ if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member });+ }+ await setOwner(engine, OWNER);+ }, 300_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ if (root) rmSync(root, { recursive: true, force: true });+ }, 60_000);++ test('fixture control: a trusted local caller reads every page and fact', async () => {+ const seen: string[] = [];+ for (const key of KEYS) {+ const slug = pageSlug(key);+ const text = slug ? (await dispatchToolCall(engine, 'get_page', { slug }, { remote: false, sourceId: SRC })).content.map(c => c.text).join('\n')+ : (await dispatchToolCall(engine, 'recall', { since: '2000-01-01', limit: 100 }, { remote: false, sourceId: SRC })).content.map(c => c.text).join('\n');+ if (text.includes(canary(key))) seen.push(key);+ }+ expect(seen).toEqual(KEYS);+ }, 120_000);++ test('with no setting, the owner reads the derived pages and facts of every origin it reads, and nothing kept to other members', async () => {+ expect(await seenBy('owner')).toEqual(expected(['health', 'grp', 'open'], ['health', 'grp']));+ }, 300_000);++ test('the opt-in extends that to pages and rules kept to other members, never another member\'s member page', async () => {+ await withOptIn(async () => {+ expect((await ownerView(engine)).reads_restricted).toBe(true);+ expect(await seenBy('owner')).toEqual(expected(['health', 'grp', 'team', 'readers', 'ledger', 'open'], ['health', 'grp', 'team']));+ });+ }, 300_000);++ test('the local --as owner preview reads what the owner\'s key reads, off and on', async () => {+ expect(await seenBy('as-owner')).toEqual(await seenBy('owner'));+ await withOptIn(async () => { expect(await seenBy('as-owner')).toEqual(await seenBy('owner')); });+ }, 600_000);++ test('every other caller reads exactly the same with the opt-in off and on', async () => {+ for (const who of ['alice', 'bob', 'unbound']) {+ const off = await seenBy(who);+ expect({ who, on: await withOptIn(() => seenBy(who)) }).toEqual({ who, on: off });+ }+ const alice = await seenBy('alice');+ expect(alice['get_page']).toEqual(['team', 'readers', 'ledger', 'member', 'open']);+ expect((await seenBy('bob'))['get_page']).toEqual(['grp', 'open']);+ expect((await seenBy('unbound'))['get_page']).toEqual(['open']);+ }, 600_000);++ test('the opt-in widens no write: the publication gate keeps the owner to the pages its readers and rules name', async () => {+ const writable = async () => {+ const authority = { version: 1, principal: { kind: 'legacy_token', id: tokenIds.owner }, remote: true, excludePrivate: true, sourceId: SRC,+ sourceIncarnation: 'unused', scopes: ['read', 'write'], operations: null, slugPrefixes: null } as WriteAuthority;+ const out: Origin[] = [];+ for (const o of Object.keys(ORIGINS) as Origin[]) if (await authorizePageVisibility(engine, authority, ORIGINS[o].slug).then(() => true, () => false)) out.push(o);+ return out;+ };+ const off = await writable();+ expect(off).toEqual(['health', 'grp', 'open']);+ expect(await withOptIn(writable)).toEqual(off);+ }, 120_000);++ test('only the operator on the brain host sets the opt-in; a remote caller is refused and nothing changes', async () => {+ await expect(setOwnerReadsRestricted(engine, true, { remote: true })).rejects.toThrow();+ expect(await engine.getConfig('access.owner_reads_restricted')).not.toBe('1');+ }, 60_000);+ });+ }+}