Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Labelled-only members no longer read unlabelled pages through recorded-time, amendment and fact-by-id lookups
garrytan5200c91a2d27
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5111b59b0c..95ad87368c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,12 +20,14 @@ identifiers and attribution are available in the pre-removal Git revision- The labelled-only migration (`src/core/schema-migrations/`, numbered at merge): `access_members.labelled_only` (default false) and the SQL function `gbrain_access_origin_labelled_for()`, which passes a derived page only when it has an origin and every origin names the caller. Nothing is rewritten.- `src/core/access/labelled-only.ts`: `gbrain access member labelled-only <id> [on|off]`, local operator only (remote callers get `permission_denied`), never on the owner (`access_labelled_only_owner`, exit 3; `gbrain access owner` refuses a labelled-only member the same way).-- `src/core/search/private-visibility.ts`: `CallerAccess.labelledOnly` adds one conjunct to every caller page, version and fact filter; derived pages and facts that name nobody fail closed, and under member lineage pass only when every origin names the caller. `src/core/access/caller.ts`, `actor.ts` and `src/cli/as-preview.ts` set it for a labelled-only member, never the owner.+- `src/core/search/private-visibility.ts`: `CallerAccess.labelledOnly` adds one conjunct to every caller page, version and fact filter; derived pages and facts that name nobody fail closed, and under member lineage pass only when every origin names the caller. Facts on the member's own member page stay readable, lineage on or off. `src/core/access/caller.ts`, `actor.ts` and `src/cli/as-preview.ts` set it for a labelled-only member, and `labelledOnlyFor` never reports the configured owner, on any door.+- The remote read floor: `remoteReadFloorSql` and `remoteProvenanceFloorSql` (`private-visibility.ts`) are the plain page and fact fragments plus the labelled-only conjunct, and exactly the plain fragments for every other caller. Every remote read gate that is not caller-aware uses them: recorded-time reads (`get_page` and `get_versions` with `known_as_of`), the `as_of` amendment list, fact lookups by id (`remember replaces`, `forget`), belief history, proactive briefs, entity resolution and the sources-not-readable check. `test/remote-read-floor.test.ts` lists the write-side, maintenance and classification sites that keep the plain fragment, each with its reason.+- Attested reads: a read that names sources for a labelled-only person is refused (`permission_denied`, `src/core/access/scope-read.ts`), since the scope read drops the member identity and the grant with it.- Writes: `src/core/persistence/page-visibility.ts` holds a labelled-only writer to the same read rule and refuses a create that would not name it (`access_labelled_only_unnamed`, checked in page preparation, streamed uploads and capture ingest); the enforced member CLI (`src/cli/enforced-member.ts`) does the same.- The semantic cache key (`xlo=1`) and the per-caller key (`labelled_only`) separate a labelled-only caller.- `gbrain access member list`, `access check` and `who-can-read` report it; doctor `access_labelled_only_members`.- Docs: `docs/guides/access-designations.md` (labelled-only members), `docs/guides/error-codes.md`, key-files entry.-- Tests: `test/access-labelled-only.test.ts` (every read path, derived pages and facts with member lineage off and on, older versions, writes over MCP and in the enforced CLI, the owner and remote refusals, cache keys, check, who-can-read and doctor; PGLite and Postgres, rules in the database and in `access.yml`); migration, catalog and doctor goldens.+- Tests: `test/access-labelled-only.test.ts` (every read path, derived pages and facts with member lineage off and on, older versions, recorded-time and `as_of` reads, a fact by id, the member's own facts, the attested scope-read refusal and owner, writes over MCP, streamed uploads, capture ingest and the enforced CLI, the owner and remote refusals, cache keys, check, who-can-read and doctor; PGLite and Postgres, rules in the database and in `access.yml`); `test/remote-read-floor.test.ts`; migration, catalog and doctor goldens.## [0.60.689.0] - 2026-11-12diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex fe3fd73a99..f68aa3086c 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`). 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`: FALSE, or under member lineage a provenance page that passes); under member lineage a derived row may pass through `gbrain_access_origin_labelled_for()` (every origin labelled, none missing). 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 stores). 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. 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 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.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 stores). 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. 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 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 b852775521..b0dc588a5e 100644--- a/docs/guides/access-designations.md+++ b/docs/guides/access-designations.md@@ -230,12 +230,18 @@ member CLI included. So is every derived page and fact that names nobody (summar`derived_from` pages): they fail closed. With `access.members_read_lineage` on, a derived page or fact passes only when ithas at least one origin and every origin names the member; one unlabelled origin keeps it hidden. An older versioncounts only if that version itself named the member or a rule over the page lists it, so adding `readable_by` to a-page does not open its unlabelled history.+page does not open its unlabelled history. The member's own memory stays readable: facts on its own member page (the+ones its `remember` calls saved) pass with lineage on or off. Under a shared agent's audience, the label test uses the+audience's identities, not the bound member's, so a page must name someone in the audience. An attested read for a+labelled-only person that names sources would run as the scope, with no member identity and so without the grant, so it+is refused (`permission_denied`); leave the sources out to read as the person.The grant lives on the member, not on one credential, so a second key for the same member cannot forget it. Writesfollow the same rule: the member cannot update a page it cannot read, and a page it creates must name it-(`access_labelled_only_unnamed`; add `readable_by: [<member>]` or ask for a rule over the folder). It never applies-to the owner: setting it there, or naming a labelled-only member the owner, is refused with exit 3+(`access_labelled_only_unnamed`; add `readable_by: [<member>]` or ask for a rule over the folder). A `put_page` to an+existing slug the member cannot read answers `page_not_found`, and to a new slug `access_labelled_only_unnamed`, the same+existence pattern pages with readers already have. It never applies to the owner, even if the flag is stored on the+owner's row: setting it there, or naming a labelled-only member the owner, is refused with exit 3(`access_labelled_only_owner`) and asks the user. Only the brain operator on the brain host sets it; a remote caller isrefused (`permission_denied`). `gbrain access member list` and `gbrain access check` show it, `who-can-read` noteswhich labelled-only members a page leaves out, and doctor's `access_labelled_only_members` lists them. An older gbraindiff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex fb35d14640..d5b53da069 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -8,7 +8,7 @@"test/access-folder-rules.test.ts": 33058,"test/access-folder-scoped-role.test.ts": 3693,"test/access-hidden-page-writes.test.ts": 16117,- "test/access-labelled-only.test.ts": 91440,+ "test/access-labelled-only.test.ts": 101796,"test/access-member-facts.test.ts": 15215,"test/access-member-sweep.test.ts": 32626,"test/access-members-read-lineage.test.ts": 94453,diff --git a/src/core/access/labelled-only.ts b/src/core/access/labelled-only.tsindex 3744aebc76..307527e5da 100644--- a/src/core/access/labelled-only.ts+++ b/src/core/access/labelled-only.ts@@ -18,6 +18,7 @@ import { hostOnlyError } from '../ops/op-fix.ts';import { ACCESS_ID_RE } from './principals.ts';import { assertAccessId, boundCredentials, existingMember, getMember, type MemberRecord } from './members.ts';import { labelledOnlyOwnerError, ownerMemberId } from './owner.ts';+import { OWNER_MEMBER_KEY } from '../search/private-visibility.ts';/*** Marks a member labelled-only or clears it. Only the trusted local operator may (remote strictly false), and never on the@@ -65,13 +66,14 @@ export async function anyLabelledOnlyMember(engine: Pick<BrainEngine, 'executeRa/*** Whether a read or write by these identities is labelled-only: one of their members carries the grant. A table that* cannot be read counts as yes (fail closed: it only narrows). Identities without a member (unbound, a group, a guest)- * are never labelled-only.+ * are never labelled-only, and neither is the configured owner (access.owner_member), whichever door the call came in by.*/export async function labelledOnlyFor(engine: Pick<BrainEngine, 'executeRaw'>, identities: readonly (readonly string[])[]): Promise<boolean> {const members = [...new Set(identities.flat().filter(p => p.startsWith('member:')).map(p => p.slice('member:'.length)).filter(id => ACCESS_ID_RE.test(id)))];if (!members.length) return false;try {- return (await engine.executeRaw('SELECT 1 FROM access_members WHERE labelled_only AND id = ANY($1::text[]) LIMIT 1', [members])).length > 0;+ return (await engine.executeRaw(`SELECT 1 FROM access_members WHERE labelled_only AND id = ANY($1::text[])+ AND id IS DISTINCT FROM (SELECT btrim(value) FROM config WHERE key = $2) LIMIT 1`, [members, OWNER_MEMBER_KEY])).length > 0;} catch {return true;}diff --git a/src/core/access/scope-read.ts b/src/core/access/scope-read.tsindex a339aad616..a04b27a133 100644--- a/src/core/access/scope-read.ts+++ b/src/core/access/scope-read.ts@@ -54,6 +54,17 @@ export function attestedReadMode(op: string, params: Record<string, unknown> | ureturn 'scope';}+/**+ * GBRA-108 design 1: a scope read takes the member's identity away, and with it the labelled-only grant, so it would+ * open every unlabelled page of the named sources. An attested read for a labelled-only member that names sources is+ * refused instead, before anything is read.+ */+export function scopeReadLabelledOnlyRefused(op: string): OperationError {+ return opError('permission_denied', `${op}: this person is labelled-only, so a read that names sources cannot run as their audience. Nothing was read.`,+ 'Leave source_id and source_ids out to read as the person, which shows only the pages labelled for them.',+ { why: 'A scope read drops the member identity, and the labelled-only grant with it, so it would show pages nobody labelled for this person.' });+}+function contextPackScopeRefused(): OperationError {return opError('invalid_params', 'context_pack: a call that names sources would read them as the person, and this credential reads named sources as their audience, so it is refused. Nothing was read.','Leave source_id, source_ids, all_sources and entity_refs out to read as the person, or call query, get_page or entity with source_id for the scope.',diff --git a/src/core/belief/history.ts b/src/core/belief/history.tsindex fb8fdaaa62..3793b85567 100644--- a/src/core/belief/history.ts+++ b/src/core/belief/history.ts@@ -21,7 +21,7 @@* inherits no history.*/import type { BrainEngine } from '../engine.ts';-import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { remoteReadFloorSql } from '../search/private-visibility.ts';import { quarantineFilterFragment } from '../quarantine.ts';export interface BeliefHistoryRow {@@ -61,7 +61,7 @@ export async function readBeliefHistoryPage(engine: BrainEngine, q: BeliefHistorconst rows = await engine.executeRaw<BeliefHistoryRow & { stream_visible: boolean | null; later_private: boolean; take_holder: string | null }>(`SELECT e.id, e.slug, e.page_lifetime::text AS page_lifetime,e.subject_kind, e.subject_key, e.event_type, e.origin, e.trust_tier, e.writer_tier, e.tier_basis, e.visibility, e.recorded_at, e.source_time,e.value, e.value_hash, e.prior_hash, e.state_hash, e.cause, e.purged, e.redacted_fields,- (SELECT ${privatePagesFilterFragment('p')} AND (e.subject_kind NOT IN ('fact', 'take') OR ${quarantineFilterFragment('p')}) FROM belief_page_lifetimes l JOIN pages p ON p.source_id = l.source_id AND p.slug = l.slug+ (SELECT ${remoteReadFloorSql('p')} AND (e.subject_kind NOT IN ('fact', 'take') OR ${quarantineFilterFragment('p')}) FROM belief_page_lifetimes l JOIN pages p ON p.source_id = l.source_id AND p.slug = l.slugAND p.deleted_at IS NULL AND (l.page_id IS NULL OR p.id = l.page_id)WHERE l.page_lifetime = e.page_lifetime AND l.ended_at IS NULL) AS stream_visible,(e.claim_fp IS NOT NULL AND EXISTS (SELECT 1 FROM belief_events v WHERE v.source_id = e.source_id AND v.source_incarnation = e.source_incarnation@@ -84,7 +84,7 @@ export async function readBeliefHistoryPage(engine: BrainEngine, q: BeliefHistorconst linkIds = [...new Set(out.filter(r => r.subject_kind === 'link' || r.subject_kind === 'link_transition').flatMap(r => linkLifetimes(r.subject_key)))];const visibleLifetimes = new Set(linkIds.length ? (await engine.executeRaw<{ page_lifetime: string }>(`SELECT l.page_lifetime::text AS page_lifetimeFROM belief_page_lifetimes l JOIN pages p ON p.source_id = l.source_id AND p.slug = l.slug AND p.deleted_at IS NULL AND (l.page_id IS NULL OR p.id = l.page_id)- WHERE l.page_lifetime = ANY($1::uuid[]) AND l.ended_at IS NULL AND ${privatePagesFilterFragment('p')}`, [linkIds])).map(r => r.page_lifetime) : []);+ WHERE l.page_lifetime = ANY($1::uuid[]) AND l.ended_at IS NULL AND ${remoteReadFloorSql('p')}`, [linkIds])).map(r => r.page_lifetime) : []);const holders = new Set(q.takesHolders ?? ['world']);return page(out.filter(r => r.visibility === 'world' && r.later_private !== true&& (r.subject_kind !== 'take' || typeof r.take_holder === 'string' && holders.has(r.take_holder))diff --git a/src/core/belief/page-at-time.ts b/src/core/belief/page-at-time.tsindex 3ce61f4a2e..3202d8d9a6 100644--- a/src/core/belief/page-at-time.ts+++ b/src/core/belief/page-at-time.ts@@ -16,7 +16,7 @@import type { BrainEngine } from '../engine.ts';import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';-import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { remoteReadFloorSql } from '../search/private-visibility.ts';import { PAGE_INLINE_MAX_BYTES } from '../page-size-policy.ts';import { coverageAt } from './coverage-report.ts';@@ -271,6 +271,6 @@ function coverageRefusal(c: { code: 'coverage_from' | 'coverage_gap'; from: stri/** A remote caller reads an interval only when its event was world-visible when recorded and its page is visible now; it fails closed when the page row is gone. */export async function remoteMayRead(engine: BrainEngine, pageId: number | null, interval: PageInterval): Promise<boolean> {if (pageId == null || interval.event.visibility !== 'world') return false;- const [row] = await engine.executeRaw<{ visible: boolean }>(`SELECT ${privatePagesFilterFragment('p')} AS visible FROM pages p WHERE p.id = $1 AND p.deleted_at IS NULL`, [pageId]);+ const [row] = await engine.executeRaw<{ visible: boolean }>(`SELECT ${remoteReadFloorSql('p')} AS visible FROM pages p WHERE p.id = $1 AND p.deleted_at IS NULL`, [pageId]);return row?.visible === true;}diff --git a/src/core/context/proactive-brief.ts b/src/core/context/proactive-brief.tsindex 5a98822d00..937a7e5e15 100644--- a/src/core/context/proactive-brief.ts+++ b/src/core/context/proactive-brief.ts@@ -19,7 +19,7 @@ import { isConfigTruthy } from '../config.ts';import { HALFLIFE_DAYS } from '../facts/decay.ts';import { listOpenLoops, type OpenLoopRow } from '../loops/loops-store.ts';import { normalizeAlias } from '../search/alias-normalize.ts';-import { privateFactFilterForCaller, privatePagesFilterForCaller, privatePagesFilterFragment, privateTimelineEventFilterForCaller, privateTimelineEventFilterFragment } from '../search/private-visibility.ts';+import { privateFactFilterForCaller, privatePagesFilterForCaller, privateTimelineEventFilterForCaller, privateTimelineEventFilterFragment, remoteReadFloorSql } from '../search/private-visibility.ts';import { pageEligibleSql, projectionEligibleSql } from '../eligibility/sql.ts';import type { ReadEligibility } from '../eligibility/policy.ts';import { renderTrustedInline, trustFields } from '../eligibility/labels.ts';@@ -203,7 +203,7 @@ async function entityPages(const rows = await engine.executeRaw<{ slug: string; title: string | null; type: string | null }>(`SELECT p.slug, p.title, p.type FROM pages pWHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND p.deleted_at IS NULL- ${opts.excludePrivate ? `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : privatePagesFilterFragment('p')}` : ''}+ ${opts.excludePrivate ? `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : remoteReadFloorSql('p')}` : ''}AND ${pageEligibleSql('p', opts.eligibility)}`,[sourceId, slugs],);@@ -281,7 +281,7 @@ export async function upcomingMeetings(engine: BrainEngine, clock: BriefClock, eFROM pages pWHERE p.deleted_at IS NULL AND p.type = 'meeting' AND p.source_id = ANY($1::text[])AND p.frontmatter->>'start' >= $2 AND p.frontmatter->>'start' <= $3- AND ${privatePagesFilterFragment('p')} AND ${pageEligibleSql('p', eligibility)}`,+ AND ${remoteReadFloorSql('p')} AND ${pageEligibleSql('p', eligibility)}`,[fresh, lo, `${hi}~`],);const out: UpcomingMeeting[] = [];@@ -342,7 +342,7 @@ export async function meetingCounterparties(`SELECT a.alias_norm, p.slug, p.title, p.type FROM page_aliases aJOIN pages p ON p.source_id = a.source_id AND p.slug = a.slug AND p.deleted_at IS NULLWHERE a.source_id = $1 AND a.alias_norm = ANY($2::text[])- AND ${privatePagesFilterFragment('p')} AND ${pageEligibleSql('p', eligibility)}`,+ AND ${remoteReadFloorSql('p')} AND ${pageEligibleSql('p', eligibility)}`,[sourceId, emails],);const byEmail = new Map<string, Array<{ slug: string; title: string | null; type: string | null }>>();@@ -484,7 +484,7 @@ async function editItem(engine: BrainEngine, cp: BriefCounterparty, clock: Briefp.timeline, p.trust_tier, p.write_originFROM pages pWHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL- AND ${opts.includePrivate ? 'TRUE' : opts.forCaller ? privatePagesFilterForCaller('p') : privatePagesFilterFragment('p')}+ AND ${opts.includePrivate ? 'TRUE' : opts.forCaller ? privatePagesFilterForCaller('p') : remoteReadFloorSql('p')}AND ${pageEligibleSql('p', opts.eligibility)}`,[cp.source_id, cp.slug, EDIT_MAX_PAGE_BYTES],);diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.tsindex 45c024533f..500e2e4d6b 100644--- a/src/core/context/retrieval-reflex.ts+++ b/src/core/context/retrieval-reflex.ts@@ -39,7 +39,7 @@ import { slugify } from '../entities/resolve.ts';import { stripTakesFence } from '../takes-fence.ts';import { stripFactsFence } from '../facts-fence.ts';import { redactFindings } from '../secret-scan.ts';-import { privatePagesFilterForCaller, privatePagesFilterFragment } from '../search/private-visibility.ts';+import { privatePagesFilterForCaller, remoteReadFloorSql } from '../search/private-visibility.ts';import type { EntityCandidate } from './entity-salience.ts';import { reflexPointerRationale } from './reflex-rationale.ts';import { preferEntityTitleMatches } from './title-matches.ts';@@ -239,7 +239,7 @@ export async function resolveEntitiesToPointers(// v0.46.15: weak-alias + surname arms share one kill switch (default ON).const lexicalArms = opts.lexicalArms !== false;- const privacySql = opts.excludePrivate === false ? '' : `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : privatePagesFilterFragment('p')}`;+ const privacySql = opts.excludePrivate === false ? '' : `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : remoteReadFloorSql('p')}`;// display lookup keyed by normalized query, so resolved slugs can recover a// human surface form for the pointer label.diff --git a/src/core/core-memory.ts b/src/core/core-memory.tsindex 125c2978d3..88213ebd53 100644--- a/src/core/core-memory.ts+++ b/src/core/core-memory.ts@@ -17,7 +17,7 @@import { createHash } from 'node:crypto';import type { BrainEngine } from './engine.ts';import { sanitizeRemoteBody } from './remote-body.ts';-import { privatePagesFilterForCaller, privatePagesFilterFragment } from './search/private-visibility.ts';+import { privatePagesFilterForCaller, remoteReadFloorSql } from './search/private-visibility.ts';import { quarantineFilterFragment } from './quarantine.ts';import { compareTrust, OWNER_TIER_FLOOR, type TrustTier } from './trust/tier.ts';import type { ReadEligibility } from './eligibility/policy.ts';@@ -254,7 +254,7 @@ export async function listCorePages(exec: RawExec, opts: ListCorePagesOpts = {})params.push(opts.exclude.sourceId, opts.exclude.slug);where.push(`NOT (p.source_id = $${params.length - 1} AND p.slug = $${params.length})`);}- if (opts.excludePrivate) where.push(opts.forCaller ? privatePagesFilterForCaller('p') : privatePagesFilterFragment('p'));+ if (opts.excludePrivate) where.push(opts.forCaller ? privatePagesFilterForCaller('p') : remoteReadFloorSql('p'));const policy = opts.eligibility;if (policy) where.push(quarantineFilterFragment('p'), pageEligibleSql('p', { floor: policy.floor }));const trustCols = policydiff --git a/src/core/entities/near-name.ts b/src/core/entities/near-name.tsindex fe5d2b2306..8f8856b791 100644--- a/src/core/entities/near-name.ts+++ b/src/core/entities/near-name.ts@@ -20,7 +20,7 @@import type { BrainEngine } from '../engine.ts';import { nameWords, matchNameVariant, editDistance, type NameMatchKind } from './name-variants.ts';import { isFactEntityPage } from './resolve.ts';-import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { remoteReadFloorSql } from '../search/private-visibility.ts';export type NearNameKind = 'same' | 'typo' | 'acronym';@@ -152,7 +152,7 @@ export interface EntityNameLoad { names: EntityName[]; truncated: boolean; alias*/export async function loadEntityNames(engine: BrainEngine, sourceId: string, opts: { excludePrivate?: boolean; max?: number } = {}): Promise<EntityNameLoad> {const max = opts.max ?? NEAR_NAME_MAX_ENTITIES;- const privacy = opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';+ const privacy = opts.excludePrivate ? `AND ${remoteReadFloorSql('p')}` : '';const rows = await engine.executeRaw<{ slug: string; type: string | null; title: string | null; aliases: unknown; distinct_from: unknown; created_at: string }>(`SELECT p.slug, p.type, p.title, p.frontmatter -> 'aliases' AS aliases, p.frontmatter -> 'distinct_from' AS distinct_from,p.created_at::text AS created_atdiff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex ff7e4684b1..be8bd37cf1 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -30,7 +30,7 @@ import { slugifySegment } from '../sync.ts';const siblingCanonical: typeof import('../mentions/siblings.ts').siblingCanonical = async (...args) =>(await import('../mentions/siblings.ts')).siblingCanonical(...args);import { isMissingSchemaObject } from '../utils.ts';-import { privatePagesFilterForCaller, privatePagesFilterFragment } from '../search/private-visibility.ts';+import { privatePagesFilterForCaller, remoteReadFloorSql } from '../search/private-visibility.ts';import { rankingLinkSql } from '../link-ranking-policy.ts';/**@@ -492,7 +492,7 @@ export async function resolveStrictEntityReference(): Promise<StrictResolution> {const trimmed = raw.trim();if (!trimmed) return { slug: null, miss: 'no_page' };- const privacy = opts.excludePrivate ? `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : privatePagesFilterFragment('p')}` : '';+ const privacy = opts.excludePrivate ? `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : remoteReadFloorSql('p')}` : '';const live = async (slugs: string[]) => slugs.length === 0 ? [] : engine.executeRaw<{ slug: string; type: string | null }>(`SELECT p.slug, p.type FROM pages pWHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug = ANY($2::text[]) ${privacy}`,@@ -574,7 +574,7 @@ export async function entityReferenceCandidates(const trimmed = raw.trim();const token = slugify(trimmed);if (!token) return [];- const privacy = opts.excludePrivate ? `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : privatePagesFilterFragment('p')}` : '';+ const privacy = opts.excludePrivate ? `AND ${opts.forCaller ? privatePagesFilterForCaller('p') : remoteReadFloorSql('p')}` : '';const aliases = await aliasHitSlugs(engine, source_id, trimmed).catch(() => [] as string[]);const prefixed = (await findPrefixCandidates(engine, source_id, token)).map(c => c.slug);const named = await engine.executeRaw<{ slug: string }>(diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex 10a5112671..18d86cb8bb 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -7,7 +7,7 @@ import { assertFactNotPurged } from './withdrawal.ts';import { cosineVerdict } from './capture-dedup.ts';import { interleaveFusion } from '../search/fusion-lists.ts';import { readSupersessionThreshold } from './supersession-threshold.ts';-import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';+import { remoteProvenanceFloorSql } from '../search/private-visibility.ts';import { pageNotVisibleError } from '../persistence/page-visibility.ts';import { slugUnderBoundPrefixes } from '../ops/context.ts';import { ownedPageWithdrawalSubject, onOwnedMemoryPageSql, withdrawalCoversFactSql } from '../access/member-facts.ts';@@ -66,7 +66,7 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: stri*/export async function factWithdrawnRefusal(engine: BrainEngine, sourceId: string, input: SingleFactIntent, opts: { excludePrivate?: boolean } = {}): Promise<OperationError> {// GST-359 D: a member writing to its own member page sees that page's withdrawn rows.- const seen = (param: number) => `(${privateProvenanceFilterFragment('f')} OR COALESCE(f.source_markdown_slug = $${param}::text, false))`;+ const seen = (param: number) => `(${remoteProvenanceFloorSql('f')} OR COALESCE(f.source_markdown_slug = $${param}::text, false))`;if (opts.excludePrivate) {const [backing] = await engine.executeRaw<{ visible: boolean; hidden: boolean }>(`SELECTCOALESCE(bool_or(${seen(5)}), false) AS visible,@@ -128,7 +128,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, inconst [exact] = await engine.executeRaw<FactCandidate>(`SELECT * FROM facts WHERE source_id=$1AND entity_slug IS NOT DISTINCT FROM $2 AND visibility=$3 AND expired_at IS NULLAND (valid_until IS NULL OR valid_until>now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($4)- AND ($5::text IS NULL OR attributed_to IS NULL OR attributed_to=$5)${opts.excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}+ AND ($5::text IS NULL OR attributed_to IS NULL OR attributed_to=$5)${opts.excludePrivate && !input.page_slug ? ` AND ${remoteProvenanceFloorSql('facts')}` : ''}AND ${input.page_slug ? 'source_markdown_slug=$6' : `($6::text IS NULL AND NOT ${onOwnedMemoryPageSql('facts')})`}ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact, input.attributed_to ?? null, input.page_slug ?? null]);if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };@@ -137,7 +137,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, ininput.page_slug ? { onlyPage: input.page_slug } : { excludeMemberPages: true });const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null; trust_tier: FactRow['trust_tier'];claim_metric: string | null; claim_unit: string | null; claim_period: string | null }>(- `SELECT id,source_markdown_slug,row_num,trust_tier,claim_metric,claim_unit,claim_period FROM facts WHERE source_id=$1 AND id=ANY($2::int[])${opts.excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`,+ `SELECT id,source_markdown_slug,row_num,trust_tier,claim_metric,claim_unit,claim_period FROM facts WHERE source_id=$1 AND id=ANY($2::int[])${opts.excludePrivate && !input.page_slug ? ` AND ${remoteProvenanceFloorSql('facts')}` : ''}`,[sourceId, candidates.map(c => c.id)]);let candidate: FactCandidate | null = null;let score = -1;@@ -196,7 +196,7 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, iEXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id AND w.visibility=f.visibilityAND w.fact_hash IN (gbrain_fact_fingerprint(f.fact),gbrain_fact_fingerprint_v1(f.fact))AND ${withdrawalCoversFactSql('w', 'f')}) AS withdrawn- FROM facts f WHERE f.id=$1 AND f.source_id=$2${!opts.excludePrivate ? '' : ownPage ? ` AND (f.source_markdown_slug = $3 OR ${privateProvenanceFilterFragment('f')})` : ` AND ${privateProvenanceFilterFragment('f')}`}${opts.lock ? ' FOR UPDATE OF f' : ''}`,+ FROM facts f WHERE f.id=$1 AND f.source_id=$2${!opts.excludePrivate ? '' : ownPage ? ` AND (f.source_markdown_slug = $3 OR ${remoteProvenanceFloorSql('f')})` : ` AND ${remoteProvenanceFloorSql('f')}`}${opts.lock ? ' FOR UPDATE OF f' : ''}`,opts.excludePrivate && ownPage ? [targetId, sourceId, ownPage] : [targetId, sourceId]);if (!target || (opts.remote && target.visibility !== 'world' && !(ownPage && target.source_markdown_slug === ownPage))) throw notFound();// #5913 [R2]: a slug-bound writer learns nothing about a fact outside its prefixes; the answer is the missing-id one.diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.tsindex 07a16b599f..07994c2e69 100644--- a/src/core/facts/subject-infer.ts+++ b/src/core/facts/subject-infer.ts@@ -24,7 +24,7 @@import type { BrainEngine } from '../engine.ts';import { extractCandidates, isCommonCapitalizedWord } from '../context/entity-salience.ts';import { isFactEntityPage, resolveStrictEntityReference, type StrictResolution } from '../entities/resolve.ts';-import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { remoteReadFloorSql } from '../search/private-visibility.ts';export type InferredVia = 'page' | 'mention';export type InferMissReason = 'ambiguous' | 'unverified_match' | 'no_mention' | 'no_page';@@ -224,7 +224,7 @@ function onlyExampleUses(fact: string, query: string): boolean {}async function liveFactEntityPage(engine: BrainEngine, sourceId: string, slug: string, excludePrivate?: boolean): Promise<string | null> {- const privacy = excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';+ const privacy = excludePrivate ? `AND ${remoteReadFloorSql('p')}` : '';const [row] = await engine.executeRaw<{ slug: string; type: string | null }>(`SELECT p.slug, p.type FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL ${privacy} LIMIT 1`,[sourceId, slug],diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.tsindex 1ba69ecb59..ebd9005de8 100644--- a/src/core/facts/withdrawal.ts+++ b/src/core/facts/withdrawal.ts@@ -5,7 +5,7 @@ import { fenceOperationError } from '../fence-repair/refusal.ts';import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';import { dropPurgedFenceRows } from './purge-overlay.ts';-import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';+import { remoteProvenanceFloorSql } from '../search/private-visibility.ts';import { outcomeMarkerSql } from './audit-sources.ts';import { coverageActive, noteBelief, readLedgerSource, withBeliefBatch } from '../belief/ledger.ts';import { createPageVersion } from '../page-state/versions.ts';@@ -56,7 +56,7 @@ export function reviewWithdrawOn(raw: string | null | undefined): boolean {* member-page fact (`memberPage`, positional $4; the caller checked it). Positional $3 is worldOnly.*/function withdrawalAdmitSql(excludePrivate?: boolean): string {- return `AND ($3::boolean=false OR visibility='world' OR (visibility='private' AND source_markdown_slug=$4::text))${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`;+ return `AND ($3::boolean=false OR visibility='world' OR (visibility='private' AND source_markdown_slug=$4::text))${excludePrivate ? ` AND ${remoteProvenanceFloorSql('facts')}` : ''}`;}/**diff --git a/src/core/ops/known-as-of.ts b/src/core/ops/known-as-of.tsindex 414435ae03..ad79a5c69c 100644--- a/src/core/ops/known-as-of.ts+++ b/src/core/ops/known-as-of.ts@@ -12,7 +12,7 @@ import { inlineBodyBytes } from './get-page-body.ts';import { historyQuarantine, pageTrustForRead, type QuarantinedView } from './get-page-projection.ts';import { parseKnownAsOf, readPageAtTime, remoteMayRead, type PageAtTime, type PageInterval } from '../belief/page-at-time.ts';import { sanitizeRemoteBody } from '../remote-body.ts';-import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { remoteReadFloorSql } from '../search/private-visibility.ts';import { unifiedDiff } from '../skillpack/diff-text.ts';import { fenceTranscriptText, quotesStored } from '../search/transcript-quote.ts';@@ -38,7 +38,7 @@ async function targetSource(ctx: OperationContext, p: Record<string, unknown>, oawait assertExplicitSourceLive(ctx, sourceIdParam);if (scope.sourceId) return scope.sourceId;const visible = ctx.remote === false ? '' : `AND e.visibility = 'world' AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = e.source_id AND p.slug = e.slug- AND p.deleted_at IS NULL AND ${privatePagesFilterFragment('p')})`;+ AND p.deleted_at IS NULL AND ${remoteReadFloorSql('p')})`;const rows = await ctx.engine.executeRaw<{ source_id: string }>(`SELECT DISTINCT e.source_id FROM belief_events eJOIN sources s ON s.id = e.source_id AND s.incarnation = e.source_incarnationWHERE e.slug = $1 AND e.subject_kind = 'page' AND ($2::text[] IS NULL OR e.source_id = ANY($2::text[])) ${visible} ORDER BY e.source_id`, [p.slug, scope.sourceIds ?? null]);@@ -59,7 +59,7 @@ async function readAsCaller(ctx: OperationContext, q: Parameters<typeof readPagereturn await readPageAtTime(ctx.engine, q);} catch (error) {if (ctx.remote === false || !PAGE_REFUSALS.has(String((error as { code?: unknown }).code))) throw error;- const [row] = await ctx.engine.executeRaw<{ visible: boolean }>(`SELECT ${privatePagesFilterFragment('p')} AS visible FROM pages p+ const [row] = await ctx.engine.executeRaw<{ visible: boolean }>(`SELECT ${remoteReadFloorSql('p')} AS visible FROM pages pWHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [q.sourceId, q.slug]);if (row?.visible === true) throw error;throw pageNotFoundError(ctx, q.slug, { includeDeleted, sourceIdParam: q.sourceId });diff --git a/src/core/ops/valid-time-read.ts b/src/core/ops/valid-time-read.tsindex 2669c83d51..4c76e8b7d9 100644--- a/src/core/ops/valid-time-read.ts+++ b/src/core/ops/valid-time-read.ts@@ -20,7 +20,7 @@ import { pageTrustForRead, readQuarantined } from './get-page-projection.ts';import { admitsTrust, type TrustTier } from '../trust/tier.ts';import { isCalendarDate } from '../link-validity.ts';import { replacedBecauseSql } from '../engine-sql/pages.ts';-import { callerReadersAllowedSql, privacyForCaller, privateLinkOriginFilterFragment, privatePagesFilterForCaller, privatePagesFilterFragment, privateSnapshotFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { callerReadersAllowedSql, privacyForCaller, privateLinkOriginFilterFragment, privatePagesFilterForCaller, privatePagesFilterFragment, privateSnapshotFilterFragment, remoteReadFloorSql, resolveExcludePrivatePages } from '../search/private-visibility.ts';import { fenceTranscriptText, isQuotedPageType, neutralizeToolCalls, quotesStored } from '../search/transcript-quote.ts';import { quotedPageMeta } from './get-page-projection.ts';import { sanitizeRemoteBody } from '../remote-body.ts';@@ -176,7 +176,7 @@ function verdictOf(asOf: string, picked: PickResult): ValidTimeVerdict {async function amendmentsNotApplied(tx: BrainEngine, pageId: number, editionFrom: string, asOf: string, excludePrivate: boolean, scope: { sourceId?: string; sourceIds?: string[] }) {const sources = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : null);const rows = await tx.executeRaw<{ slug: string; source_id: string; since: string | null }>(`SELECT f.slug, f.source_id, min(to_char(r.first_start, 'YYYY-MM-DD')) AS since- FROM links l JOIN pages f ON f.id = l.from_page_id AND f.deleted_at IS NULL${excludePrivate ? ` AND ${privatePagesFilterFragment('f')}` : ''}+ FROM links l JOIN pages f ON f.id = l.from_page_id AND f.deleted_at IS NULL${excludePrivate ? ` AND ${remoteReadFloorSql('f')}` : ''}LEFT JOIN link_relationships r ON r.from_page_id = l.from_page_id AND r.to_page_id = l.to_page_id AND r.link_type = l.link_type AND r.scope = $4WHERE l.to_page_id = $1 AND l.link_type = 'amends'${excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : ''}AND ($5::text[] IS NULL OR f.source_id = ANY($5::text[]))diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.tsindex 56ef6fdc68..7307f35f2d 100644--- a/src/core/persistence/drift-conflicts.ts+++ b/src/core/persistence/drift-conflicts.ts@@ -28,7 +28,7 @@ import { normalizeSlugPrefix } from '../ops/context.ts';import { resolveSourceLocalFilePath } from '../markdown.ts';import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';import { hardenedGitSync, hardenedPathDirty } from '../hardened-git.ts';-import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { remoteReadFloorSql } from '../search/private-visibility.ts';import { isValidSourceId } from '../source-id.ts';import { validateSlug } from '../utils.ts';import type { PageSnapshot } from '../page-state/types.ts';@@ -320,7 +320,7 @@ export async function auditDriftConflicts(engine: BrainEngine, sourceId: string,where.push(`(${alternatives.join(' OR ')})`);}if (!access.trusted || access.excludePrivate) {- where.push(`EXISTS (SELECT 1 FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug AND p.deleted_at IS NULL${access.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : ''})`);+ where.push(`EXISTS (SELECT 1 FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug AND p.deleted_at IS NULL${access.excludePrivate ? ` AND ${remoteReadFloorSql('p')}` : ''})`);}const filtered = where.join(' AND ');const [totals] = await engine.executeRaw<{ slugs: number; receipts: number }>(diff --git a/src/core/persistence/forget-prepare.ts b/src/core/persistence/forget-prepare.tsindex 74a9335d00..eb2999778a 100644--- a/src/core/persistence/forget-prepare.ts+++ b/src/core/persistence/forget-prepare.ts@@ -21,7 +21,7 @@ import { serializePageToMarkdown } from '../markdown.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { planFactWithdrawal, recordFactWithdrawal } from '../facts/withdrawal.ts';import { rebuildPendingPageProjections } from '../page-state/projections.ts';-import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { remoteProvenanceFloorSql, resolveExcludePrivatePages } from '../search/private-visibility.ts';import { remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';import { materializedPage } from './segmented-apply.ts';import { prepareFileTarget, snapshotLedger, unreadPageFile } from './page-prepare.ts';@@ -49,7 +49,7 @@ export async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId:JOIN facts l ON l.source_id=u.source_id AND l.visibility=u.visibility AND l.entity_slug IS NOT NULL AND l.id<>u.idAND l.expired_at IS NULL AND (l.valid_until IS NULL OR l.valid_until > now())AND gbrain_fact_fingerprint(l.fact)=gbrain_fact_fingerprint(u.fact)- WHERE u.id=$1 AND u.source_id=$2 AND ($3::boolean=false OR l.visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('l')}` : ''}+ WHERE u.id=$1 AND u.source_id=$2 AND ($3::boolean=false OR l.visibility='world')${excludePrivate ? ` AND ${remoteProvenanceFloorSql('l')}` : ''}ORDER BY l.id LIMIT 5`, [id, sourceId, remote]);if (linked.length) {const named = linked.map(row => `#${row.id} (${row.entity_slug})`).join(', ');@@ -64,7 +64,7 @@ export async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId:AND (u.entity_slug IS NULL OR l.entity_slug=u.entity_slug)AND l.expired_at IS NULL AND (l.valid_until IS NULL OR l.valid_until > now())AND gbrain_fact_fingerprint(l.fact)=gbrain_fact_fingerprint(u.fact)- WHERE u.id=$1 AND u.source_id=$2 AND NOT (${privateProvenanceFilterFragment('l')}) LIMIT 1`, [id, sourceId]);+ WHERE u.id=$1 AND u.source_id=$2 AND NOT (${remoteProvenanceFloorSql('l')}) LIMIT 1`, [id, sourceId]);if (!hidden.length) return;throw verbError('invalid_params',`claim_linked: the same claim as fact #${id} is active elsewhere in this brain. Forgetting #${id} would withdraw it there too, so nothing was forgotten.`,@@ -80,7 +80,7 @@ export async function readForgetTarget(engine: BrainEngine, id: number, sourceIdconst [fact] = await engine.executeRaw<ForgetTarget & { source_markdown_slug: string | null; row_num: number | null; expired_at: Date | null }>(`SELECT id,entity_slug,source_markdown_slug,row_num,expired_at,trust_tier FROM factsWHERE id=$1 AND source_id=$2 AND ${ownPage ? `visibility='private' AND source_markdown_slug=$3 AND EXISTS (SELECT 1 FROM pages member_pageWHERE member_page.source_id=facts.source_id AND member_page.slug=$3 AND member_page.deleted_at IS NULL AND member_page.page_readers && ARRAY[$4::text])`- : `($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`}${lock ? ' FOR UPDATE' : ''}`,+ : `($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${remoteProvenanceFloorSql('facts')}` : ''}`}${lock ? ' FOR UPDATE' : ''}`,ownPage ? [id, sourceId, ownPage, `member:${ownPage.slice(MEMBER_PAGE_PREFIX.length)}`] : [id, sourceId, remote]);return fact ?? null;}diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 871d3be88c..a03fdaac54 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -20,7 +20,7 @@ import { lexicalContestCandidate, recordContestedFact, supersessionGuarded } froimport { storedTrustTier } from '../trust/tier.ts';import { fenceAppendPendingTier } from '../eligibility/fence-overlay.ts';import { prepareFenceFactAppend, prepareFenceFactCreate, prepareFenceRowRetirement, requestReceiptFix, type FenceFactAppend } from '../facts/fence-fact-append.ts';-import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';+import { remoteProvenanceFloorSql, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { tightenToPage } from '../facts/visibility.ts';import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';import { noteBelief } from '../belief/ledger.ts';@@ -59,7 +59,7 @@ async function activeUnlinkedCopy(engine: BrainEngine, sourceId: string, input:// GST-359 C2: a member's fact links only its own page's unlinked copy; no other write links one on a member page.const [row] = await engine.executeRaw<{ id: number }>(`SELECT id FROM factsWHERE source_id=$1 AND visibility=$2 AND entity_slug IS NULL AND expired_at IS NULL- AND (valid_until IS NULL OR valid_until > now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)${excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}+ AND (valid_until IS NULL OR valid_until > now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)${excludePrivate && !input.page_slug ? ` AND ${remoteProvenanceFloorSql('facts')}` : ''}AND ${input.page_slug ? 'source_markdown_slug=$4' : `($4::text IS NULL AND NOT ${onOwnedMemoryPageSql('facts')})`}ORDER BY id DESC LIMIT 1`, [sourceId, input.visibility, input.fact, input.page_slug ?? null]);return row ? Number(row.id) : null;diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 1c865d8b5d..c923fbbd78 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -505,14 +505,37 @@ function labelledOnlySql(alias: string, access: LabelledRecord, readers = true):/*** GBRA-108 design 1: the fact conjunct of a labelled-only read. A fact has no readers or rule of its own, so it is hidden,- * except under access.members_read_lineage when its provenance page exists and names the caller (labelledOnlySql). Empty- * for every other caller.+ * except on the caller's own member page while that page names the member (the member's own memory), and under+ * access.members_read_lineage when its provenance page exists and names the caller (labelledOnlySql). Empty for every+ * other caller.*/function labelledOnlyFactSql(factAlias: string): string {const access = currentCallerAccess();if (!access.labelledOnly) return '';- if (!access.lineage || access.owner) return ' AND FALSE';- return ` AND EXISTS (SELECT 1 FROM pages lp WHERE lp.source_id = ${factAlias}.source_id AND lp.slug = ${factAlias}.source_markdown_slug AND ${labelledOnlySql('lp', access)})`;+ const lone = access.audienceIdentities.length ? null : access.identity.find(p => p.startsWith('member:'))?.slice('member:'.length) ?? null;+ const member = access.actor?.member ?? lone;+ const own = member && ACCESS_ID_RE.test(member) ? `EXISTS (SELECT 1 FROM pages lp WHERE lp.source_id = ${factAlias}.source_id AND lp.slug = ${factAlias}.source_markdown_slug+ AND lp.slug = '${MEMBER_PAGE_PREFIX}${member}' AND COALESCE(lp.page_readers && ARRAY['member:${member}']::text[], false))` : 'FALSE';+ if (!access.lineage || access.owner) return ` AND ${own}`;+ return ` AND (${own} OR EXISTS (SELECT 1 FROM pages lp WHERE lp.source_id = ${factAlias}.source_id AND lp.slug = ${factAlias}.source_markdown_slug AND ${labelledOnlySql('lp', access)}))`;+}++/**+ * GBRA-108 design 1: the floor of a remote read gate that is not caller-aware. For any caller that is not labelled-only+ * it is exactly privatePagesFilterFragment; a labelled-only caller also gets its labelled-only conjunct, so a page that+ * does not name it never answers. Write-side, maintenance and derived-visibility decisions keep the plain fragment; test/remote-read-floor.test.ts pins which call sites do.+ */+export function remoteReadFloorSql(pageAlias: string, derived = false): string {+ const plain = privatePagesFilterFragment(pageAlias, derived);+ const access = currentCallerAccess();+ return access.labelledOnly ? `(${plain} AND ${labelledOnlySql(pageAlias, access)})` : plain;+}++/** remoteReadFloorSql for a fact lookup: privateProvenanceFilterFragment, plus the labelled-only fact conjunct for a labelled-only caller. */+export function remoteProvenanceFloorSql(factAlias: string): string {+ const plain = privateProvenanceFilterFragment(factAlias);+ const labelled = labelledOnlyFactSql(factAlias);+ return labelled ? `(${plain}${labelled})` : plain;}const GUEST_ENTRY = 'guest';diff --git a/src/core/sources-not-readable.ts b/src/core/sources-not-readable.tsindex 3ba1d46cac..09ba81a4b9 100644--- a/src/core/sources-not-readable.ts+++ b/src/core/sources-not-readable.ts@@ -21,7 +21,7 @@ import type { OperationContext } from './ops/contract.ts';import { opError } from './ops/contract.ts';import { federatedSearchScope } from './ops/context.ts';import { hostFix } from './ops/op-fix.ts';-import { privatePagesFilterFragment, resolveExcludePrivatePages } from './search/private-visibility.ts';+import { remoteReadFloorSql, resolveExcludePrivatePages } from './search/private-visibility.ts';const UNSCOPED_READ_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'list_pages']);@@ -42,7 +42,7 @@ export async function assertUnscopedReadReachesPages(op: string, params: Record<const readableFacts = op === 'recall' || op === 'query'? ` OR EXISTS (SELECT 1 FROM facts WHERE source_id = ANY($1::text[]) AND visibility = 'world')`: '';- const visible = await resolveExcludePrivatePages(ctx.engine, ctx.remote) ? ` AND ${privatePagesFilterFragment('p')}` : '';+ const visible = await resolveExcludePrivatePages(ctx.engine, ctx.remote) ? ` AND ${remoteReadFloorSql('p')}` : '';const [row] = await ctx.engine.executeRaw<{ refuse: boolean }>(`SELECT CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.source_id = ANY($1::text[]) AND p.deleted_at IS NULL${visible})${readableFacts} THEN falseELSE EXISTS (SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_iddiff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.tsindex 8ba91c584e..74332dddd7 100644--- a/src/core/trust/supersede-handlers.ts+++ b/src/core/trust/supersede-handlers.ts@@ -30,7 +30,7 @@ import { tierRaiseFix } from './confirm.ts';import { queueTierProjection } from './page-write.ts';import { propagateTierLowering } from './propagation.ts';import { compareTrust, effectiveWriteTrust, storedTrustTier, trustRankSql, type TrustTier, type WriteTrust } from './tier.ts';-import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';+import { remoteProvenanceFloorSql } from '../search/private-visibility.ts';/** I3: a write at `writer` may supersede, expire or forget a row at `target` only when it is at least as trusted. */export function supersessionGuarded(writer: TrustTier | null | undefined, target: unknown): boolean {@@ -119,7 +119,7 @@ export async function forgetRequiresOwner(engine: BrainEngine, input: { sourceId/** Pre-admission check for a remote forget: a guarded target becomes a `forget` proposal and the verb error. */export async function guardRemoteForget(engine: BrainEngine, input: { sourceId: string; factId: number; principal: Principal; reason: string | null; excludePrivate?: boolean }): Promise<void> {- const [fact] = await engine.executeRaw<{ trust_tier: string }>(`SELECT trust_tier FROM facts WHERE id = $1 AND source_id = $2 AND visibility = 'world'${input.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`, [input.factId, input.sourceId]);+ const [fact] = await engine.executeRaw<{ trust_tier: string }>(`SELECT trust_tier FROM facts WHERE id = $1 AND source_id = $2 AND visibility = 'world'${input.excludePrivate ? ` AND ${remoteProvenanceFloorSql('facts')}` : ''}`, [input.factId, input.sourceId]);if (!fact || !supersessionGuarded('agent_written', fact.trust_tier)) return;throw await forgetRequiresOwner(engine, { ...input, factTier: storedTrustTier(fact.trust_tier), writerTier: 'agent_written' });}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 4b8fea3137..6825553a61 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -18,7 +18,7 @@ import { withCallerAccess } from '../core/search/private-visibility.ts';import { appliedAccessSummary, folderAccessFor, remoteCallerAccess } from '../core/access/caller.ts';import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';import { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';-import { attestedReadMode, SCOPE_READ_ACCESS, withReadMode, type ReadMode } from '../core/access/scope-read.ts';+import { attestedReadMode, SCOPE_READ_ACCESS, scopeReadLabelledOnlyRefused, withReadMode, type ReadMode } from '../core/access/scope-read.ts';import { attestedReadScope } from '../core/access/member-sources.ts';import { QM_PERSONAL_OPS, qmMemoryToolResult, recallArguments, unlinkedRecallResult } from '../core/ops/qm-memory.ts';import { resolveBrainId } from '../core/brain-resolver.ts';@@ -1028,6 +1028,7 @@ export async function dispatchToolCall(auth: opts.auth, transport: opts.transport, audienceAsserted: audience !== null });// GST-1158 E1: an attested read that names sources reads as the scope (access/scope-read.ts), or as the person on an attest_read person credential.readMode = attested?.actor ? attestedReadMode(name, attested.params, attested.read) : null;+ if (readMode === 'scope' && attested?.access?.labelledOnly) throw scopeReadLabelledOnlyRefused(name);access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(engine, [])).folderCoverage } : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience, opts.transport === 'stdio' && !opts.auth ? opts.stdioMember : undefined, readOnly);// GBRA-284: an attested call reads its grant minus other members' personal sources, a scope read minus every personal source (access/member-sources.ts).if (attested?.actor) scoped = await attestedReadScope(engine, resolved, attested.actor.member, readMode === 'scope');diff --git a/test/access-labelled-only.test.ts b/test/access-labelled-only.test.tsindex 34f520bad4..ccb9bb0612 100644--- a/test/access-labelled-only.test.ts+++ b/test/access-labelled-only.test.ts@@ -1,9 +1,13 @@import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';import type { DoctorContext } from '../src/commands/doctor/context.ts';import { accessLabelledOnlyEntry } from '../src/commands/doctor/checks/access-labelled-only.ts';import { accessCheck, runAccess, whoCanRead } from '../src/commands/access.ts';import { setMembersReadLineage } from '../src/core/access/lineage.ts';-import { setMemberLabelledOnly } from '../src/core/access/labelled-only.ts';+import { labelledOnlyFor, setMemberLabelledOnly } from '../src/core/access/labelled-only.ts';+import { linkMember } from '../src/core/access/actor.ts';+import { enableBeliefLedger } from '../src/core/belief/coverage.ts';+import { assertWebhookWriterMayReplace } from '../src/core/minions/handlers/ingest-capture.ts';import { setOwner } from '../src/core/access/owner.ts';import { bindCredential } from '../src/core/access/members.ts';import { callerIdentityKey } from '../src/core/access/member-facts.ts';@@ -21,7 +25,7 @@ import type { AuthInfo } from '../src/core/ops/contract.ts';import { ENFORCED_MEMBER_ENV, enforcedRead, memberPageView, type EnforcedAccess } from '../src/cli/enforced-member.ts';import { remoteCallerAccess } from '../src/core/access/caller.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { buildLineageBrain, derivedOf, factsOf, HUB, type LineageBrain, type Seen } from './helpers/access-lineage-fixture.ts';+import { buildLineageBrain, derivedOf, ENTITY as ENTITY_SLUG, factsOf, HUB, type LineageBrain, type Seen } from './helpers/access-lineage-fixture.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';@@ -59,6 +63,14 @@ const RELAB = 'notes/relabelled-example';const RELAB_V1 = 'canarylorelabonex';const RELAB_V2 = 'canarylorelabtwox';const OTHERS = ['owner', 'bob', 'alice', 'unbound'] as const;+const BOT_QM = 'U0BOTEXAMPLE';+const OWNER_QM = 'U0OWNEREXAMPLE';+const KAO = 'notes/recorded-open-example';+const KAO_CANARY = 'canarylorecordedx';+const AMENDED = 'notes/amended-lab-example';+const OWN_FACT = 'The group bot keeps its own planning checklist';+const MiB = 1024 ** 2;+const PART_CHARS = 3_900_000;describe('labelled-only grant: the cache keys', () => {test('the semantic cache and the caller identity key separate a labelled-only caller from an ordinary one', () => {@@ -113,6 +125,7 @@ for (const kind of testBackends()) {const SRC = 'lo-src';const before: Record<string, Seen> = {};const writeToken = { token: '', id: '' };+ const attestClient = { token: '' };async function cli(args: string[]): Promise<any> {const lines: string[] = [];const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });@@ -124,16 +137,19 @@ for (const kind of testBackends()) {const doctor = async () => (await accessLabelledOnlyEntry.run({ engine: b.engine } as unknown as DoctorContext) as Array<{ name: string; status: string; message: string }>)[0]!;const authority = (): WriteAuthority => ({ version: 1, principal: { kind: 'legacy_token', id: writeToken.id }, remote: true, excludePrivate: true, sourceId: SRC,sourceIncarnation: 'unused', scopes: ['read', 'write'], operations: null, slugPrefixes: null } as WriteAuthority);- async function put(slug: string, fm: string[]): Promise<{ isError: boolean; json: Record<string, any> }> {- const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(b.engine), transaction: fn => b.engine.transaction(tx => fn(sqlQueryForEngine(tx))) });- const auth = await provider.verifyAccessToken(writeToken.token) as unknown as AuthInfo;- const content = ['---', 'type: note', 'title: Bot page', ...fm, '---', '# Bot page', '', 'Written by the group bot.'].join('\n');- const out = await dispatchToolCall(b.engine, 'put_page', { slug, content }, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'] });+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(b.engine), transaction: fn => b.engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ /** One remote call as the bot's write token, or (`actor`) as the attest client naming that person. */+ async function wcall(op: string, params: Record<string, unknown>, actor?: string): Promise<{ isError: boolean; text: string; json: Record<string, any> }> {+ const auth = await provider().verifyAccessToken(actor ? attestClient.token : writeToken.token) as unknown as AuthInfo;+ const out = await dispatchToolCall(b.engine, op, params, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'], inboundFrameBytes: 4 * MiB,+ ...(actor ? { actor: { header: actor } } : {}) });const text = out.content.map(c => c.text).join('\n');let json: Record<string, any> = {};try { json = JSON.parse(text); } catch { /* prose */ }- return { isError: out.isError === true, json };+ return { isError: out.isError === true, text, json };}+ const note = (title: string, fm: string[]) => ['---', 'type: note', 'title: ' + title, ...fm, '---', '# ' + title, '', 'Written by the group bot.'].join('\n');+ const put = (slug: string, fm: string[]) => wcall('put_page', { slug, content: note('Bot page', fm) });const oldCanary = (key: string) => 'canaryold' + 'lo' + key.replace(/[^a-z]/g, '') + 'x';/** The enforced member CLI's whole read surface (enforced-member-classes READ_OPS), for one origin key: which ops show it. */async function enforcedSeen(key: 'lab' | 'open'): Promise<string[]> {@@ -192,6 +208,11 @@ for (const kind of testBackends()) {const minted = await mintLegacyToken(b.engine, { name: 'bot-writer', scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC] });await bindCredential(b.engine, { kind: 'token', id: minted.id }, { member: BOT });Object.assign(writeToken, { token: minted.token, id: minted.id });+ const client = await provider().registerClientManual('lo-attest-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);+ await bindCredential(b.engine, { kind: 'client', id: client.clientId }, { attestActor: 'qm', attestOps: ['get_page'] });+ attestClient.token = (await provider().exchangeClientCredentials(client.clientId, client.clientSecret ?? '')).access_token;+ await linkMember(b.engine, BOT, 'qm', BOT_QM);+ await linkMember(b.engine, OWNER, 'qm', OWNER_QM);}, 300_000);afterAll(async () => { await b?.close(); }, 60_000);@@ -306,6 +327,131 @@ for (const kind of testBackends()) {}expect(await all()).toEqual(['readable', 'readable', 'missing', 'missing']);}, 600_000);++ test('on: a recorded-time read (get_page and get_versions with known_as_of) of an unlabelled page is page_not_found; an as_of read names no unlabelled amendment', async () => {+ await enableBeliefLedger(b.engine, SRC);+ await importFromContent(b.engine, KAO, ['---', 'type: note', 'title: recorded open', '---', '# recorded open', '', 'Harbor ledger planning notes ' + KAO_CANARY + ' here.'].join('\n'), { sourceId: SRC });+ await importFromContent(b.engine, AMENDED, ['---', 'type: note', 'title: amended lab', 'readable_by: [group:team-a]', "valid_from: '2026-01-01'", '---', '# amended lab', '', 'Anchor page.'].join('\n'), { sourceId: SRC });+ await b.engine.addLink(ORIGINS.open.slug, AMENDED, 'amends', 'amends', 'fixture', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });+ const knownAsOf = new Date().toISOString();+ const asOf = knownAsOf.slice(0, 10);+ const reads = async (who: string) => [+ await b.call(who, 'get_page', { slug: KAO, known_as_of: knownAsOf }),+ await b.call(who, 'get_versions', { slug: KAO, known_as_of: knownAsOf, include_body: true }),+ ];+ for (const text of await reads('bot')) expect(text).toContain(KAO_CANARY);+ expect(await b.call('bot', 'get_page', { slug: AMENDED, as_of: asOf })).toContain(ORIGINS.open.slug);+ await grant(true);+ try {+ for (const text of await reads('bot')) {+ expect(text).not.toContain(KAO_CANARY);+ expect(JSON.parse(text).code).toBe('page_not_found');+ }+ const amended = JSON.parse(await b.call('bot', 'get_page', { slug: AMENDED, as_of: asOf }));+ expect(amended.slug).toBe(AMENDED);+ expect(JSON.stringify(amended)).not.toContain(ORIGINS.open.slug);+ for (const text of await reads('bob')) expect(text).toContain(KAO_CANARY);+ expect(await b.call('bob', 'get_page', { slug: AMENDED, as_of: asOf })).toContain(ORIGINS.open.slug);+ } finally {+ await grant(false);+ }+ }, 600_000);++ test('on: a fact on an unlabelled page is not_found by id, like a fact that does not exist', async () => {+ const [fact] = await b.engine.executeRaw<{ id: number | string }>("SELECT id FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND source = 'fixture'", [SRC, ORIGINS.open.slug]);+ const replace = (id: string) => wcall('remember', { fact: 'A replacement planning claim', entity: ENTITY_SLUG, provenance: 'fixture chat 2026-11-01', replaces: id });+ expect((await replace(String(fact!.id))).json.message).toContain('replaces_visibility_mismatch');+ await grant(true);+ try {+ const hidden = await replace(String(fact!.id));+ const missing = await replace('999999');+ expect({ code: hidden.json.code, message: hidden.json.message.replace(String(fact!.id), 'N') }).toEqual({ code: missing.json.code, message: missing.json.message.replace('999999', 'N') });+ expect(missing.json.code).toBe('not_found');+ } finally {+ await grant(false);+ }+ }, 600_000);++ test('on: recall returns the member\'s own facts with lineage off and on, and still no fact of another page', async () => {+ expect((await wcall('remember', { fact: OWN_FACT, entity: ENTITY_SLUG, provenance: 'fixture chat 2026-11-01' })).isError).toBe(false);+ await grant(true);+ try {+ for (const on of [false, true]) {+ await lineage(on);+ const text = (await wcall('recall', { entity: ENTITY_SLUG })).text;+ expect(text).toContain(OWN_FACT);+ for (const key of on ? ['open', 'other'] : ['lab', 'rule', 'open', 'other']) expect(text).not.toContain(b.canary(key + '.fact'));+ }+ } finally {+ await lineage(false);+ await grant(false);+ }+ }, 600_000);++ test('attested reads: a scope read for a labelled-only person is refused before anything is read; the person read stays labelled-only', async () => {+ const scope = () => wcall('get_page', { slug: ORIGINS.open.slug, source_id: SRC }, BOT_QM);+ expect((await scope()).text).toContain(b.canary('open'));+ await grant(true);+ try {+ const refused = await scope();+ expect({ isError: refused.isError, code: refused.json.code }).toEqual({ isError: true, code: 'permission_denied' });+ expect(refused.json.message).toContain('labelled-only');+ expect(refused.text).not.toContain(b.canary('open'));+ expect((await wcall('get_page', { slug: ORIGINS.open.slug }, BOT_QM)).json.code).toBe('page_not_found');+ expect((await wcall('get_page', { slug: ORIGINS.lab.slug }, BOT_QM)).text).toContain(b.canary('lab'));+ } finally {+ await grant(false);+ }+ }, 600_000);++ test('the owner is never labelled-only, whatever the stored flag says, on the attested door too', async () => {+ await b.engine.executeRaw('UPDATE access_members SET labelled_only = true WHERE id = $1', [OWNER]);+ __resetPrivateVisibilityCacheForTests();+ try {+ expect(await labelledOnlyFor(b.engine, [['member:' + OWNER]])).toBe(false);+ expect((await wcall('get_page', { slug: ORIGINS.open.slug }, OWNER_QM)).text).toContain(b.canary('open'));+ expect(await b.call('owner', 'get_page', { slug: ORIGINS.open.slug })).toContain(b.canary('open'));+ } finally {+ await b.engine.executeRaw('UPDATE access_members SET labelled_only = false WHERE id = $1', [OWNER]);+ __resetPrivateVisibilityCacheForTests();+ }+ }, 600_000);++ test('creates: a webhook capture must name the member, as put_page does', async () => {+ const writer = { principal: { kind: 'legacy_token', id: writeToken.id } };+ await grant(true);+ try {+ await expect(assertWebhookWriterMayReplace(b.engine, writer, SRC, 'notes/capture-new', note('Capture', []))).rejects.toMatchObject({ code: 'access_labelled_only_unnamed' });+ expect(await assertWebhookWriterMayReplace(b.engine, writer, SRC, 'notes/capture-new', note('Capture', ['readable_by: [group:team-a]']))).toBeNull();+ } finally {+ await grant(false);+ }+ expect(await assertWebhookWriterMayReplace(b.engine, writer, SRC, 'notes/capture-new', note('Capture', []))).toBeNull();+ }, 600_000);++ if (store === 'database') test('creates: a streamed upload over the single-string ceiling must name the member; nothing is written', async () => {+ await b.engine.setConfig('write_gate.agent_mode', 'off');+ await grant(true);+ try {+ const slug = 'notes/bot-upload-new';+ const filler = 'We agreed to ship the review checklist first and revisit pricing next week. '.repeat(64) + '\n\n';+ const text = note('Bot upload', []) + '\n\n' + filler.repeat(Math.ceil(25 * MiB / filler.length));+ const sha = (s: string) => createHash('sha256').update(s).digest('hex');+ const begin = await wcall('begin_page_upload', { slug, mode: 'create', total_bytes: Buffer.byteLength(text), sha256: sha(text), request_id: randomUUID() });+ expect(begin.isError).toBe(false);+ for (let part = 0, at = 0; at < text.length; part++, at += PART_CHARS) {+ const piece = text.slice(at, at + PART_CHARS);+ expect((await wcall('upload_page_part', { upload_id: begin.json.upload_id, part, text: piece, part_sha256: sha(piece) })).isError).toBe(false);+ }+ let commit = await wcall('commit_page_upload', { upload_id: begin.json.upload_id, wait_ms: 30_000 });+ for (let attempt = 0; commit.json.code === 'write_pending' && attempt < 40; attempt++) commit = await wcall('commit_page_upload', { upload_id: begin.json.upload_id, wait_ms: 30_000 });+ expect(commit.text).toContain('access_labelled_only_unnamed');+ expect((await b.engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2', [SRC, slug])).length).toBe(0);+ } finally {+ await grant(false);+ await b.engine.executeRaw("DELETE FROM config WHERE key = 'write_gate.agent_mode'");+ }+ }, 600_000);});}}diff --git a/test/remote-read-floor.test.ts b/test/remote-read-floor.test.tsnew file mode 100644index 0000000000..0b072a021e--- /dev/null+++ b/test/remote-read-floor.test.ts@@ -0,0 +1,74 @@+/**+ * GBRA-108 design 1: which call sites read through the remote read floor.+ * 1. Protects: a remote read gate that is not caller-aware uses remoteReadFloorSql / remoteProvenanceFloorSql, which keep+ * a labelled-only caller to pages that name it; only the write-side, maintenance, egress and classification sites+ * listed here keep the plain privatePagesFilterFragment / privateProvenanceFilterFragment, each with its reason.+ * 2. Fails when: a new call of either plain fragment appears outside src/core/search/private-visibility.ts without a+ * row here (use the floor, or add a row with the reason it is not a remote read), a listed site moves to another+ * function, or the floor stops being byte-identical to the plain fragment for a caller that is not labelled-only.+ * 3. Real seams: the source tree as shipped, and the SQL the helpers emit inside caller records.+ */+import { describe, expect, test } from 'bun:test';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { privatePagesFilterFragment, privateProvenanceFilterFragment, remoteProvenanceFloorSql, remoteReadFloorSql, withCallerAccess } from '../src/core/search/private-visibility.ts';++/** file, enclosing top-level declaration, fragment: why it stays plain. */+const PLAIN: Record<string, string> = {+ 'src/commands/sources-add-next.ts noGrantFloorNext privatePagesFilterFragment': 'local CLI hint after sources add; never a remote read',+ 'src/core/ai/decide/egress.ts visiblePages privatePagesFilterFragment': 'egress policy: which pages may leave the machine, judged as world',+ 'src/core/belief/backfill.ts preparePage privatePagesFilterFragment': 'maintenance: stamps the ledger visibility of each page',+ 'src/core/belief/purge.ts registerVersionCarriers privatePagesFilterFragment': 'maintenance: classifies the purged versions',+ 'src/core/belief/state.ts readBeliefState privatePagesFilterFragment': 'the ledger and purge read the stored world visibility, not a caller view',+ 'src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts privatePagesFilterFragment': 'dream cycle: marks a concept private when an input is',+ 'src/core/facts/held-fact-move.ts moveHeldFacts privatePagesFilterFragment': 'write-side: whether the target page is world',+ 'src/core/link-relationships.ts refreshRelationships privatePagesFilterFragment': 'write-side: records whether a link origin is public',+ 'src/core/ops/valid-time-read.ts resolveIdentity privatePagesFilterFragment': 'the world flag of the page; the read itself is gated by privatePagesFilterForCaller',+ 'src/core/persistence/change-reason.ts pageWorldVisible privatePagesFilterFragment': 'write-side: whether a change reason may be published',+ 'src/core/persistence/origin-twins.ts readOriginClaimants privatePagesFilterFragment': 'maintenance: classifies twin pages as private',+ 'src/core/persistence/rows-behind.ts scanRowsBehind privatePagesFilterFragment': 'maintenance: lineage privacy of rows behind the projection',+};++const DECL = /^(?:export )?(?:async )?function\*?\s+(\w+)|^(?:export )?(?:const|let)\s+(\w+)\s*[=:]/;++function plainSites(): string[] {+ const walk = (d: string): string[] => readdirSync(d).flatMap(n => { const p = join(d, n); return statSync(p).isDirectory() ? walk(p) : p.endsWith('.ts') ? [p] : []; });+ const sites: string[] = [];+ for (const file of walk('src')) {+ if (file === join('src', 'core', 'search', 'private-visibility.ts')) continue;+ const lines = readFileSync(file, 'utf8').split('\n');+ lines.forEach((line, i) => {+ for (const m of line.matchAll(/\b(privatePagesFilterFragment|privateProvenanceFilterFragment)\(/g)) {+ let fn = '(module)';+ for (let j = i; j >= 0; j--) { const d = lines[j]!.match(DECL); if (d) { fn = d[1] ?? d[2]!; break; } }+ sites.push(file.split('\\').join('/') + ' ' + fn + ' ' + m[1]);+ }+ });+ }+ return [...new Set(sites)].sort();+}++describe('the remote read floor', () => {+ test('every plain fragment call outside private-visibility.ts is a listed write-side, maintenance or classification site', () => {+ const unlisted = plainSites().filter(site => !(site in PLAIN));+ expect({ unlisted, hint: unlisted.length ? 'A remote read gate uses remoteReadFloorSql (pages) or remoteProvenanceFloorSql (facts); add a row to PLAIN only with the reason it is not a remote read.' : '' })+ .toEqual({ unlisted: [], hint: '' });+ expect(Object.keys(PLAIN).filter(site => !plainSites().includes(site))).toEqual([]);+ });++ test('for any caller that is not labelled-only the floor is exactly the plain fragment; a labelled-only caller gets a narrower one', () => {+ const records = [{}, { identity: ['member:alice-example'], applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] },+ { identity: ['member:alice-example'], lineage: true }, { audienceIdentities: [['member:alice-example'], ['member:bob-example']] }];+ for (const access of records) {+ withCallerAccess(access, () => {+ for (const derived of [false, true]) expect(remoteReadFloorSql('p', derived)).toBe(privatePagesFilterFragment('p', derived));+ expect(remoteProvenanceFloorSql('f')).toBe(privateProvenanceFilterFragment('f'));+ });+ }+ withCallerAccess({ identity: ['member:alice-example'], labelledOnly: true }, () => {+ expect(remoteReadFloorSql('p')).toStartWith('(' + privatePagesFilterFragment('p') + ' AND ');+ expect(remoteProvenanceFloorSql('f')).toStartWith('(' + privateProvenanceFilterFragment('f') + ' AND ');+ expect(remoteProvenanceFloorSql('f')).toContain("lp.slug = 'memory/members/alice-example'");+ });+ });+});