Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Let the operator keep a member to pages labelled for it (labelled-only grant)

garrytand0ae918258a7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8286ca1bed..8c5687c32d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
-**Three opt-in ways to share what is derived from member-restricted pages: raw-only folder rules, audience members the owner reads, and member lineage reads.** A folder rule kept the summaries, atoms, chronicle events and facts made from its pages as tightly as the pages themselves, so a transcript folder kept to one member hid every summary of those calls from everyone else; a group chat's own memory page was closed to the brain owner; and only the owner could read the derived pages and facts of pages it already reads. Each now has an operator setting, off by default, and nothing changes on upgrade: `gbrain access rule add --raw-only` keeps a folder's pages to its readers but lets whoever reads a derived page read it (use it for transcripts, never for a folder whose content is itself the secret); `gbrain access member kind <id> audience` lets the owner read that member's own member page, versions, derived pages and facts; and `gbrain access members-read-lineage on` lets every member read the derived pages and facts of pages it reads, as the owner does. All three work the same on a repo-less brain and with rules in `access.yml`, only the operator on the brain host sets them, and no write widens.
+**Three opt-in ways to share what is derived from member-restricted pages: raw-only folder rules, audience members the owner reads, and member lineage reads.** A folder rule kept the summaries, atoms, chronicle events and facts made from its pages as tightly as the pages themselves, so a transcript folder kept to one member hid every summary of those calls from everyone else; a group chat's own memory page was closed to the brain owner; and only the owner could read the derived pages and facts of pages it already reads. Each now has an operator setting, off by default, and nothing changes on upgrade: `gbrain access rule add --raw-only` keeps a folder's pages to its readers but lets whoever reads a derived page read it (use it for transcripts, never for a folder whose content is itself the secret); `gbrain access member kind <id> audience` lets the owner read that member's own member page, versions, derived pages and facts; and `gbrain access members-read-lineage on` lets every member read the derived pages and facts of pages it reads, as the owner does. All three work the same on a repo-less brain and with rules in `access.yml`, only the operator on the brain host sets them, and no write widens. A fourth setting goes the other way: `gbrain access member labelled-only <id> on` keeps a group or audience credential to pages that name it, hiding unlabelled pages and anything derived from them.
### Itemized changes
@@ -28,6 +28,17 @@ identifiers and attribution are available in the pre-removal Git revision
- Docs: `docs/guides/access-designations.md` (raw-only rules, audience members, members read lineage), key-files entry.
- Tests: `test/access-raw-only-rules.test.ts`, `test/access-audience-members.test.ts`, `test/access-members-read-lineage.test.ts` (every read path for every caller, off and on, the held widening, remote refusals, cache keys and the write gate; PGLite and Postgres, rules in the database and in `access.yml`); shared fixture `test/helpers/access-lineage-fixture.ts`; migration, catalog and doctor goldens.
+#### Labelled-only members (GBRA-108 design 1)
+
+- Migration v306 (`src/core/schema-migrations/v306-access-labelled-only.ts`, provisional number): `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.
+- 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.
+
## [0.60.684.0] - 2026-11-12
**An agent that runs gbrain for one member can now be held to that member's view of the brain.** Set `GBRAIN_ENFORCED_MEMBER=<member>` in the launcher that starts the agent's gbrain calls, and every command it runs reads exactly what a remote credential bound to that member would read: pages kept to other members, private pages, folders the member is outside of and other members' personal sources leave no slug, title, body, fact or count behind. Writes still land where they land today, as trusted local writes, but the mode refuses a write to a page the member cannot read and every change to a page's readers or visibility. `remember` saves a fact only with `--entity` naming a page the member reads, and its refusal says so with the exact retry command. `gbrain write-request <id>` reads the member's own receipts, and any other id answers exactly like an unknown one. sync, `sources refresh` and `git commit-push` keep working with their output replaced by one line (sync and refresh take only `--source <id>`, `--no-pull`, `--no-embed`, `--json` and `--dry-run`, on a source the member reads), `doctor` prints only check names, statuses and counts, and `hook` succeeds silently so group turns never fail. Every other command is refused with one exact line, exit 3 and the code `enforced_member_refused`, `--help` included, and so is everything when the value is empty, names an unknown member or names the owner. Unset, nothing changes. The mode binds only a caller whose launcher pins the variable; a process that can unset it, or read the brain's files or database directly, is outside it. Guide: [docs/guides/enforced-member.md](docs/guides/enforced-member.md).
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.md
index a5cc107a1b..75fd8ccdce 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`). A derivative of a page that names readers is otherwise hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v299; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) on the stored actor, else the stored audience, and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).
+- `src/core/access/` (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 (migration v306): `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`, `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. 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.md
index 18fd04e9dd..035ee7d975 100644
--- a/docs/guides/access-designations.md
+++ b/docs/guides/access-designations.md
@@ -211,6 +211,28 @@ operator on the brain host sets it; a remote caller is refused. While it is on,
(`members_read_lineage`), `gbrain access check` reports it, `who-can-read` names it on pages it opens, and doctor
reports `access_members_read_lineage`. `gbrain access members-read-lineage off` is the undo.
+### Labelled-only members (`gbrain access member labelled-only`)
+
+Some credentials should see only what someone deliberately labelled for them: a group chat bot, a shared assistant, an
+audience of several people. `gbrain access member labelled-only <id> on` marks a member that way (off by default and
+unchanged on upgrade; `off` is the undo). Every token, OAuth client and stdio binding of that member then reads only
+pages that name it: its id or one of its groups in `readable_by`, or a folder or page rule that lists them. A page with
+no label, which its source grant would otherwise open, is hidden on every read path, `--as <member>` and the enforced
+member CLI included. So is every derived page and fact that names nobody (summaries, atoms, chronicle events,
+`derived_from` pages): they fail closed. With `access.members_read_lineage` on, a derived page or fact passes only when it
+has at least one origin and every origin names the member; one unlabelled origin keeps it hidden. An older version
+counts 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.
+
+The grant lives on the member, not on one credential, so a second key for the same member cannot forget it. Writes
+follow 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_owner`) and asks the user. Only the brain operator on the brain host sets it; a remote caller is
+refused (`permission_denied`). `gbrain access member list` and `gbrain access check` show it, `who-can-read` notes
+which labelled-only members a page leaves out, and doctor's `access_labelled_only_members` lists them. An older gbrain
+binary sharing the same database ignores the grant, so upgrade every binary that serves the brain before turning it on.
+
## Related
- [Multi-source brains](multi-source-brains.md): sources and grants.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6118b5a284..1a3595e4ba 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -72,6 +72,22 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### access_labelled_only_owner
+
+<a id="access_labelled_only_owner"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A labelled-only grant was asked for on the brain owner (gbrain access member labelled-only <owner> on), or a labelled-only member was named the owner (gbrain access owner set), so nothing was changed. | The owner reads the whole brain. A labelled-only grant hides every page that does not name its member, so on the owner it would silently hide the owner's own brain from every credential bound to it. | Ask the user which member the group or audience credential should read as; give it its own member and mark that one labelled-only, or clear the grant before naming the owner. | user | `repeat the read that failed` | 3 | no |
+
+### access_labelled_only_unnamed
+
+<a id="access_labelled_only_unnamed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A credential whose member is labelled-only tried to create a page that would not name it: the page has no readable_by holding the member or one of its groups, and no folder or page rule over its slug lists them, so nothing was written. | A labelled-only member reads only pages labelled for it, so a page it creates must name it; otherwise it would write a page it could never read back, readable by every other caller its source admits. | Add readable_by naming the member or one of its groups to the frontmatter (readable_by: [alice-example, group:team-a]), or ask the brain operator to add a folder rule over the path that lists it, then submit again with a new request_id. | agent | `repeat the read that failed` | 1 | no |
+
### access_member_disabled
<a id="access_member_disabled"></a>
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 5e7c7adb11..bd38107a98 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -43,7 +43,7 @@ src/core/persistence/worktree-refresh.ts 1554 ratchet new row: crossed the 1500
src/core/bootstrap/harness.ts 2630 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)
src/core/oauth-provider.ts 1237 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mint
src/core/ops/pages.ts 744 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (739 measured); +4 GBRA-449: an empty list_pages names the page types present when no visible page has the requested type (logic in ops/list-pages-pagination.ts unusedTypeNotice); +1 GST-2462: a static import of the put_page ignored-label notice (a dynamic one yielded on the first put_page, so a queued embedding ran inside it; mode-receipt.serial.test.ts)
-src/core/search/mode.ts 1732 ratchet +12 #7175 (train R): search.keyword_phrase bundle field, config parse and knobsHash part; +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156 #7593: private-pages grant part in the cache key; +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities) (re-summed at the train M .538 merge: 1717 measured); +1 GBRA-283 B2: import of the embedded engine reranker model (engine-gateway.ts); re-summed at the train R merge with v0.60.574.0: 1721 + 9; +1 GST-2490: append-only xol= knobsHash part (owner lineage and the owner opt-in); +1 GBRA-108: append-only xak= knobsHash part (the owner's audience members; member lineage reuses the xol= line as xol=3)
+src/core/search/mode.ts 1733 ratchet +12 #7175 (train R): search.keyword_phrase bundle field, config parse and knobsHash part; +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156 #7593: private-pages grant part in the cache key; +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities) (re-summed at the train M .538 merge: 1717 measured); +1 GBRA-283 B2: import of the embedded engine reranker model (engine-gateway.ts); re-summed at the train R merge with v0.60.574.0: 1721 + 9; +1 GST-2490: append-only xol= knobsHash part (owner lineage and the owner opt-in); +1 GBRA-108: append-only xak= knobsHash part (the owner's audience members; member lineage reuses the xol= line as xol=3); +1 GBRA-108 design 1: append-only xlo= knobsHash part (the labelled-only grant)
src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)
src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
diff --git a/scripts/stress/iteration-weights.json b/scripts/stress/iteration-weights.json
index c3300c157e..6a6a553706 100644
--- a/scripts/stress/iteration-weights.json
+++ b/scripts/stress/iteration-weights.json
@@ -1,5 +1,6 @@
{
"test/access-audience-members.test.ts": 60000,
+ "test/access-labelled-only.test.ts": 60000,
"test/access-members-read-lineage.test.ts": 60000,
"test/access-page-rule-fileless.test.ts": 59000,
"test/access-raw-only-rules.test.ts": 60000,
diff --git a/src/cli/as-preview.ts b/src/cli/as-preview.ts
index 68b0fc4d39..15141e5bf4 100644
--- a/src/cli/as-preview.ts
+++ b/src/cli/as-preview.ts
@@ -3,7 +3,7 @@
* The handler runs under that member's identity with the remote read policy
* (readers and privacy; GST-2059: the brain owner reads with privacy relaxed, and GST-2490: with access.owner_reads_restricted
* on, past readers lists and rules too; GBRA-108: a read previews the lineage the member's own credential gets, owner
- * or access.members_read_lineage, and the owner's audience members), while ctx.remote stays false, so upload confinement
+ * or access.members_read_lineage, and the owner's audience members; GBRA-108 design 1: a labelled-only member's grant), while ctx.remote stays false, so upload confinement
* and write trust are unchanged. An unknown or ill-formed member is refused
* before any work.
*/
@@ -39,6 +39,7 @@ export async function openAsPreview(engine: BrainEngine, member: string | undefi
let ownerReadsRestricted: boolean;
let lineage: boolean;
let audienceKindMembers: string[];
+ let labelledOnly: boolean;
try {
const membersModule = await import('../core/access/members.ts');
const resolved = await membersModule.memberIdentity(engine, member);
@@ -48,13 +49,14 @@ export async function openAsPreview(engine: BrainEngine, member: string | undefi
ownerReadsRestricted = owner && await ownerModule.ownerReadsRestrictedOn(engine);
lineage = readOnly && (owner || await (await import('../core/access/lineage.ts')).membersReadLineageOn(engine));
audienceKindMembers = owner && lineage ? await membersModule.audienceMemberIds(engine) : [];
+ labelledOnly = !owner && await (await import('../core/access/labelled-only.ts')).labelledOnlyFor(engine, [identity]);
} catch (e: unknown) {
await finishCliTeardown({ engine });
exitCliError(e, command);
}
const { withCallerAccess } = await import('../core/search/private-visibility.ts');
const folder = await (await import('../core/access/caller.ts')).folderAccessFor(engine, identity);
- const access = { identity, ...folder, applyRemoteReadPolicy: true, hidePrivate: !owner, owner, lineage, ownerReadsRestricted: ownerReadsRestricted && lineage, audienceKindMembers, privateReadableSources: [] };
+ const access = { identity, ...folder, applyRemoteReadPolicy: true, hidePrivate: !owner, owner, lineage, ownerReadsRestricted: ownerReadsRestricted && lineage, audienceKindMembers, labelledOnly, privateReadableSources: [] };
return {
run: fn => withCallerAccess(access, fn),
context: ctx => ({ ...ctx, accessIdentity: identity, applyRemoteReadPolicy: true }),
diff --git a/src/cli/enforced-member.ts b/src/cli/enforced-member.ts
index 6af5bb7ff6..0fe0650fa6 100644
--- a/src/cli/enforced-member.ts
+++ b/src/cli/enforced-member.ts
@@ -321,17 +321,23 @@ function withoutCoverageCounts(value: unknown, depth = 0): unknown {
type PageView = 'readable' | 'hidden' | 'missing';
-/** Whether the member reads a page: an existing row under the member's full read policy, a new slug under the folder rules it would sit under. */
+/**
+ * Whether the member reads a page: an existing row under the member's full read policy, a new slug under the folder rules it
+ * would sit under. GBRA-108 design 1: a labelled-only member reads an existing row only when it names the member, and a
+ * new slug only under a rule that lists it (the mode refuses label changes, so a rule is the only way a create names it).
+ */
export async function memberPageView(engine: BrainEngine, ea: EnforcedAccess, sourceId: string, slug: string): Promise<PageView> {
if (ea.hiddenSources.has(sourceId)) return 'hidden';
- const { withCallerAccess, readPolicyFragment, folderRulesAllowedSql } = await import('../core/search/private-visibility.ts');
+ const { withCallerAccess, readPolicyFragment, folderRulesAllowedSql, labelledOnlyForSql } = await import('../core/search/private-visibility.ts');
const { access } = ea;
+ const labelled = access.labelledOnly ? ' AND ' + labelledOnlyForSql('p', [access.identity], access.satisfiedRuleIds) : '';
let view: PageView = 'missing';
for (const candidate of [...new Set([slug, slug.toLowerCase()])]) {
- const policy = withCallerAccess(access, () => readPolicyFragment('p', access.identity, true, access.satisfiedRuleIds));
+ const policy = withCallerAccess(access, () => readPolicyFragment('p', access.identity, true, access.satisfiedRuleIds)) + labelled;
const [row] = await engine.executeRaw<{ ok: boolean }>('SELECT (' + policy + ') AS ok FROM pages p WHERE p.source_id = $1 AND p.slug = $2 LIMIT 1', [sourceId, candidate]);
if (row) { if (!row.ok) return 'hidden'; view = 'readable'; continue; }
- const folder = withCallerAccess(access, () => folderRulesAllowedSql('p', access.satisfiedRuleIds));
+ const folder = withCallerAccess(access, () => folderRulesAllowedSql('p', access.satisfiedRuleIds))
+ + (access.labelledOnly ? ' AND ' + labelledOnlyForSql('p', [access.identity], access.satisfiedRuleIds, false) : '');
const [rule] = await engine.executeRaw<{ ok: boolean }>('SELECT (' + folder + ') AS ok FROM (SELECT $1::text AS source_id, $2::text AS slug, gbrain_access_folder_rules($1, $2) AS folder_rule_ids) p', [sourceId, candidate]);
if (!rule?.ok) return 'hidden';
}
diff --git a/src/commands/access.ts b/src/commands/access.ts
index 036c4911bb..f6c57f28f5 100644
--- a/src/commands/access.ts
+++ b/src/commands/access.ts
@@ -24,6 +24,7 @@ import { readClientGrant } from '../core/grants/service.ts';
import { resolveTokenGrant } from '../core/grants/legacy-token.ts';
import { accessAllowedSql, folderRulesAllowedSql, isPrivacyPrivatePage, withCallerAccess } from '../core/search/private-visibility.ts';
import { membersReadLineageOn, setMembersReadLineage } from '../core/access/lineage.ts';
+import { setMemberLabelledOnly } from '../core/access/labelled-only.ts';
import { folderAccessFor } from '../core/access/caller.ts';
import { identityFor, MEMBER_PAGE_PREFIX, normalizePrincipal, normalizeReaders } from '../core/access/principals.ts';
import { mayActForCovers, singleMemberAudience, type AudiencePrincipal } from '../core/access/audience.ts';
@@ -31,7 +32,7 @@ import { linkMember, linkMemberByEmail, listMemberLinks, unlinkMember } from '..
import { bindMemberSource, listMemberSources, unbindMemberSource } from '../core/access/member-sources.ts';
import { clearOwner, ownerMemberId, ownerReadsRestrictedOn, ownerView, setOwner, setOwnerReadsRestricted, type OwnerView } from '../core/access/owner.ts';
import {
- addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,
+ addGroup, addMember, assertAccessId, disableMember, enableMember, existingMember, getMember, legacyTokenByName, listGroups, listMembers,
parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, setMemberEmail, setMemberKind, type MemberRecord,
} from '../core/access/members.ts';
@@ -42,6 +43,9 @@ Members and groups:
gbrain access member kind <id> person|audience
audience: a group chat or shared assistant; the owner reads its own
member page, older versions, derived pages and facts (person: default)
+ gbrain access member labelled-only <id> [on|off]
+ On: every credential bound to the member reads only pages that name it
+ (readable_by or a rule listing it or its groups); never the owner
gbrain access member set <id> --email <addr>|none
Declare or clear the email an operator finds the member by
(case-folded, unique per brain)
@@ -135,7 +139,7 @@ function positionals(args: string[]): string[] {
}
function memberLine(m: MemberRecord): string {
- return ` ${m.id}${m.display_name ? ` (${m.display_name})` : ''} ${m.status} ${m.kind}${m.email ? ` email: ${m.email}` : ''}${m.groups.length ? ` groups: ${m.groups.join(', ')}` : ''}`;
+ return ` ${m.id}${m.display_name ? ` (${m.display_name})` : ''} ${m.status} ${m.kind}${m.labelled_only ? ' labelled-only' : ''}${m.email ? ` email: ${m.email}` : ''}${m.groups.length ? ` groups: ${m.groups.join(', ')}` : ''}`;
}
export interface WhoCanReadEntry {
@@ -164,6 +168,7 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: s
const identity = identityFor(m.id, m.groups);
return { id: m.id, identity, folder: await folderAccessFor(engine, identity) };
}));
+ const labelledOnlyIds = enabled.filter(m => m.labelled_only && m.id !== ownerId).map(m => m.id);
const entries: WhoCanReadEntry[] = [];
for (const row of rows) {
const fm = typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter;
@@ -202,6 +207,7 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: s
: 'Derived pages (atoms, facts, chronicle events) of a page that names readers are hidden from every remote caller.',
...(ownerOpened ? [`The owner (${optIn}) reads it too, and its derived pages and facts: access.owner_reads_restricted is on (gbrain access owner reads-restricted off turns it off).`] : []),
...(audienceOpened || (audiencePage && ownerOpened) ? [`It is the member page of an audience member (gbrain access member kind), so the owner (${ownerId}) reads it, its older versions, its derived pages and its facts as if it named the owner.`] : []),
+ ...(labelledOnlyIds.length ? [`Labelled-only members (${labelledOnlyIds.join(', ')}) read it only when it names them: readable_by or a rule listing them or their groups${readers === null && !ruled ? ', so none of them reads it' : ''}; a derived page or fact that names nobody is hidden from them${memberLineage ? ' unless every origin names them' : ''}.`] : []),
];
entries.push({ slug: row.slug, source_id: row.source_id, readers, private: priv, members: readers === null && !ruled ? 'every_source_reader' : allowed, note: notes.join(' ') });
}
@@ -221,6 +227,8 @@ export interface AccessCheckResult {
owner_reads_restricted: boolean;
/** GBRA-108 design 3: access.members_read_lineage is on, so a member's reads pass derived pages and facts whose origins it reads. */
members_read_lineage: boolean;
+ /** GBRA-108 design 1: the credential's member is labelled-only, so it reads only pages that name it. */
+ labelled_only: boolean;
explanation: string;
audience?: Array<{ principal: string; covered_by_may_act_for: boolean }>;
}
@@ -254,6 +262,7 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;
const owner = live && member!.id === ownerId;
const ownerReadsRestricted = !!ownerId && await ownerReadsRestrictedOn(engine);
const memberLineage = await membersReadLineageOn(engine);
+ const labelledOnly = live && !owner && rec?.labelled_only === true;
const explanation = verdict === 'unbound' ? 'Bound to no member: reads every page its grant allows except pages that name readers (readable_by).'
: verdict === 'refused' ? `Bound to member "${member!.id}", which is ${member!.status}: the credential is refused at verification (access_member_disabled).`
: `Reads as member "${member!.id}"${member!.groups.length ? ` (groups: ${member!.groups.join(', ')})` : ''}: pages naming readers are visible when they list the member or one of its groups, within the grant below.`
@@ -263,12 +272,13 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;
: ` access.owner_reads_restricted is on: the brain owner (${ownerId}) also reads the pages this credential's readers lists and rules keep to it, except its own member page.`) : '')
+ (owner ? ' In reads it also reads derived pages and facts whose origins it reads.'
: memberLineage ? ' access.members_read_lineage is on: in reads, speaking for itself, it also reads derived pages and facts whose origins it reads.' : '')
- + (rec?.kind === 'audience' ? ` It is an audience member (a group chat or shared assistant)${ownerId && !owner ? `: the brain owner (${ownerId}) reads its own member page, older versions, derived pages and facts as if they named the owner` : ''}.` : '');
+ + (rec?.kind === 'audience' ? ` It is an audience member (a group chat or shared assistant)${ownerId && !owner ? `: the brain owner (${ownerId}) reads its own member page, older versions, derived pages and facts as if they named the owner` : ''}.` : '')
+ + (labelledOnly ? ` It is labelled-only (gbrain access member labelled-only ${member!.id} off clears it): it reads only pages whose readable_by names the member or one of its groups, or that a rule listing them covers; every unlabelled page its grant would open, and every derived page and fact that names nobody${memberLineage ? ' (unless every origin names it)' : ''}, is hidden.` : '');
const result: AccessCheckResult = {
credential,
grant: { scopes: grant.scopes, sources: grant.sources, takes_holders: grant.takesHolders, private_pages: grant.privatePages,
operations: grant.allowedOperations ?? 'unrestricted', revision: grant.revision },
- member, identity, may_act_for: mayActFor, verdict, owner, owner_reads_restricted: ownerReadsRestricted, members_read_lineage: memberLineage, explanation,
+ member, identity, may_act_for: mayActFor, verdict, owner, owner_reads_restricted: ownerReadsRestricted, members_read_lineage: memberLineage, labelled_only: labelledOnly, explanation,
};
if (target.as !== undefined) {
const audience: NonNullable<AccessCheckResult['audience']> = [];
@@ -314,6 +324,14 @@ async function memberCmd(engine: BrainEngine, sub: string | undefined, args: str
r.member.kind === 'audience' ? 'The brain owner reads its own member page, older versions, derived pages and facts as if they named the owner. gbrain access member kind ' + r.member.id + ' person undoes this.'
: 'A person: the owner reads its member page only when listed.']);
}
+ case 'labelled-only': {
+ const value = positionals(args)[1];
+ if (!id || (value !== undefined && value !== 'on' && value !== 'off')) throw usageError('access member labelled-only needs a member id and on or off.', 'gbrain access member labelled-only <id> [on|off]');
+ const r = value === undefined ? { member: await existingMember(engine, id, 'read'), changed: false } : await setMemberLabelledOnly(engine, id, value === 'on', { remote: false });
+ return print(json, r, () => [`${value === undefined ? 'Member' : r.changed ? 'Member updated' : 'Unchanged'}: ${r.member.id}`, memberLine(r.member),
+ r.member.labelled_only ? `Labelled-only: every credential bound to it reads only pages that name it (readable_by or a rule listing it or its groups). gbrain access member labelled-only ${r.member.id} off clears it.`
+ : 'Not labelled-only: its credentials read every page their grant and readers allow.']);
+ }
case 'disable':
case 'enable': {
const m = await (sub === 'disable' ? disableMember : enableMember)(engine, id);
@@ -347,7 +365,7 @@ async function memberCmd(engine: BrainEngine, sub: string | undefined, args: str
case 'source':
return memberSourceCmd(engine, args, json);
default:
- throw usageError(`Unknown access member subcommand: ${sub ?? '(none)'}.`, 'Use add, set, kind, disable, enable, rm, list, link, unlink, links or source (gbrain access --help).');
+ throw usageError(`Unknown access member subcommand: ${sub ?? '(none)'}.`, 'Use add, set, kind, labelled-only, disable, enable, rm, list, link, unlink, links or source (gbrain access --help).');
}
}
@@ -513,7 +531,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<vo
` Sources: ${JSON.stringify(r.grant.sources)}`,
` Operations: ${r.grant.operations === 'unrestricted' ? 'every operation the scopes allow' : r.grant.operations.length}`,
` Private pages: ${r.grant.private_pages}`,
- ` Member: ${r.member ? `${r.member.id} (${r.member.status})` : 'none'}${r.member?.groups.length ? ` groups: ${r.member.groups.join(', ')}` : ''}`,
+ ` Member: ${r.member ? `${r.member.id} (${r.member.status})` : 'none'}${r.member?.groups.length ? ` groups: ${r.member.groups.join(', ')}` : ''}${r.labelled_only ? ' labelled-only' : ''}`,
` May act for: ${r.may_act_for?.join(', ') ?? 'none'}`,
...(r.audience ? [` Audience: ${r.audience.map(a => `${a.principal}${a.covered_by_may_act_for ? '' : ' (not in may_act_for)'}`).join(', ')}`] : []),
` ${r.explanation}`]);
diff --git a/src/commands/doctor/checks/access-labelled-only.ts b/src/commands/doctor/checks/access-labelled-only.ts
new file mode 100644
index 0000000000..296edcda11
--- /dev/null
+++ b/src/commands/doctor/checks/access-labelled-only.ts
@@ -0,0 +1,51 @@
+/**
+ * GBRA-108 design 1 doctor check (an operator setting, off by default).
+ *
+ * - access_labelled_only_members: every enabled member that carries the labelled-only grant (access_members.labelled_only).
+ * Every credential bound to such a member reads only pages that name it (readable_by or a rule listing it or its
+ * groups), so it is listed with its bound credentials so a group or audience credential kept to labelled pages is easy
+ * to audit. A warn when the brain owner carries it (only a hand edit gets there; the owner reads past it anyway, and
+ * the grant should be cleared).
+ *
+ * With no labelled-only member, the check is not applicable.
+ */
+import type { Check } from '../../doctor.ts';
+import { agentFix, checkError, infoCheck } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { labelledOnlyMemberIds } from '../../../core/access/labelled-only.ts';
+import { ownerMemberId } from '../../../core/access/owner.ts';
+import { boundCredentials } from '../../../core/access/members.ts';
+
+const name = 'access_labelled_only_members';
+
+async function verdict(ctx: DoctorContext): Promise<Check> {
+ const engine = connectedEngine(ctx);
+ try {
+ const ids = await labelledOnlyMemberIds(engine);
+ if (!ids.length) return infoCheck(name, 'Not applicable: no member is labelled-only (gbrain access member labelled-only <id> on).', 'not_applicable');
+ const owner = await ownerMemberId(engine);
+ const members = await Promise.all(ids.map(async id => ({ id, credentials: (await boundCredentials(engine, id)).length })));
+ if (owner && ids.includes(owner)) {
+ return { name, status: 'warn', details: { members, owner },
+ message: `The brain owner (${owner}) is marked labelled-only. The owner reads the whole brain, so the grant does not apply to it; clear it with gbrain access member labelled-only ${owner} off.`,
+ fix: agentFix(['gbrain', 'access', 'member', 'labelled-only', owner, 'off'], 'Clears the grant on the owner; no read changes, because the owner never reads under it.', name, { ask_user: true }) };
+ }
+ return infoCheck(name, `${ids.length} labelled-only member(s): every credential bound to each reads only pages that name it (readable_by or a rule listing it or its groups), never an unlabelled page its grant would otherwise open: ${members.map(m => `${m.id} (${m.credentials} credential(s))`).join(', ')}. Clear one with gbrain access member labelled-only <id> off.`,
+ 'ok', undefined, { members });
+ } catch (error) {
+ return checkError(name, `run ${name}`, error);
+ }
+}
+
+async function runAccessLabelledOnly(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const { name: _name, ...check } = await verdict(ctx);
+ checks.push({ name: 'access_labelled_only_members', ...check });
+ return checks;
+}
+
+export const accessLabelledOnlyEntry: DoctorEntry = {
+ name: 'access_labelled_only_members',
+ emits: ['access_labelled_only_members'],
+ run: runAccessLabelledOnly,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 7164278b1d..bfeebf016b 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -145,6 +145,7 @@ import { unlabeledPeopleFoldersEntry } from './checks/unlabeled-people-folders.t
import { sharedAgentAccessEntry } from './checks/shared-agent-access.ts';
import { ownerReadsRestrictedEntry } from './checks/owner-reads-restricted.ts';
import { accessLineageEntry } from './checks/access-lineage.ts';
+import { accessLabelledOnlyEntry } from './checks/access-labelled-only.ts';
import { attestReadAccessEntry } from './checks/attest-read-access.ts';
import { originTwinsEntry } from './checks/origin-twins.ts';
import { slugPathMismatchEntry } from './checks/slug-path-mismatch.ts';
@@ -233,6 +234,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
sharedAgentAccessEntry,
ownerReadsRestrictedEntry,
accessLineageEntry,
+ accessLabelledOnlyEntry,
attestReadAccessEntry,
rlsEntry,
postgresTlsEntry,
diff --git a/src/core/access/actor.ts b/src/core/access/actor.ts
index 8c043a8dc7..e00a261270 100644
--- a/src/core/access/actor.ts
+++ b/src/core/access/actor.ts
@@ -21,6 +21,7 @@ import { identityFor } from './principals.ts';
import { isMissingSchemaObject } from '../utils.ts';
import { memberByEmail, memberIdentity } from './members.ts';
import { folderAccessFor, memberIdentityFor } from './caller.ts';
+import { labelledOnlyFor } from './labelled-only.ts';
import { markedScopeSources, sourceNotAttested } from './attest-sources.ts';
import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, attestRightFrom, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER, type AttestedActor, type AttestRight } from './actor-model.ts';
@@ -222,6 +223,7 @@ export async function attestedCallerAccess(engine: Pick<BrainEngine, 'executeRaw
...await folderAccessFor(engine, identity),
privateReadableSources: [],
hidePrivate: true,
+ labelledOnly: await labelledOnlyFor(engine, [identity]),
applyRemoteReadPolicy: false,
restricted: true,
remotePolicy: { privacyRelaxed: false, restricted: true },
diff --git a/src/core/access/caller.ts b/src/core/access/caller.ts
index 2034fde5ab..e841559810 100644
--- a/src/core/access/caller.ts
+++ b/src/core/access/caller.ts
@@ -23,6 +23,7 @@ import { currentCallerAccess } from '../search/private-visibility.ts';
import { edgeTrimSql } from '../edge-whitespace.ts';
import { GUEST, STDIO_MAY_ACT_FOR_KEY, mayActForCovers, singleMemberAudience, type AudiencePrincipal } from './audience.ts';
import { audienceMemberIds, parseMayActFor } from './members.ts';
+import { labelledOnlyFor } from './labelled-only.ts';
/** Config key binding a local stdio MCP server to one member. */
export const STDIO_MEMBER_KEY = 'mcp.stdio_member';
@@ -211,6 +212,8 @@ export async function resolveAudienceIdentities(engine: Pick<BrainEngine, 'execu
* GBRA-108: under access.members_read_lineage a read by any other member speaking for itself (no audience, or an
* audience of that one member) gets the same lineage (design 3), and an owner read carries the audience members
* (design 2). Never an audience of several, a group or a guest, and never an unbound credential (no member identity).
+ * GBRA-108 design 1: a read or write whose bound member, or any member of its audience, is labelled-only reads only
+ * pages that name it (labelledOnly); never the owner.
*/
export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string, audience?: readonly AudiencePrincipal[] | null, stdioMember?: string, readOnly = false): Promise<Partial<CallerAccess>> {
const [relaxed, remotePolicy] = await Promise.all([remotePrivacyRelaxed(engine), requestRemotePolicy(engine)]);
@@ -232,6 +235,7 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | u
lineage,
ownerReadsRestricted: owner && lineage && remotePolicy.ownerReadsRestricted === true,
audienceKindMembers: owner && lineage ? await audienceMemberIds(engine) : [],
+ labelledOnly: !owner && restricted && await labelledOnlyFor(engine, [...identities, await boundIdentity(engine, auth, transport, stdioMember)]),
applyRemoteReadPolicy: false,
restricted,
remotePolicy,
@@ -251,6 +255,7 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | u
lineage,
ownerReadsRestricted: owner && lineage && remotePolicy.ownerReadsRestricted === true,
audienceKindMembers: owner && lineage ? await audienceMemberIds(engine) : [],
+ labelledOnly: !owner && restricted && await labelledOnlyFor(engine, [identity]),
applyRemoteReadPolicy: false,
restricted,
remotePolicy,
diff --git a/src/core/access/labelled-only.ts b/src/core/access/labelled-only.ts
new file mode 100644
index 0000000000..e055db7d9e
--- /dev/null
+++ b/src/core/access/labelled-only.ts
@@ -0,0 +1,73 @@
+/**
+ * GBRA-108 design 1: the labelled-only grant. A member that carries access_members.labelled_only (v306; false by default
+ * and unchanged on upgrade) reads only pages that name it: its member id or one of its groups in readable_by, or a folder
+ * or page rule that lists it. Unlabelled pages its source grant would otherwise open are hidden, and so is every derived
+ * page and fact with no readers or rule of its own, except under access.members_read_lineage where every origin names it
+ * (CallerAccess.labelledOnly, search/private-visibility.ts). For group and audience credentials that should see only what
+ * was deliberately labelled for them.
+ *
+ * The flag lives on the member, so every token, OAuth client and stdio binding of that member inherits it, and a second
+ * credential cannot forget it. It never applies to the owner: setting it on the owner, or naming a labelled-only member
+ * the owner, is refused (access_labelled_only_owner, exit 3). Only the trusted local operator sets it; a remote caller is
+ * refused before anything is written, and no MCP operation or HTTP route reaches it. Everything lives in the database, so
+ * a repo-less brain gets it unchanged.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+import { hostOnlyError } from '../ops/op-fix.ts';
+import { ACCESS_ID_RE } from './principals.ts';
+import { assertAccessId, existingMember, getMember, type MemberRecord } from './members.ts';
+import { labelledOnlyOwnerError, ownerMemberId } from './owner.ts';
+
+/**
+ * Marks a member labelled-only or clears it. Only the trusted local operator may (remote strictly false), and never on the
+ * owner; both refusals come before anything is written.
+ */
+export async function setMemberLabelledOnly(engine: BrainEngine, rawId: unknown, on: boolean, ctx: { remote?: boolean }): Promise<{ member: MemberRecord; changed: boolean }> {
+ const id = assertAccessId(rawId);
+ if (ctx.remote !== false) {
+ throw hostOnlyError({ remote: true, transport: 'http' }, 'permission_denied',
+ 'Only the brain operator on the brain host sets or clears a labelled-only grant, so nothing was changed.',
+ ['gbrain', 'access', 'member', 'labelled-only', id, on ? 'on' : 'off'],
+ 'Decides which pages every credential of that member reads. Who reads what is the brain operator\'s decision, never an agent\'s.');
+ }
+ const member = await existingMember(engine, id, 'changed');
+ if (member.status === 'removed') {
+ throw opError('access_member_id_retired', `Member id "${member.id}" was removed and can never be reused.`, 'Add a new member id instead.', { why: 'A removed member stays removed.' });
+ }
+ if (on && await ownerMemberId(engine) === member.id) throw labelledOnlyOwnerError(member.id, 'grant');
+ if (member.labelled_only === on) return { member, changed: false };
+ await engine.executeRaw('UPDATE access_members SET labelled_only = $2, updated_at = now() WHERE id = $1 AND tombstoned_at IS NULL', [member.id, on]);
+ return { member: (await getMember(engine, member.id))!, changed: true };
+}
+
+/** The enabled labelled-only members, sorted; empty when none. */
+export async function labelledOnlyMemberIds(engine: Pick<BrainEngine, 'executeRaw'>): Promise<string[]> {
+ const rows = await engine.executeRaw<{ id: string }>(
+ 'SELECT id FROM access_members WHERE labelled_only AND disabled_at IS NULL AND tombstoned_at IS NULL ORDER BY id');
+ return rows.map(r => r.id);
+}
+
+/** Whether any member carries the grant: the one cheap test a write runs before resolving its writer. Unreadable counts as yes. */
+export async function anyLabelledOnlyMember(engine: Pick<BrainEngine, 'executeRaw'>): Promise<boolean> {
+ try {
+ return (await engine.executeRaw('SELECT 1 FROM access_members WHERE labelled_only LIMIT 1')).length > 0;
+ } catch {
+ return true;
+ }
+}
+
+/**
+ * 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.
+ */
+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;
+ } catch {
+ return true;
+ }
+}
diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.ts
index 8cf196ddc8..0c30e7fa49 100644
--- a/src/core/access/member-facts.ts
+++ b/src/core/access/member-facts.ts
@@ -196,7 +196,8 @@ export function callerIdentityKey(): string {
if (!access.actor && !access.identity.length && !access.audienceIdentities.length && !access.audience) return '';
const parts = { actor: access.actor ? [access.actor.system, access.actor.member] : null, identity: access.identity, audience: access.audienceIdentities, entries: access.audience,
...(access.lineage ? { owner_reads: access.owner ? (access.ownerReadsRestricted ? 'restricted' : 'lineage') : 'member_lineage' } : {}),
- ...(access.audienceKindMembers.length ? { audience_kind: access.audienceKindMembers } : {}) };
+ ...(access.audienceKindMembers.length ? { audience_kind: access.audienceKindMembers } : {}),
+ ...(access.labelledOnly ? { labelled_only: true } : {}) };
return createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 16);
}
diff --git a/src/core/access/members.ts b/src/core/access/members.ts
index 1c87d2277b..4d013eb4de 100644
--- a/src/core/access/members.ts
+++ b/src/core/access/members.ts
@@ -36,6 +36,8 @@ export interface MemberRecord {
status: 'enabled' | 'disabled' | 'removed';
/** GBRA-108 design 2: person (the default) or audience (a group chat, a shared assistant; the owner reads its member page). */
kind: MemberKind;
+ /** GBRA-108 design 1: reads only pages that name it (access/labelled-only.ts); false by default. */
+ labelled_only: boolean;
groups: string[];
created_at: string | null;
}
@@ -107,12 +109,13 @@ function toRecord(row: Record<string, unknown>): MemberRecord {
email: (row.email as string | null) ?? null,
status: row.tombstoned_at != null ? 'removed' : row.disabled_at != null ? 'disabled' : 'enabled',
kind: row.kind === 'audience' ? 'audience' : 'person',
+ labelled_only: row.labelled_only === true,
groups: Array.isArray(row.groups) ? (row.groups as string[]) : [],
created_at: iso(row.created_at),
};
}
-const MEMBER_SELECT = `SELECT m.id, m.display_name, m.email, m.kind, m.disabled_at, m.tombstoned_at, m.created_at,
+const MEMBER_SELECT = `SELECT m.id, m.display_name, m.email, m.kind, m.labelled_only, m.disabled_at, m.tombstoned_at, m.created_at,
COALESCE(array_agg(g.group_id ORDER BY g.group_id) FILTER (WHERE g.group_id IS NOT NULL), '{}') AS groups
FROM access_members m LEFT JOIN access_group_members g ON g.member_id = m.id`;
diff --git a/src/core/access/owner.ts b/src/core/access/owner.ts
index 485b9d83fc..b39af636a2 100644
--- a/src/core/access/owner.ts
+++ b/src/core/access/owner.ts
@@ -14,6 +14,7 @@
import type { BrainEngine } from '../engine.ts';
import { OWNER_MEMBER_KEY, OWNER_READS_RESTRICTED_KEY } from '../search/private-visibility.ts';
import { hostOnlyError } from '../ops/op-fix.ts';
+import { opError, type OperationError } from '../ops/contract.ts';
import { ACCESS_ID_RE } from './principals.ts';
import { boundCredentials, memberIdentity } from './members.ts';
import type { CredentialRef } from './members.ts';
@@ -84,9 +85,32 @@ export async function setOwnerReadsRestricted(engine: BrainEngine, on: boolean,
return ownerView(engine);
}
-/** Names the owner; refuses an ill-formed or non-enabled member before writing anything. */
+/** The refusal for a labelled-only grant on the owner: `member` is the owner (or the labelled-only member named as owner). */
+export function labelledOnlyOwnerError(member: string, via: 'grant' | 'owner'): OperationError {
+ const grant = via === 'grant';
+ return opError('access_labelled_only_owner',
+ grant ? `Member "${member}" is the brain owner, so it cannot be labelled-only; nothing was changed.`
+ : `Member "${member}" is labelled-only, so it cannot be the brain owner; nothing was changed.`,
+ grant ? 'Ask the user which member the group or audience credential should read as, add that member, bind the credential to it and mark that member labelled-only.'
+ : `Ask the user whether to clear the labelled-only grant first (gbrain access member labelled-only ${member} off) or name another member the owner.`,
+ {
+ why: 'The owner reads the whole brain. A labelled-only grant would hide every unlabelled page from the owner\'s own credentials, so the two never go together.',
+ fix: grant
+ ? { ask_user: true, argv: ['gbrain', 'access', 'member', 'add', '<MEMBER>'], inputs: [{ name: 'MEMBER', how: 'Ask the user for a new member id for the group or audience credential (lower-case letters, digits, ., _ and -). Then: gbrain auth rescope --token <name> --member <MEMBER>, and gbrain access member labelled-only <MEMBER> on.' }],
+ consent: [], actor: 'user', why: 'Gives the group or audience credential its own member, which can be labelled-only, and leaves the owner reading the whole brain.', requires_exclusive: false }
+ : { ask_user: true, argv: ['gbrain', 'access', 'member', 'labelled-only', member, 'off'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Clears the labelled-only grant, so the member may be named the owner; every credential bound to it then reads its whole grant again.' },
+ });
+}
+
+/**
+ * Names the owner; refuses an ill-formed or non-enabled member, and (GBRA-108 design 1) a labelled-only one, before
+ * writing anything.
+ */
export async function setOwner(engine: BrainEngine, raw: unknown): Promise<OwnerView> {
const { member } = await memberIdentity(engine, raw);
+ const [row] = await engine.executeRaw<{ labelled_only: boolean }>('SELECT labelled_only FROM access_members WHERE id = $1', [member]);
+ if (row?.labelled_only === true) throw labelledOnlyOwnerError(member, 'owner');
await engine.setConfig(OWNER_MEMBER_KEY, member);
return ownerView(engine);
}
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index f61136ae37..d79e3e4e7d 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -110,6 +110,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'access_raw_only_rules',
'access_audience_members',
'access_members_read_lineage',
+ // GBRA-108 design 1: labelled-only members (doctor/checks/access-labelled-only.ts).
+ 'access_labelled_only_members',
// GST-1158 F3: attest credentials that read a shared-scope source as the person (doctor/checks/attest-read-access.ts).
'attest_read_shared_scope',
'extractor_facts_expired',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 99f5cbf988..687b3a59b8 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -79,6 +79,8 @@ export const CODES = {
access_serves_roster_empty: { class: 'caller', summary: 'gbrain setup --serves several or gbrain access serves several was given no people (no --members, an empty --members-file), so nothing was written.', why: 'Each person gets a member, a folder only they read and a key bound to them; the installer never guesses who they are.', suggestion: 'Name every person: --members alice-example,bob-example, or --members-file <file> with one id per line.' },
access_serves_key_dir_in_git: { class: 'caller', summary: 'The directory the per-member keys would be written to is inside a git work tree, so no key, member or rule was written.', why: 'Key files hold live credentials; a file inside a checkout can be committed and pushed.', suggestion: 'Point GBRAIN_HOME at a directory outside any git checkout (the default is your home directory) and run the command again.' },
access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },
+ access_labelled_only_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A labelled-only grant was asked for on the brain owner (gbrain access member labelled-only <owner> on), or a labelled-only member was named the owner (gbrain access owner set), so nothing was changed.", why: "The owner reads the whole brain. A labelled-only grant hides every page that does not name its member, so on the owner it would silently hide the owner's own brain from every credential bound to it.", suggestion: 'Ask the user which member the group or audience credential should read as; give it its own member and mark that one labelled-only, or clear the grant before naming the owner.' },
+ access_labelled_only_unnamed: { class: 'caller', summary: "A credential whose member is labelled-only tried to create a page that would not name it: the page has no readable_by holding the member or one of its groups, and no folder or page rule over its slug lists them, so nothing was written.", why: 'A labelled-only member reads only pages labelled for it, so a page it creates must name it; otherwise it would write a page it could never read back, readable by every other caller its source admits.', suggestion: 'Add readable_by naming the member or one of its groups to the frontmatter (readable_by: [alice-example, group:team-a]), or ask the brain operator to add a folder rule over the path that lists it, then submit again with a new request_id.' },
access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group', 'invalid_external_id', 'link_exists', 'unknown_link', 'invalid_email', 'email_taken', 'email_ambiguous'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, or a declared member email is invalid, taken or ambiguous, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },
access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },
access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },
diff --git a/src/core/function-search-path.ts b/src/core/function-search-path.ts
index b7a0b1a605..a88128a0b2 100644
--- a/src/core/function-search-path.ts
+++ b/src/core/function-search-path.ts
@@ -24,7 +24,7 @@ export const LEGACY_SEARCH_PATH_SETTINGS = ['search_path=pg_catalog, public', 's
export const PINNED_FUNCTION_NAMES = [
'auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol',
'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_lineage_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers',
- 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules',
+ 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_labelled_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules',
'gbrain_access_state_unreadable',
'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation',
'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals',
diff --git a/src/core/minions/handlers/ingest-capture.ts b/src/core/minions/handlers/ingest-capture.ts
index d6ca89ebf9..308fb4c4dd 100644
--- a/src/core/minions/handlers/ingest-capture.ts
+++ b/src/core/minions/handlers/ingest-capture.ts
@@ -44,7 +44,7 @@ import { privateRequestRefusal } from '../../persistence/visibility-request.ts';
import { parseMarkdown } from '../../markdown.ts';
import { OperationError, opError, type OperationContext } from '../../ops/contract.ts';
import { submitPageMutation } from '../../persistence/page-mutations.ts';
-import { authorizePageVisibility, defaultSourceMemberWriter, excludesPrivateWrites, remoteReadersChecked } from '../../persistence/page-visibility.ts';
+import { authorizePageVisibility, defaultSourceMemberWriter, excludesPrivateWrites, remoteLabelsChecked } from '../../persistence/page-visibility.ts';
import type { Principal, WriteAuthority } from '../../persistence/model.ts';
import { assertMemberPageWriter, assertScopePageWriter } from '../../access/member-facts.ts';
import { validateSlug } from '../../utils.ts';
@@ -131,7 +131,8 @@ export async function assertWebhookWriterMayReplace(engine: BrainEngine, writer:
if (content === undefined) return;
// The capture writes through a trusted local path, so apply the remote put_page readers rule here: a body never
// drops readable_by from a page that names readers, and the readers it names keep the writer.
- await remoteReadersChecked(engine, authority, stored?.page.frontmatter, { parsedPage: { frontmatter: parseMarkdown(content, target + '.md', { validate: true }).frontmatter } });
+ const frontmatter = parseMarkdown(content, target + '.md', { validate: true }).frontmatter;
+ await remoteLabelsChecked(engine, authority, target, stored?.page, { parsedPage: { frontmatter } });
// A page the revision backfill has not reached has no revision to bind the write to: refused, kept in the job row for `gbrain jobs retry`.
if (stored?.revision === REVISION_BACKFILL_PENDING) throw new RevisionBackfillPendingError(null);
return stored?.revision ?? null;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 4720613a21..f4ec80775e 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -37,7 +37,7 @@ import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
import { assertPurgeParams } from './purge-params.ts';
import { authorizeWrite, slugDisclosable } from './authority.ts';
-import { remoteReadersChecked, defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders } from './page-visibility.ts';
+import { remoteLabelsChecked, defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders } from './page-visibility.ts';
import { findLiveFileClaimants, type FileClaimant, type FileClaimTarget } from './file-claims.ts';
import { digest, sha256 } from './digest.ts';
import { replaceableFile } from '../facts/file-body-guard.ts';
@@ -1073,7 +1073,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
if (refusal) throw frontmatterRefusalError(refusal);
throw opError('invalid_params', 'The content was rejected before publication.', 'Check the content and frontmatter, then submit the corrected content with a new request_id.');
}
- const ready = await remoteReadersChecked(engine, row.authority, snapshot?.page.frontmatter, prepared);
+ const ready = await remoteLabelsChecked(engine, row.authority, row.slug, snapshot?.page, prepared);
if (ready.observedRevision !== observedRevision) throw pageRefusal('revision_conflict', 'The page changed during import preparation.', row,
`Page ${row.slug} was written by another request while this one was being prepared, so it published nothing. Read the current page and revision, then submit the intended change against it.`,
pageFix(row.source_id, row.slug));
diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.ts
index 066caa1942..8806a2d474 100644
--- a/src/core/persistence/page-visibility.ts
+++ b/src/core/persistence/page-visibility.ts
@@ -1,5 +1,7 @@
import { opError } from '../ops/contract.ts';
-import { callerAccessAllowedSql, callerIdentities, currentCallerAccess, OWNER_MEMBER_KEY, privatePagesFilterForCaller, readPolicyFragment, readRemotePolicyNow, resolveExcludePrivatePages, withCallerAccess } from '../search/private-visibility.ts';
+import { callerAccessAllowedSql, callerIdentities, currentCallerAccess, labelledOnlyForSql, OWNER_MEMBER_KEY, privatePagesFilterForCaller, readPolicyFragment, readRemotePolicyNow, resolveExcludePrivatePages, withCallerAccess } from '../search/private-visibility.ts';
+import { anyLabelledOnlyMember, labelledOnlyFor } from '../access/labelled-only.ts';
+import { hostFix } from '../ops/op-fix.ts';
import { parseMarkdown } from '../markdown.ts';
import { folderAccessForAll, memberIdentityFor, resolveAudienceIdentities } from '../access/caller.ts';
import type { AudiencePrincipal } from '../access/audience.ts';
@@ -33,7 +35,10 @@ export async function excludesPrivateWritesAtAdmission(engine: SqlEngine, remote
*/
export async function authorizePageVisibility(engine: SqlEngine, authority: WriteAuthority, slug: string): Promise<void> {
if (!authority.remote) return;
- if (authority.excludePrivate ?? true) {
+ // GBRA-108 design 1: a labelled-only writer reads only pages that name it, so the empty-identity shortcut (a page every
+ // caller reads) does not apply to it.
+ const labelled = await anyLabelledOnlyMember(engine) && await writerLabelledOnly(engine, authority, await writerIdentities(engine, authority));
+ if (!labelled && (authority.excludePrivate ?? true)) {
// Privacy is hidden whatever the policy says, and an empty identity is the strictest reading (an identity only
// opens a page that names readers or sits under a folder rule), so a page visible with none needs no policy read
// or member lookup.
@@ -44,7 +49,7 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writ
}
const policy = await readRemotePolicyNow(engine);
const hidePrivate = (authority.excludePrivate ?? true) || !policy.privacyRelaxed;
- if (!hidePrivate && !policy.restricted) return;
+ if (!hidePrivate && !policy.restricted && !labelled) return;
const fragment = await writerReadPolicySql(engine, authority, 'pages', hidePrivate, policy.restricted);
const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2
AND NOT (${fragment}) LIMIT 1`, [authority.sourceId, slug]);
@@ -54,14 +59,62 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writ
/**
* The read policy a stored remote write's writer is held to, re-resolved live: the member-access part always (an
* empty identity, the strictest reading, when the brain has no restrictions), then the privacy part when
- * `hidePrivate`. No operator hatch relaxes the member-access part.
+ * `hidePrivate`. No operator hatch relaxes the member-access part. GBRA-108 design 1: a labelled-only writer is held to
+ * pages that name it too, the same rule its reads follow.
*/
export async function writerReadPolicySql(engine: SqlEngine, authority: WriteAuthority, pageAlias: string, hidePrivate: boolean,
restricted?: boolean): Promise<string> {
restricted ??= (await readRemotePolicyNow(engine)).restricted;
const identities = restricted ? await writerIdentities(engine, authority) : [[]];
const folder = restricted ? await folderAccessForAll(engine, identities) : { satisfiedRuleIds: [], folderCoverage: [] };
- return withCallerAccess({ folderCoverage: folder.folderCoverage }, () => readPolicyFragment(pageAlias, { all: identities }, hidePrivate, folder.satisfiedRuleIds));
+ const fragment = withCallerAccess({ folderCoverage: folder.folderCoverage }, () => readPolicyFragment(pageAlias, { all: identities }, hidePrivate, folder.satisfiedRuleIds));
+ if (!restricted || !await anyLabelledOnlyMember(engine) || !await writerLabelledOnly(engine, authority, identities)) return fragment;
+ return `(${fragment} AND ${labelledOnlyForSql(pageAlias, identities, folder.satisfiedRuleIds)})`;
+}
+
+/**
+ * GBRA-108 design 1: a stored write is labelled-only when its credential's member, or a member it writes for, carries
+ * the grant (labelledOnlyFor); never the owner.
+ */
+async function writerLabelledOnly(engine: SqlEngine, authority: WriteAuthority, identities: readonly (readonly string[])[]): Promise<boolean> {
+ const bound = authority.actingFor && !Array.isArray(authority.actingFor) ? [] : await memberIdentityFor(engine, authority);
+ const [owner] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1', [OWNER_MEMBER_KEY]);
+ const ownerId = owner?.value?.trim();
+ const members = [...identities, bound].filter(id => !(ownerId && id.includes(`member:${ownerId}`)));
+ return labelledOnlyFor(engine, members);
+}
+
+/**
+ * GBRA-108 design 1: a labelled-only writer may create a page only when the page names it: its readable_by holds the
+ * member or one of its groups (or an audience entry it writes for), or a folder or page rule over the slug lists them.
+ * Otherwise it would write a page it could never read back. An update is held to the readers check
+ * (authorizePageVisibility), so only a slug with no live page is checked here. Refused with the readers line to add and
+ * the page rule the operator could add instead.
+ */
+export async function assertLabelledOnlyCreate(engine: SqlEngine, authority: WriteAuthority, slug: string,
+ stored: { deleted_at?: unknown } | null | undefined, frontmatter: unknown): Promise<void> {
+ if (!authority.remote || (stored && stored.deleted_at == null) || !await anyLabelledOnlyMember(engine)) return;
+ const identities = await writerIdentities(engine, authority);
+ if (!await writerLabelledOnly(engine, authority, identities)) return;
+ const named = new Set(identities.flat());
+ if ((normalizeReaders(frontmatter) ?? []).some(r => named.has(r))) return;
+ const folder = await folderAccessForAll(engine, identities);
+ const [row] = await engine.executeRaw<{ named: boolean }>('SELECT COALESCE(gbrain_access_folder_rules($1, $2) && $3::text[], false) AS named',
+ [authority.sourceId, slug, folder.satisfiedRuleIds]);
+ if (row?.named === true) return;
+ const reader = [...named].sort().find(p => p.startsWith('member:'))?.slice('member:'.length) ?? [...named].sort()[0] ?? 'alice-example';
+ throw opError('access_labelled_only_unnamed', `This connection is labelled-only, so a page it creates must name it: add readable_by: [${reader}] (or one of its groups) to the frontmatter of ${slug}, or ask the user for a page or folder rule over it that lists them; nothing was written.`,
+ `Add readable_by: [${reader}] (or one of its groups) to the frontmatter and submit again with a new request_id, or ask the user to add a page or folder rule that lists it on the brain host.`,
+ { fix: hostFix({ remote: true, transport: 'http' }, ['gbrain', 'access', 'rule', 'add', '--slug', slug, '--readers', reader, '--source', authority.sourceId],
+ 'A page rule over this slug that lists the labelled-only member, so the page it creates names it. Adding readable_by to the page itself needs no operator.') });
+}
+
+/** The readers check (remoteReadersChecked) and the labelled-only create check (assertLabelledOnlyCreate) of one remote page write. */
+export async function remoteLabelsChecked<T extends { parsedPage: { frontmatter: unknown } }>(engine: SqlEngine, authority: WriteAuthority, slug: string,
+ stored: { frontmatter?: unknown; deleted_at?: unknown } | null | undefined, prepared: T): Promise<T> {
+ const ready = await remoteReadersChecked(engine, authority, stored?.frontmatter, prepared);
+ await assertLabelledOnlyCreate(engine, authority, slug, stored, ready.parsedPage.frontmatter);
+ return ready;
}
/**
diff --git a/src/core/persistence/upload-streamed.ts b/src/core/persistence/upload-streamed.ts
index 0264cd667b..2fbf2443a5 100644
--- a/src/core/persistence/upload-streamed.ts
+++ b/src/core/persistence/upload-streamed.ts
@@ -41,7 +41,7 @@ import { stagedUploadParts, stagedUploadWork, type StagingBodyRef } from './page
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import { assertPrivateRequestKept, privateRequestGuarded, readPrivateRequest } from './visibility-request.ts';
-import { defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders } from './page-visibility.ts';
+import { assertLabelledOnlyCreate, defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders } from './page-visibility.ts';
const text = (value: unknown) => (typeof value === 'string' ? value : null);
@@ -137,6 +137,7 @@ export async function prepareStreamedUpload(engine: BrainEngine, row: WriteReque
throw opError('invalid_params', result.error ?? 'The uploaded page could not be prepared.', `Page ${row.slug} was not written. Fix what the message names, then upload it again with a new request_id.`);
}
const prepared: StreamedPreparedImport = ready;
+ await assertLabelledOnlyCreate(engine, row.authority, row.slug, snapshot?.page, prepared.frontmatter);
const privateRequest = privateRequestGuarded(row.operation, p.kind) ? readPrivateRequest('', () => prepared.frontmatter) : null;
if (privateRequest) assertPrivateRequestKept(row, privateRequest.frontmatter);
if (coreMarking(snapshot?.page.frontmatter).core || coreMarking(prepared.frontmatter).core) {
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 2f8fc824f5..302db66412 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -2962,7 +2962,7 @@ BEGIN
FOR f IN SELECT p.oid::regprocedure AS sig, substr(c.setting, 13) AS path
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace CROSS JOIN LATERAL unnest(p.proconfig) AS c(setting)
WHERE n.nspname = 'public' AND p.prokind = 'f' AND c.setting IN ('search_path=pg_catalog, public', 'search_path=pg_catalog')
- AND p.proname IN ('auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol', 'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_lineage_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers', 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules', 'gbrain_access_state_unreadable', 'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation', 'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals', 'gbrain_fts_input', 'gbrain_graduation_fence', 'gbrain_guard_deferred_request', 'gbrain_guard_effect_protocol', 'gbrain_guard_inserted_facts', 'gbrain_guard_protocol_activation', 'gbrain_guard_request_protocol', 'gbrain_guard_skill_publication', 'gbrain_lease_shared_skill_delivery', 'gbrain_mark_derivation_scope_entry', 'gbrain_preserve_fact_withdrawal', 'gbrain_queue_page_projection', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take', 'gbrain_refuse_purging_derivation', 'gbrain_release_refresh_barrier', 'gbrain_require_managed_writer', 'gbrain_require_persistence_protocol', 'gbrain_snapshot_version_trust', 'gbrain_stamp_revision_attribution', 'gbrain_stamp_trust_tier', 'gbrain_stamp_version_attribution', 'gbrain_stamp_write_attribution', 'gbrain_try_jsonb', 'notify_minion_job_change', 'update_chunk_search_vector', 'update_page_search_vector')
+ AND p.proname IN ('auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol', 'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_lineage_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers', 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_labelled_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules', 'gbrain_access_state_unreadable', 'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation', 'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals', 'gbrain_fts_input', 'gbrain_graduation_fence', 'gbrain_guard_deferred_request', 'gbrain_guard_effect_protocol', 'gbrain_guard_inserted_facts', 'gbrain_guard_protocol_activation', 'gbrain_guard_request_protocol', 'gbrain_guard_skill_publication', 'gbrain_lease_shared_skill_delivery', 'gbrain_mark_derivation_scope_entry', 'gbrain_preserve_fact_withdrawal', 'gbrain_queue_page_projection', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take', 'gbrain_refuse_purging_derivation', 'gbrain_release_refresh_barrier', 'gbrain_require_managed_writer', 'gbrain_require_persistence_protocol', 'gbrain_snapshot_version_trust', 'gbrain_stamp_revision_attribution', 'gbrain_stamp_trust_tier', 'gbrain_stamp_version_attribution', 'gbrain_stamp_write_attribution', 'gbrain_try_jsonb', 'notify_minion_job_change', 'update_chunk_search_vector', 'update_page_search_vector')
AND pg_has_role(current_user, p.proowner, 'USAGE')
ORDER BY 1
LOOP
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 0fd5ea0ff6..1217b84f60 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -3748,7 +3748,7 @@ BEGIN
FOR f IN SELECT p.oid::regprocedure AS sig, substr(c.setting, 13) AS path
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace CROSS JOIN LATERAL unnest(p.proconfig) AS c(setting)
WHERE n.nspname = 'public' AND p.prokind = 'f' AND c.setting IN ('search_path=pg_catalog, public', 'search_path=pg_catalog')
- AND p.proname IN ('auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol', 'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_lineage_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers', 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules', 'gbrain_access_state_unreadable', 'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation', 'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals', 'gbrain_fts_input', 'gbrain_graduation_fence', 'gbrain_guard_deferred_request', 'gbrain_guard_effect_protocol', 'gbrain_guard_inserted_facts', 'gbrain_guard_protocol_activation', 'gbrain_guard_request_protocol', 'gbrain_guard_skill_publication', 'gbrain_lease_shared_skill_delivery', 'gbrain_mark_derivation_scope_entry', 'gbrain_preserve_fact_withdrawal', 'gbrain_queue_page_projection', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take', 'gbrain_refuse_purging_derivation', 'gbrain_release_refresh_barrier', 'gbrain_require_managed_writer', 'gbrain_require_persistence_protocol', 'gbrain_snapshot_version_trust', 'gbrain_stamp_revision_attribution', 'gbrain_stamp_trust_tier', 'gbrain_stamp_version_attribution', 'gbrain_stamp_write_attribution', 'gbrain_try_jsonb', 'notify_minion_job_change', 'update_chunk_search_vector', 'update_page_search_vector')
+ AND p.proname IN ('auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol', 'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_lineage_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers', 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_labelled_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules', 'gbrain_access_state_unreadable', 'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation', 'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals', 'gbrain_fts_input', 'gbrain_graduation_fence', 'gbrain_guard_deferred_request', 'gbrain_guard_effect_protocol', 'gbrain_guard_inserted_facts', 'gbrain_guard_protocol_activation', 'gbrain_guard_request_protocol', 'gbrain_guard_skill_publication', 'gbrain_lease_shared_skill_delivery', 'gbrain_mark_derivation_scope_entry', 'gbrain_preserve_fact_withdrawal', 'gbrain_queue_page_projection', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take', 'gbrain_refuse_purging_derivation', 'gbrain_release_refresh_barrier', 'gbrain_require_managed_writer', 'gbrain_require_persistence_protocol', 'gbrain_snapshot_version_trust', 'gbrain_stamp_revision_attribution', 'gbrain_stamp_trust_tier', 'gbrain_stamp_version_attribution', 'gbrain_stamp_write_attribution', 'gbrain_try_jsonb', 'notify_minion_job_change', 'update_chunk_search_vector', 'update_page_search_vector')
AND pg_has_role(current_user, p.proowner, 'USAGE')
ORDER BY 1
LOOP
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index e228ee6a8c..70b544043e 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 305;
+export const LATEST_SCHEMA_VERSION = 306;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index ee670ca2bb..5081de84b8 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -306,6 +306,7 @@ import { v302 } from './v302-link-transitions-source.ts';
import { v303 } from './v303-access-page-rules.ts';
import { v304 } from './v304-access-owner-origin.ts';
import { v305 } from './v305-access-lineage-designs.ts';
+import { v306 } from './v306-access-labelled-only.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -610,4 +611,5 @@ export const MIGRATIONS: Migration[] = [
v303,
v304,
v305,
+ v306,
];
diff --git a/src/core/schema-migrations/v306-access-labelled-only.ts b/src/core/schema-migrations/v306-access-labelled-only.ts
new file mode 100644
index 0000000000..9610a45255
--- /dev/null
+++ b/src/core/schema-migrations/v306-access-labelled-only.ts
@@ -0,0 +1,76 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GBRA-108 design 1, the labelled-only grant (operator-set, off on upgrade):
+//
+// access_members.labelled_only (default false). A credential bound to a member that carries it reads only pages that
+// name that member: its id or one of its groups in readable_by, or a folder or page rule listing it
+// (search/private-visibility.ts labelledOnlySql). It lives on the member, so every token, OAuth client and stdio binding
+// of that member inherits it and no second credential can forget it.
+//
+// gbrain_access_origin_labelled_for(page, identity, satisfied rules) is the lineage arm: under
+// access.members_read_lineage a derived page with no label of its own passes only when it has an origin and every
+// origin names the caller. The origins are v305's (an atom's source page, a synthesized concept's or question's inputs,
+// an input atom's own origin, a Life Chronicle event's meeting, a declared derived_from page; aliases and renames
+// followed). No origin found, a declared derived_from that resolves to nothing, or one origin that names someone else
+// returns false (fail closed). The ordinary lineage rule (gbrain_access_origin_hidden_for) still applies on top.
+//
+// Nothing is rewritten: every member keeps labelled_only false, so every read is unchanged. No schema.sql mirror: like
+// v283, v285, v304 and v305, these exist only through migrations. Provisional number: renumbered at the merge slot.
+const LABELLED = (o: string) => `(COALESCE(${o}.page_readers && p_identity, false) OR COALESCE(${o}.folder_rule_ids && p_satisfied, false))`;
+const RESOLVED = (source: string, slug: string) => `SELECT ${slug} UNION SELECT a.canonical_slug FROM slug_aliases a WHERE a.source_id = ${source} AND a.alias_slug = ${slug}
+ UNION SELECT h.new_slug FROM slug_rename_history h WHERE h.source_id = ${source} AND h.old_slug = ${slug}`;
+const DECLARED = `jsonb_array_elements_text(CASE WHEN jsonb_typeof(fm->'derived_from') = 'array' THEN fm->'derived_from' ELSE jsonb_build_array(fm->'derived_from') END)`;
+
+export const v306: Migration = {
+ version: 306,
+ name: 'access_labelled_only',
+ idempotent: true,
+ sql: `
+ALTER TABLE access_members ADD COLUMN IF NOT EXISTS labelled_only BOOLEAN NOT NULL DEFAULT false;
+CREATE OR REPLACE FUNCTION gbrain_access_origin_labelled_for(p_id INTEGER, p_source_id TEXT, p_type TEXT, fm JSONB,
+ p_identity TEXT[], p_satisfied TEXT[]) RETURNS boolean
+ LANGUAGE plpgsql STABLE PARALLEL SAFE SET search_path = pg_catalog, public, pg_temp AS $fn$
+DECLARE
+ found boolean := false;
+BEGIN
+ IF p_type = 'atom' THEN
+ IF NOT EXISTS (SELECT 1 FROM pages o WHERE o.source_id = p_source_id AND o.slug IN (${RESOLVED('p_source_id', "fm->>'source_slug'")}))
+ OR EXISTS (SELECT 1 FROM pages o WHERE o.source_id = p_source_id AND o.slug IN (${RESOLVED('p_source_id', "fm->>'source_slug'")}) AND NOT ${LABELLED('o')}) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ ELSIF p_type = 'question' OR (p_type = 'concept' AND fm->>'synthesized_by' IS NOT NULL) THEN
+ IF NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p_id AND l.link_source = 'concept-provenance' AND l.link_type = 'synthesized_from')
+ OR EXISTS (SELECT 1 FROM links l JOIN pages i ON i.id = l.to_page_id
+ WHERE l.from_page_id = p_id AND l.link_source = 'concept-provenance' AND l.link_type = 'synthesized_from'
+ AND NOT ${LABELLED('i')}
+ AND NOT (i.type = 'atom'
+ AND EXISTS (SELECT 1 FROM pages io WHERE io.source_id = i.source_id AND io.slug IN (${RESOLVED('i.source_id', "i.frontmatter->>'source_slug'")}))
+ AND NOT EXISTS (SELECT 1 FROM pages io WHERE io.source_id = i.source_id AND io.slug IN (${RESOLVED('i.source_id', "i.frontmatter->>'source_slug'")}) AND NOT ${LABELLED('io')}))) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ ELSIF p_type = 'event' AND fm->>'captured_via' LIKE 'life-chronicle:%' THEN
+ IF NOT EXISTS (SELECT 1 FROM pages c WHERE c.source_id = p_source_id AND c.slug IN (${RESOLVED('p_source_id', "fm->'event'->>'depth'")}))
+ OR EXISTS (SELECT 1 FROM pages c WHERE c.source_id = p_source_id AND c.slug IN (${RESOLVED('p_source_id', "fm->'event'->>'depth'")}) AND NOT ${LABELLED('c')}) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ END IF;
+ IF jsonb_typeof(fm->'derived_from') IN ('array', 'string') THEN
+ IF NOT EXISTS (SELECT 1 FROM ${DECLARED})
+ OR EXISTS (SELECT 1 FROM (SELECT regexp_replace(x, '\\.md$', '') AS slug FROM ${DECLARED} AS x) declared
+ WHERE NOT EXISTS (SELECT 1 FROM pages d WHERE d.source_id = p_source_id AND d.slug IN (${RESOLVED('p_source_id', 'declared.slug')}))
+ OR EXISTS (SELECT 1 FROM pages d WHERE d.source_id = p_source_id AND d.slug IN (${RESOLVED('p_source_id', 'declared.slug')}) AND NOT ${LABELLED('d')})) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ END IF;
+ RETURN found;
+END
+$fn$;
+`,
+};
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 4a70312455..1d327aa88c 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -1323,6 +1323,7 @@ export function knobsHash(
if (access.audienceIdentities.length) parts.push(`xau=${createHash('sha256').update(JSON.stringify(access.audienceIdentities)).digest('hex').slice(0, 16)}`);
if (!access.hidePrivate) parts.push('xhp=0');
if (access.lineage) parts.push(!access.owner ? 'xol=3' : access.ownerReadsRestricted ? 'xol=2' : 'xol=1');
+ if (access.labelledOnly) parts.push('xlo=1');
if (access.audienceKindMembers.length) parts.push(`xak=${createHash('sha256').update(access.audienceKindMembers.join(',')).digest('hex').slice(0, 16)}`);
}
const h = createHash('sha256');
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 2c1990167b..589635e0fc 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -349,6 +349,14 @@ export interface CallerAccess {
* facts as if its readers named the owner. Ids pass ACCESS_ID_RE, so they embed as literals; empty otherwise.
*/
audienceKindMembers: readonly string[];
+ /**
+ * GBRA-108 design 1 (labelled-only grant): the caller's member carries access_members.labelled_only (v306), so every
+ * credential bound to it reads only pages that name it: its member id or one of its groups in readable_by, or a folder
+ * or page rule that lists it (labelledOnlySql). An unlabelled page its source grant would otherwise open is hidden; a
+ * derived page or fact with no readers and no rule of its own is hidden too, except under access.members_read_lineage
+ * where every origin is labelled for the caller (gbrain_access_origin_labelled_for). Never on the owner.
+ */
+ labelledOnly: boolean;
applyRemoteReadPolicy: boolean;
restricted: boolean;
/** The fresh remote policy (readRemotePolicyNow) a remote request read when it started; null outside one. */
@@ -359,7 +367,7 @@ const callerAccessStore = new AsyncLocalStorage<CallerAccess>();
/** The current read's caller-access record (see CallerAccess). */
export function currentCallerAccess(): CallerAccess {
- return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), owner: false, lineage: false, ownerReadsRestricted: false, audienceKindMembers: [], applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };
+ return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), owner: false, lineage: false, ownerReadsRestricted: false, audienceKindMembers: [], labelledOnly: false, applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };
}
/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */
@@ -388,6 +396,7 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):
...lineageReads(access.owner ?? (fresh ? false : base.owner), audienceIdentities.length <= 1,
access.lineage ?? (fresh ? false : base.lineage), access.ownerReadsRestricted ?? (fresh ? false : base.ownerReadsRestricted),
access.audienceKindMembers ?? (fresh ? [] : base.audienceKindMembers)),
+ labelledOnly: access.labelledOnly ?? (fresh ? false : base.labelledOnly),
applyRemoteReadPolicy: access.applyRemoteReadPolicy ?? base.applyRemoteReadPolicy,
restricted: access.restricted ?? base.restricted,
remotePolicy: access.remotePolicy ?? base.remotePolicy,
@@ -460,9 +469,50 @@ export function callerReadersAllowedSql(alias: string, row: 'page' | 'snapshot'
const ownPage = ownerOptInPage(access);
const audience = audiencePages(access);
const onPage = (test: (pageAlias: string) => string) => row === 'snapshot' ? `EXISTS (SELECT 1 FROM pages sp WHERE sp.id = ${alias}.page_id AND ${test('sp')})` : test(alias);
- if (ownPage) return `(${readersAllowedSql(alias, access.identity, row)} OR ${onPage(a => notOtherMemberPageSql(a, ownPage, audience))})`;
- if (audience.length) return `(${readersAllowedSql(alias, access.identity, row)} OR ${onPage(a => audiencePageSql(a, audience))})`;
- return callerIdentities().map(identity => readersAllowedSql(alias, identity, row)).join(' AND ');
+ const readers = ownPage ? `(${readersAllowedSql(alias, access.identity, row)} OR ${onPage(a => notOtherMemberPageSql(a, ownPage, audience))})`
+ : audience.length ? `(${readersAllowedSql(alias, access.identity, row)} OR ${onPage(a => audiencePageSql(a, audience))})`
+ : callerIdentities().map(identity => readersAllowedSql(alias, identity, row)).join(' AND ');
+ if (!access.labelledOnly) return readers;
+ if (row === 'page') return `(${readers} AND ${labelledOnlySql(alias, access)})`;
+ return `(${readers} AND (COALESCE(gbrain_access_readers(${alias}.frontmatter) && ${textArraySql(labelledIdentity(access))}, false)
+ OR EXISTS (SELECT 1 FROM pages sp WHERE sp.id = ${alias}.page_id AND ${labelledOnlySql('sp', access, false)})))`;
+}
+
+type LabelledRecord = Pick<CallerAccess, 'identity' | 'audienceIdentities' | 'satisfiedRuleIds' | 'lineage' | 'owner'>;
+
+/** GBRA-108 design 1: every principal a labelled-only read may be named by (the identity, or each audience entry's). */
+function labelledIdentity(access: LabelledRecord): string[] {
+ const identity = [...new Set([...access.identity, ...access.audienceIdentities.flat()])].sort();
+ return identity.length && validIdentity(identity) ? identity : [];
+}
+
+/**
+ * GBRA-108 design 1: `alias` names a labelled-only caller (CallerAccess.labelledOnly): its readable_by holds the caller's
+ * member or one of its groups, or one of its folder or page rules lists them (a rule the caller satisfies). Under
+ * access.members_read_lineage (a member read with lineage) a derived page with no label of its own passes only when it
+ * has an origin and every origin names the caller (gbrain_access_origin_labelled_for, v306); with it off a derived page
+ * that names nobody is hidden, whatever its origins say. ANDed with the caller's ordinary access, so it only narrows.
+ * `readers` false tests only the rules (a version snapshot carries its own readers). Ids embed as validated literals.
+ */
+function labelledOnlySql(alias: string, access: LabelledRecord, readers = true): string {
+ const identity = textArraySql(labelledIdentity(access));
+ const satisfied = textArraySql(access.satisfiedRuleIds.every(validQualifiedRuleId) ? access.satisfiedRuleIds : []);
+ const named = `(${readers ? `COALESCE(${alias}.page_readers && ${identity}, false) OR ` : ''}COALESCE(${alias}.folder_rule_ids && ${satisfied}, false))`;
+ if (!access.lineage || access.owner) return named;
+ return `(${named} OR ((${alias}.type IN ('atom', 'question', 'concept', 'event') OR ${alias}.frontmatter ? 'derived_from')
+ AND gbrain_access_origin_labelled_for(${alias}.id, ${alias}.source_id, ${alias}.type, ${alias}.frontmatter, ${identity}, ${satisfied})))`;
+}
+
+/**
+ * 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.
+ */
+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 GUEST_ENTRY = 'guest';
@@ -473,9 +523,19 @@ function validAudienceEntry(entry: string): boolean {
function callerAccessSql(pageAlias: string): string {
const access = currentCallerAccess();
const ownPage = lineageReadPage(access);
- if (ownPage) return lineageAccessSql(pageAlias, access, ownPage);
- return access.audienceIdentities.length ? accessAllowedForAllSql(pageAlias, access.audienceIdentities, access.satisfiedRuleIds)
+ const allowed = ownPage ? lineageAccessSql(pageAlias, access, ownPage)
+ : access.audienceIdentities.length ? accessAllowedForAllSql(pageAlias, access.audienceIdentities, access.satisfiedRuleIds)
: accessAllowedSql(pageAlias, access.identity);
+ return access.labelledOnly ? `(${allowed} AND ${labelledOnlySql(pageAlias, access)})` : allowed;
+}
+
+/**
+ * GBRA-108 design 1: the labelled-only conjunct for a page row checked outside the caller's read (a stored write's writer,
+ * the enforced member CLI): the page names one of `identities` or sits under a rule in `satisfied` (`readers` false: the
+ * rule alone, for a slug with no row yet). No lineage: a write never reads through it.
+ */
+export function labelledOnlyForSql(pageAlias: string, identities: readonly (readonly string[])[], satisfied: readonly string[], readers = true): string {
+ return labelledOnlySql(pageAlias, { identity: [], audienceIdentities: identities, satisfiedRuleIds: satisfied, lineage: false, owner: false }, readers);
}
/**
@@ -830,17 +890,20 @@ export function privateProvenanceFilterUnderPolicy(factAlias: string): string {
const policy = member && ACCESS_ID_RE.test(member)
? `CASE WHEN pp.slug = '${MEMBER_PAGE_PREFIX}${member}' THEN ${readPolicyFragment('pp', access.identity, hide, access.satisfiedRuleIds, true)} ELSE ${otherwise} END`
: otherwise;
- return `(NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = ${factAlias}.source_id AND pp.slug = ${factAlias}.source_markdown_slug AND NOT (${policy})) AND ${privateEntityFilterForCaller(factAlias)})`;
+ return `(NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = ${factAlias}.source_id AND pp.slug = ${factAlias}.source_markdown_slug AND NOT (${policy})) AND ${privateEntityFilterForCaller(factAlias)}${labelledOnlyFactSql(factAlias)})`;
}
/**
* A fact is never wider than the page it is about: hide a fact whose entity page (`entity_slug`, looked up in the fact's
* own source) the current caller cannot read under the read policy its page reads use, so a member the page's readers
* name keeps the fact and every other remote caller loses it. A fact with no entity page passes. Read sites only; it
- * only ever narrows.
+ * only ever narrows. GBRA-108 design 1: the entity page is judged by the caller's ordinary access, not its labelled-only
+ * grant: a labelled-only caller's fact is already kept to provenance that names it (labelledOnlyFactSql), and the
+ * page a fact is about is not one of its origins.
*/
export function privateEntityFilterForCaller(factAlias: string, perCandidate = false): string {
- return `NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = ${factAlias}.source_id AND entity_pp.slug = ${factAlias}.entity_slug AND NOT ${privatePagesFilterForCaller('entity_pp')}${perCandidate ? ' OFFSET 0' : ''})`;
+ const entityPolicy = currentCallerAccess().labelledOnly ? withCallerAccess({ labelledOnly: false }, () => privatePagesFilterForCaller('entity_pp')) : privatePagesFilterForCaller('entity_pp');
+ return `NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = ${factAlias}.source_id AND entity_pp.slug = ${factAlias}.entity_slug AND NOT ${entityPolicy}${perCandidate ? ' OFFSET 0' : ''})`;
}
/**
@@ -849,7 +912,7 @@ export function privateEntityFilterForCaller(factAlias: string, perCandidate = f
* a scan an index serves, such as the saved-fact keyword match, keeps that index.
*/
export function privateFactFilterForCaller(factAlias: string, perCandidate = false): string {
- return `(${privateProvenanceFilterFragment(factAlias)} AND ${privateEntityFilterForCaller(factAlias, perCandidate)})`;
+ return `(${privateProvenanceFilterFragment(factAlias)} AND ${privateEntityFilterForCaller(factAlias, perCandidate)}${labelledOnlyFactSql(factAlias)})`;
}
/** True only inside a remote caller record whose read an operator relaxed (the env hatch or the config opt-out). */
diff --git a/src/schema.sql b/src/schema.sql
index 8c17094d96..8036ebf6d8 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -3744,7 +3744,7 @@ BEGIN
FOR f IN SELECT p.oid::regprocedure AS sig, substr(c.setting, 13) AS path
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace CROSS JOIN LATERAL unnest(p.proconfig) AS c(setting)
WHERE n.nspname = 'public' AND p.prokind = 'f' AND c.setting IN ('search_path=pg_catalog, public', 'search_path=pg_catalog')
- AND p.proname IN ('auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol', 'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_lineage_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers', 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules', 'gbrain_access_state_unreadable', 'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation', 'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals', 'gbrain_fts_input', 'gbrain_graduation_fence', 'gbrain_guard_deferred_request', 'gbrain_guard_effect_protocol', 'gbrain_guard_inserted_facts', 'gbrain_guard_protocol_activation', 'gbrain_guard_request_protocol', 'gbrain_guard_skill_publication', 'gbrain_lease_shared_skill_delivery', 'gbrain_mark_derivation_scope_entry', 'gbrain_preserve_fact_withdrawal', 'gbrain_queue_page_projection', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take', 'gbrain_refuse_purging_derivation', 'gbrain_release_refresh_barrier', 'gbrain_require_managed_writer', 'gbrain_require_persistence_protocol', 'gbrain_snapshot_version_trust', 'gbrain_stamp_revision_attribution', 'gbrain_stamp_trust_tier', 'gbrain_stamp_version_attribution', 'gbrain_stamp_write_attribution', 'gbrain_try_jsonb', 'notify_minion_job_change', 'update_chunk_search_vector', 'update_page_search_vector')
+ AND p.proname IN ('auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol', 'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_lineage_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers', 'gbrain_access_origin_closed_for', 'gbrain_access_origin_hidden_for', 'gbrain_access_origin_labelled_for', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules', 'gbrain_access_state_unreadable', 'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation', 'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals', 'gbrain_fts_input', 'gbrain_graduation_fence', 'gbrain_guard_deferred_request', 'gbrain_guard_effect_protocol', 'gbrain_guard_inserted_facts', 'gbrain_guard_protocol_activation', 'gbrain_guard_request_protocol', 'gbrain_guard_skill_publication', 'gbrain_lease_shared_skill_delivery', 'gbrain_mark_derivation_scope_entry', 'gbrain_preserve_fact_withdrawal', 'gbrain_queue_page_projection', 'gbrain_refuse_purged_fact', 'gbrain_refuse_purged_page', 'gbrain_refuse_purged_take', 'gbrain_refuse_purging_derivation', 'gbrain_release_refresh_barrier', 'gbrain_require_managed_writer', 'gbrain_require_persistence_protocol', 'gbrain_snapshot_version_trust', 'gbrain_stamp_revision_attribution', 'gbrain_stamp_trust_tier', 'gbrain_stamp_version_attribution', 'gbrain_stamp_write_attribution', 'gbrain_try_jsonb', 'notify_minion_job_change', 'update_chunk_search_vector', 'update_page_search_vector')
AND pg_has_role(current_user, p.proowner, 'USAGE')
ORDER BY 1
LOOP
diff --git a/test/access-labelled-only.test.ts b/test/access-labelled-only.test.ts
new file mode 100644
index 0000000000..88e46946e9
--- /dev/null
+++ b/test/access-labelled-only.test.ts
@@ -0,0 +1,311 @@
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+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 { setOwner } from '../src/core/access/owner.ts';
+import { bindCredential } from '../src/core/access/members.ts';
+import { callerIdentityKey } from '../src/core/access/member-facts.ts';
+import { knobsHash, resolveSearchMode } from '../src/core/search/mode.ts';
+import { __resetPrivateVisibilityCacheForTests, withCallerAccess } from '../src/core/search/private-visibility.ts';
+import { authorizePageVisibility } from '../src/core/persistence/page-visibility.ts';
+import type { WriteAuthority } from '../src/core/persistence/model.ts';
+import { exitCodeForCode } from '../src/core/error-catalogue.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+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 { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+/**
+ * GBRA-108 design 1: the labelled-only grant (access_members.labelled_only, v306; off by default, set only by the operator
+ * on the brain host with gbrain access member labelled-only <id> on|off).
+ * 1. Protects: every credential bound to a labelled-only member reads only pages that name it (its id or one of its
+ * groups in readable_by, or a folder rule listing them), on every read path: MCP over HTTP tokens, the --as preview
+ * and the enforced member CLI's whole read surface. Unlabelled pages its source grant opens are hidden, and so is
+ * every derived page and fact with no readers or rule of its own (fail closed), except under
+ * access.members_read_lineage where every origin names the caller. An update to a page it cannot read and a create
+ * that would not name it are refused. With no grant set anywhere, nothing changes, and every other caller reads the
+ * same with the grant on.
+ * 2. Fails when: a labelled-only caller reads an unlabelled page, a derived page or fact that names nobody (off), or a
+ * derivative with one unlabelled or unreadable origin (on); misses a labelled page; another caller's view changes;
+ * the owner can hold the grant; a remote caller sets it; check, who-can-read or doctor do not report it; or the
+ * semantic cache and caller key do not separate it.
+ * 3. Real seams: tokens minted by the token service and verified by the serve --http verifier, dispatched through MCP
+ * dispatch (remote: true); the enforced member CLI's enforcedRead; the access CLI; folder rules in the database
+ * (repo-less) and in a committed access.yml (git); PGLite, and Postgres with DATABASE_URL; embeddings stubbed.
+ */
+
+const OWNER = 'owner-example';
+const BOT = 'group-bot-example';
+const ORIGINS = {
+ lab: { slug: 'notes/lab-example', fm: ['readable_by: [group:team-a]'], derive: true },
+ rule: { slug: 'team/rule-example', fm: [] as string[], derive: true },
+ open: { slug: 'notes/open-example', fm: [] as string[], derive: true },
+ other: { slug: 'notes/other-example', fm: ['readable_by: [alice-example]'], derive: true },
+};
+const MIXED = 'notes/mixed-derived';
+const LHUB = 'team/hub-labelled';
+const MIXED_CANARY = 'canarylomixedx';
+const RELAB = 'notes/relabelled-example';
+const RELAB_V1 = 'canarylorelabonex';
+const RELAB_V2 = 'canarylorelabtwox';
+const OTHERS = ['owner', 'bob', 'alice', 'unbound'] as const;
+
+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', () => {
+ const knobs = resolveSearchMode({ mode: 'balanced' });
+ const base = { identity: ['member:' + BOT, 'group:team-a'], applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] as string[] };
+ const keys = (labelledOnly: boolean, lineage = false) => withCallerAccess({ ...base, labelledOnly, lineage }, () => [knobsHash(knobs, { excludePrivate: true }), callerIdentityKey()]);
+ const [plain, labelled, plainLineage, labelledLineage] = [keys(false), keys(true), keys(false, true), keys(true, true)];
+ for (const i of [0, 1]) expect(new Set([plain[i], labelled[i], plainLineage[i], labelledLineage[i]]).size).toBe(4);
+ expect(withCallerAccess({ ...base }, () => [knobsHash(knobs, { excludePrivate: true }), callerIdentityKey()])).toEqual(plain);
+ });
+});
+
+describe('labelled-only grant: who may set it', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();
+ for (const id of [OWNER, BOT]) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ await setOwner(engine, OWNER);
+ }, 120_000);
+ afterAll(async () => { await engine?.disconnect(); });
+
+ test('a remote caller cannot set or clear it, and no operation reaches it', async () => {
+ await expect(setMemberLabelledOnly(engine, BOT, true, { remote: true })).rejects.toMatchObject({ code: 'permission_denied' });
+ await expect(setMemberLabelledOnly(engine, BOT, true, {})).rejects.toMatchObject({ code: 'permission_denied' });
+ const [row] = await engine.executeRaw<{ labelled_only: boolean }>('SELECT labelled_only FROM access_members WHERE id = $1', [BOT]);
+ expect(row!.labelled_only).toBe(false);
+ const { OPERATION_MANIFEST } = await import('../src/cli/op-manifest.ts');
+ expect(OPERATION_MANIFEST.filter(o => /labelled/.test(o.name))).toEqual([]);
+ expect(await setMemberLabelledOnly(engine, BOT, true, { remote: false })).toMatchObject({ changed: true, member: { labelled_only: true } });
+ expect(await setMemberLabelledOnly(engine, BOT, false, { remote: false })).toMatchObject({ changed: true, member: { labelled_only: false } });
+ });
+
+ test('never on the owner: setting it there, or naming a labelled-only member the owner, refuses with exit 3 and asks the user', async () => {
+ const refused = await setMemberLabelledOnly(engine, OWNER, true, { remote: false }).catch(e => e);
+ expect(refused).toMatchObject({ code: 'access_labelled_only_owner', fix: { ask_user: true, actor: 'user' } });
+ expect(String(refused.message)).toContain('is the brain owner');
+ expect(exitCodeForCode(refused.code)).toBe(3);
+ const [row] = await engine.executeRaw<{ labelled_only: boolean }>('SELECT labelled_only FROM access_members WHERE id = $1', [OWNER]);
+ expect(row!.labelled_only).toBe(false);
+ await setMemberLabelledOnly(engine, BOT, true, { remote: false });
+ const owner = await setOwner(engine, BOT).catch(e => e);
+ expect(owner).toMatchObject({ code: 'access_labelled_only_owner', fix: { ask_user: true, argv: ['gbrain', 'access', 'member', 'labelled-only', BOT, 'off'] } });
+ expect(await engine.getConfig('access.owner_member')).toBe(OWNER);
+ await setMemberLabelledOnly(engine, BOT, false, { remote: false });
+ });
+});
+
+for (const kind of testBackends()) {
+ for (const store of ['database', 'git'] as const) {
+ describe('labelled-only grant (' + kind + ', rules in ' + (store === 'git' ? 'access.yml' : 'the database, repo-less') + ')', () => {
+ let b: LineageBrain;
+ const SRC = 'lo-src';
+ const before: Record<string, Seen> = {};
+ const writeToken = { token: '', id: '' };
+ async function cli(args: string[]): Promise<any> {
+ const lines: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ try { await runAccess(b.engine, [...args, '--json']); } finally { spy.mockRestore(); }
+ return JSON.parse(lines.join('\n'));
+ }
+ const grant = async (on: boolean) => { await cli(['member', 'labelled-only', BOT, on ? 'on' : 'off']); __resetPrivateVisibilityCacheForTests(); };
+ const lineage = async (on: boolean) => { await setMembersReadLineage(b.engine, on, { remote: false }); __resetPrivateVisibilityCacheForTests(); };
+ 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 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 };
+ }
+ 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[]> {
+ const slug = ORIGINS[key].slug;
+ const reads: Array<[string, Record<string, unknown>, (text: string) => boolean]> = [
+ ['search', { query: 'harbor ledger planning notes', autocut: false, limit: 100 }, t => t.includes(b.canary(key))],
+ ['query', { query: 'harbor ledger planning notes', expand: false, autocut: false, limit: 100 }, t => t.includes(b.canary(key))],
+ ['search_exact', { phrase: b.canary(key) }, t => t.includes('"slug":"' + slug + '"')],
+ ['list_pages', { limit: 100 }, t => t.includes('"' + slug + '"')],
+ ['find_pages', { pattern: slug.split('/')[0] + '/*' }, t => t.includes('"slug":"' + slug + '"')],
+ ['get_page', { slug }, t => t.includes(b.canary(key))],
+ ['get_backlinks', { slug: LHUB }, t => t.includes('"' + slug + '"')],
+ ['get_timeline', { slug }, t => t.includes('Timeline ' + b.canary(key))],
+ ['get_links', { slug }, t => t.includes('"to_slug":"' + LHUB + '"')],
+ ['get_tags', { slug }, t => t.includes('tag-' + key)],
+ ['get_versions', { slug, include_body: true }, t => t.includes(oldCanary(key))],
+ ['whoami', {}, t => t.includes(b.canary(key)) || t.includes(slug)],
+ ['entity', { name: slug }, t => t.includes(b.canary(key))],
+ ['whois', { query: key + ' origin', types: ['note'] }, t => t.includes('"slug":"' + slug + '"')],
+ ['traverse_graph', { slug: LHUB, depth: 1, direction: 'in' }, t => t.includes('"from_slug":"' + slug + '"')],
+ ];
+ const seen: string[] = [];
+ await withEnv({ [ENFORCED_MEMBER_ENV]: BOT }, async () => {
+ for (const [op, params, shows] of reads) {
+ const text = await enforcedRead(b.engine, op, op, params, { sourceId: SRC }).then(r => JSON.stringify(r), () => '');
+ if (shows(text)) seen.push(op);
+ }
+ });
+ return seen;
+ }
+ /** get_stats --by type through the enforced CLI: the page counts the member sees. */
+ async function enforcedStats(): Promise<number> {
+ return withEnv({ [ENFORCED_MEMBER_ENV]: BOT }, async () => ((await enforcedRead(b.engine, 'get_stats', 'get_stats', { by: 'type' }, { sourceId: SRC })) as { total_pages: number }).total_pages);
+ }
+ const ALL_READS = ['search', 'query', 'search_exact', 'list_pages', 'find_pages', 'get_page', 'get_backlinks', 'get_timeline', 'get_links', 'get_tags', 'get_versions', 'entity', 'whois', 'traverse_graph'];
+
+ beforeAll(async () => {
+ b = await buildLineageBrain({
+ kind, store, src: SRC, tag: 'lo', origins: ORIGINS,
+ rules: [{ id: 'team', prefix: 'team/', readable_by: ['group:team-a'] }],
+ members: [OWNER, BOT, 'bob-example', 'alice-example'], groups: { 'team-a': [BOT, 'bob-example'] }, owner: OWNER,
+ callers: [{ name: 'owner', member: OWNER }, { name: 'bot', member: BOT }, { name: 'bob', member: 'bob-example' }, { name: 'alice', member: 'alice-example' },
+ { name: 'as-bot', as: BOT }, { name: 'unbound' }],
+ });
+ await importFromContent(b.engine, MIXED, ['---', 'type: note', 'title: mixed derived', 'derived_from: [' + ORIGINS.lab.slug + ', ' + ORIGINS.open.slug + ']', '---', '# mixed', '', 'Harbor ledger planning notes ' + MIXED_CANARY + ' here.'].join('\n'), { sourceId: SRC });
+ for (const [fm, canary] of [[[] as string[], RELAB_V1], [['readable_by: [group:team-a]'], RELAB_V2]] as const) {
+ await importFromContent(b.engine, RELAB, ['---', 'type: note', 'title: relabelled', ...fm, '---', '# relabelled', '', 'Harbor ledger planning notes ' + canary + ' here.'].join('\n'), { sourceId: SRC });
+ }
+ await importFromContent(b.engine, LHUB, ['---', 'type: project', 'title: labelled hub', '---', '# labelled hub', '', 'Anchor page.'].join('\n'), { sourceId: SRC });
+ for (const key of ['lab', 'open'] as const) {
+ await b.engine.addLink(ORIGINS[key].slug, LHUB, 'hub', 'mentions', 'fixture', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });
+ await b.engine.addTimelineEntry(ORIGINS[key].slug, { date: '2026-01-02', source: 'fixture', summary: 'Timeline ' + b.canary(key) }, { sourceId: SRC });
+ await b.engine.addTag(ORIGINS[key].slug, 'tag-' + key, { sourceId: SRC });
+ }
+ await b.engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE source_id = $1', [SRC]);
+ 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 });
+ }, 300_000);
+ afterAll(async () => { await b?.close(); }, 60_000);
+
+ test('no grant anywhere (the default): every caller, the future labelled-only member included, reads as before', async () => {
+ for (const who of [...OTHERS, 'bot', 'as-bot']) before[who] = await b.seenBy(who);
+ const ordinary = b.expected(['lab', 'rule', 'open', ...derivedOf(b.keys, ['open'])], factsOf(b.keys, ['open']));
+ expect(before.bot).toEqual(ordinary);
+ expect(before.bob).toEqual(ordinary);
+ expect(before['as-bot']).toEqual(ordinary);
+ expect(await enforcedSeen('open')).toEqual(ALL_READS);
+ expect((await doctor()).message).toStartWith('Not applicable');
+ expect((await accessCheck(b.engine, { token: 'bot' })).labelled_only).toBe(false);
+ }, 600_000);
+
+ test('on, lineage off: only the labelled pages, on every path; no derived page or fact, whatever its origin', async () => {
+ await grant(true);
+ const labelled = { ...b.expected(['lab', 'rule'], []), backlinks: [] };
+ expect(await b.seenBy('bot')).toEqual(labelled);
+ expect(await b.seenBy('as-bot')).toEqual(labelled);
+ expect(await b.call('bot', 'get_page', { slug: MIXED })).not.toContain(MIXED_CANARY);
+ for (const who of OTHERS) expect({ who, seen: await b.seenBy(who) }).toEqual({ who, seen: before[who]! });
+ }, 600_000);
+
+ test('on: the enforced member CLI shows the labelled page on every read op and the unlabelled one on none; stats count only labelled pages', async () => {
+ expect(await enforcedSeen('lab')).toEqual(ALL_READS);
+ expect(await enforcedSeen('open')).toEqual([]);
+ expect(await enforcedStats()).toBe(4);
+ }, 600_000);
+
+ test('on, lineage on: derived pages and facts of labelled origins only; never of an unlabelled, unreadable or mixed origin', async () => {
+ await lineage(true);
+ try {
+ expect(await b.seenBy('bot')).toEqual({ ...b.expected(['lab', 'rule', ...derivedOf(b.keys, ['lab', 'rule'])], factsOf(b.keys, ['lab', 'rule'])), backlinks: [] });
+ expect(await b.call('bot', 'get_page', { slug: MIXED })).not.toContain(MIXED_CANARY);
+ expect(await b.call('bob', 'get_page', { slug: MIXED })).toContain(MIXED_CANARY);
+ expect(await enforcedStats()).toBe(4 + derivedOf(b.keys, ['lab', 'rule']).length);
+ } finally {
+ await lineage(false);
+ }
+ expect(await b.seenBy('bot')).toEqual({ ...b.expected(['lab', 'rule'], []), backlinks: [] });
+ }, 600_000);
+
+ test('writes: an unreadable target is refused; a create must name the member', async () => {
+ await expect(authorizePageVisibility(b.engine, authority(), ORIGINS.open.slug)).rejects.toMatchObject({ code: 'page_not_found' });
+ await expect(authorizePageVisibility(b.engine, authority(), ORIGINS.lab.slug)).resolves.toBeUndefined();
+ await expect(authorizePageVisibility(b.engine, authority(), ORIGINS.rule.slug)).resolves.toBeUndefined();
+ // A checkout source on Postgres refuses direct writes until it is bound or allows database-only writes; the access checks run either way.
+ if (store === 'git') await b.engine.setConfig('persistence.unbound_write', 'database_only');
+ const unnamed = await put('notes/bot-new', []);
+ expect(unnamed.json).toMatchObject({ code: 'access_labelled_only_unnamed' });
+ expect(JSON.stringify(unnamed.json)).toContain('readable_by: [' + BOT + ']');
+ expect((await b.engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2', [SRC, 'notes/bot-new'])).length).toBe(0);
+ expect((await put('notes/bot-new', ['readable_by: [group:team-a]'])).isError).toBe(false);
+ expect((await put('team/bot-new', [])).isError).toBe(false);
+ await grant(false);
+ try {
+ await expect(authorizePageVisibility(b.engine, authority(), ORIGINS.open.slug)).resolves.toBeUndefined();
+ expect((await put('notes/bot-open', [])).isError).toBe(false);
+ } finally {
+ await grant(true);
+ }
+ }, 600_000);
+
+ test('access check, who-can-read and doctor report it; the grant off restores every view', async () => {
+ const check = await accessCheck(b.engine, { token: 'bot' });
+ expect(check.labelled_only).toBe(true);
+ expect(check.explanation).toContain('It is labelled-only');
+ expect((await accessCheck(b.engine, { token: 'bob' })).labelled_only).toBe(false);
+ const open = (await whoCanRead(b.engine, ORIGINS.open.slug, SRC))[0]!;
+ expect(open.note).toContain('Labelled-only members (' + BOT + ')');
+ const lab = (await whoCanRead(b.engine, ORIGINS.lab.slug, SRC))[0]!;
+ expect(lab.members).toContain(BOT);
+ expect((await whoCanRead(b.engine, ORIGINS.other.slug, SRC))[0]!.members).not.toContain(BOT);
+ const d = await doctor();
+ expect(d.status).toBe('ok');
+ expect(d.message).toContain(BOT);
+ expect((await cli(['member', 'list'])).members.find((m: { id: string }) => m.id === BOT)).toMatchObject({ labelled_only: true });
+ await grant(false);
+ expect(await b.seenBy('bot')).toEqual(before.bot);
+ expect((await doctor()).message).toStartWith('Not applicable');
+ }, 600_000);
+
+ test('an older version that named nobody stays hidden after the page is relabelled; ordinary readers still see it', async () => {
+ const versions = (who: string) => b.call(who, 'get_versions', { slug: RELAB, include_body: true });
+ expect(await versions('bob')).toContain(RELAB_V1);
+ await grant(true);
+ try {
+ expect(await b.call('bot', 'get_page', { slug: RELAB })).toContain(RELAB_V2);
+ const own = await versions('bot');
+ expect(own).not.toContain(RELAB_V1);
+ expect(await versions('bob')).toContain(RELAB_V1);
+ } finally {
+ await grant(false);
+ }
+ expect(await versions('bot')).toContain(RELAB_V1);
+ }, 600_000);
+
+ test('enforced member writes: an unlabelled target is hidden, and a new slug is writable only under a rule naming the member', async () => {
+ const view = async (slug: string) => {
+ const base = await remoteCallerAccess(b.engine, undefined, [], 'stdio', null, BOT);
+ const ea: EnforcedAccess = { member: BOT, hiddenSources: new Set(),
+ access: { ...base, identity: [...base.identity ?? []], satisfiedRuleIds: [...base.satisfiedRuleIds ?? []], hidePrivate: true, owner: false, privateReadableSources: [], applyRemoteReadPolicy: false } };
+ return memberPageView(b.engine, ea, SRC, slug);
+ };
+ const all = async () => [await view(ORIGINS.open.slug), await view(ORIGINS.lab.slug), await view('notes/enforced-new'), await view('team/enforced-new')];
+ expect(await all()).toEqual(['readable', 'readable', 'missing', 'missing']);
+ await grant(true);
+ try {
+ expect(await all()).toEqual(['hidden', 'readable', 'hidden', 'missing']);
+ } finally {
+ await grant(false);
+ }
+ expect(await all()).toEqual(['readable', 'readable', 'missing', 'missing']);
+ }, 600_000);
+ });
+ }
+}
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index c3a0d10736..7394b047aa 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -603,6 +603,7 @@
"gbrain_access_origin_closed_for(o_source text, o_slug text, o_frontmatter jsonb, o_readers text[], o_rules text[], p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=141ca5767c490e897b509cee46d2e7b54ce8ff12176c4c45ec36fb7b048cd660",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3eac3806fcfc6e54e07a28f06ce153b4ac415709cd53c50d3b24e4423646be3c",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=74057c9cd464b1993aa10970e8d21cc5fb2f66c7c7fe91dc271680901f927188",
+ "gbrain_access_origin_labelled_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a96033dc414d3a00b9fe8c84cdd66d9429260c9d62ca3a9640562944d76ed2f",
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
@@ -1814,7 +1815,8 @@
"5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"7 email text/text NULL",
- "8 kind text/text NOT NULL DEFAULT 'person'::text"
+ "8 kind text/text NOT NULL DEFAULT 'person'::text",
+ "9 labelled_only boolean/bool NOT NULL DEFAULT false"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index c382197414..3515f7116e 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -603,6 +603,7 @@
"gbrain_access_origin_closed_for(o_source text, o_slug text, o_frontmatter jsonb, o_readers text[], o_rules text[], p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=141ca5767c490e897b509cee46d2e7b54ce8ff12176c4c45ec36fb7b048cd660",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3eac3806fcfc6e54e07a28f06ce153b4ac415709cd53c50d3b24e4423646be3c",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=74057c9cd464b1993aa10970e8d21cc5fb2f66c7c7fe91dc271680901f927188",
+ "gbrain_access_origin_labelled_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a96033dc414d3a00b9fe8c84cdd66d9429260c9d62ca3a9640562944d76ed2f",
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
@@ -1814,7 +1815,8 @@
"5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"7 email text/text NULL",
- "8 kind text/text NOT NULL DEFAULT 'person'::text"
+ "8 kind text/text NOT NULL DEFAULT 'person'::text",
+ "9 labelled_only boolean/bool NOT NULL DEFAULT false"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index c2c3aa0861..16819e115d 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -603,6 +603,7 @@
"gbrain_access_origin_closed_for(o_source text, o_slug text, o_frontmatter jsonb, o_readers text[], o_rules text[], p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=141ca5767c490e897b509cee46d2e7b54ce8ff12176c4c45ec36fb7b048cd660",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3eac3806fcfc6e54e07a28f06ce153b4ac415709cd53c50d3b24e4423646be3c",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=74057c9cd464b1993aa10970e8d21cc5fb2f66c7c7fe91dc271680901f927188",
+ "gbrain_access_origin_labelled_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a96033dc414d3a00b9fe8c84cdd66d9429260c9d62ca3a9640562944d76ed2f",
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
@@ -1810,7 +1811,8 @@
"5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"7 email text/text NULL",
- "8 kind text/text NOT NULL DEFAULT 'person'::text"
+ "8 kind text/text NOT NULL DEFAULT 'person'::text",
+ "9 labelled_only boolean/bool NOT NULL DEFAULT false"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 7d94b8bbc8..b3031f2a95 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -607,6 +607,7 @@
"gbrain_access_origin_closed_for(o_source text, o_slug text, o_frontmatter jsonb, o_readers text[], o_rules text[], p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=141ca5767c490e897b509cee46d2e7b54ce8ff12176c4c45ec36fb7b048cd660",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3eac3806fcfc6e54e07a28f06ce153b4ac415709cd53c50d3b24e4423646be3c",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=74057c9cd464b1993aa10970e8d21cc5fb2f66c7c7fe91dc271680901f927188",
+ "gbrain_access_origin_labelled_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a96033dc414d3a00b9fe8c84cdd66d9429260c9d62ca3a9640562944d76ed2f",
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
@@ -1815,7 +1816,8 @@
"5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"7 email text/text NULL",
- "8 kind text/text NOT NULL DEFAULT 'person'::text"
+ "8 kind text/text NOT NULL DEFAULT 'person'::text",
+ "9 labelled_only boolean/bool NOT NULL DEFAULT false"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 129cd03abf..dd02aaad74 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -607,6 +607,7 @@
"gbrain_access_origin_closed_for(o_source text, o_slug text, o_frontmatter jsonb, o_readers text[], o_rules text[], p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=141ca5767c490e897b509cee46d2e7b54ce8ff12176c4c45ec36fb7b048cd660",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3eac3806fcfc6e54e07a28f06ce153b4ac415709cd53c50d3b24e4423646be3c",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=74057c9cd464b1993aa10970e8d21cc5fb2f66c7c7fe91dc271680901f927188",
+ "gbrain_access_origin_labelled_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a96033dc414d3a00b9fe8c84cdd66d9429260c9d62ca3a9640562944d76ed2f",
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
@@ -1815,7 +1816,8 @@
"5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"7 email text/text NULL",
- "8 kind text/text NOT NULL DEFAULT 'person'::text"
+ "8 kind text/text NOT NULL DEFAULT 'person'::text",
+ "9 labelled_only boolean/bool NOT NULL DEFAULT false"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index fa8bebae32..b889f9fff6 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -607,6 +607,7 @@
"gbrain_access_origin_closed_for(o_source text, o_slug text, o_frontmatter jsonb, o_readers text[], o_rules text[], p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=141ca5767c490e897b509cee46d2e7b54ce8ff12176c4c45ec36fb7b048cd660",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3eac3806fcfc6e54e07a28f06ce153b4ac415709cd53c50d3b24e4423646be3c",
"gbrain_access_origin_hidden_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[], p_open boolean, p_own_page text, p_audience_pages text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=74057c9cd464b1993aa10970e8d21cc5fb2f66c7c7fe91dc271680901f927188",
+ "gbrain_access_origin_labelled_for(p_id integer, p_source_id text, p_type text, fm jsonb, p_identity text[], p_satisfied text[])": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a96033dc414d3a00b9fe8c84cdd66d9429260c9d62ca3a9640562944d76ed2f",
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
@@ -1811,7 +1812,8 @@
"5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"7 email text/text NULL",
- "8 kind text/text NOT NULL DEFAULT 'person'::text"
+ "8 kind text/text NOT NULL DEFAULT 'person'::text",
+ "9 labelled_only boolean/bool NOT NULL DEFAULT false"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 322ec838d6..92f9ad81d5 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -1169,6 +1169,15 @@
"severity": "info",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Not applicable: no member is labelled-only (gbrain access member labelled-only <id> on).",
+ "name": "access_labelled_only_members",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"elapsed_ms": "<volatile>",
@@ -6289,6 +6298,15 @@
"severity": "info",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Not applicable: no member is labelled-only (gbrain access member labelled-only <id> on).",
+ "name": "access_labelled_only_members",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index e97b9d794b..310b99f308 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1015,6 +1015,15 @@
"severity": "info",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Not applicable: no member is labelled-only (gbrain access member labelled-only <id> on).",
+ "name": "access_labelled_only_members",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 62d8b75e86..b8ce4b8191 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1062,6 +1062,15 @@
"severity": "info",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Not applicable: no member is labelled-only (gbrain access member labelled-only <id> on).",
+ "name": "access_labelled_only_members",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 5a180ab54e..b0d8b1c676 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1058,6 +1058,15 @@
"severity": "info",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "Not applicable: no member is labelled-only (gbrain access member labelled-only <id> on).",
+ "name": "access_labelled_only_members",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"elapsed_ms": "<volatile>",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index e0e4487ddb..71a8d36cf6 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -413,6 +413,10 @@
"category": "brain",
"name": "access_members_read_lineage"
},
+ {
+ "category": "brain",
+ "name": "access_labelled_only_members"
+ },
{
"category": "brain",
"name": "attest_read_shared_scope"
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 930d34535f..85eaf5811d 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 300,
+ "count": 301,
"gaps": [
17,
18,
@@ -52,7 +52,7 @@
"PERSISTENCE_REQUEST_SLUG_SEQUENCE_INDEX": "4759eaf319a6ad8d99aae7648acb6556745ed7cba051175273e2f46927c77d52",
"PERSISTENCE_SYNC_RUN_INDEXES": "e1b12613c5fd2facb850e6857b0bddcf49b2478ec258fa226fe15e71e55df9c1",
"PERSISTENCE_SYNC_WATERMARK_INDEX": "93523954a30e8483717f07ec97a3e0cd062b15d8a60cc759281054b06c23bb40",
- "PINNED_FUNCTION_NAMES": "e1fae0df5d24dc4721ffc1939c661ed377c3da6f8f8eea1913a497893a2a5090",
+ "PINNED_FUNCTION_NAMES": "3fa6f2d0dd5103f72816065470decff94fdc3af11aa0269dee4765b56d0cb4a9",
"PLANNER_REPAIR_TABLES": "008725595e099adba279d4292661eb4a59930b777c35db43c340220f7f12e093",
"POSTGRES_15_GATE": "09c990d8c0bd6e4ebeb3b897477748609035b0e695b5b2c6a9bf7539f7352193",
"TABLES": "3fc77a0fccb525f9b791098f9eae27b19adaa3f5dadbabcff2a719137cbc3ef8",
@@ -103,7 +103,7 @@
"widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6",
"withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"
},
- "latest": 305,
+ "latest": 306,
"records": [
{
"handler": {
@@ -4976,6 +4976,19 @@
"transaction": "absent",
"verify": "absent",
"version": 305
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "access_labelled_only",
+ "sql": {
+ "length": 5308,
+ "sha256": "95654c03d34eb123551f0dcb816969e40f2fe9d48f70d8a5a07a03c00590315a"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 306
}
],
"versions": [
@@ -5278,7 +5291,8 @@
302,
303,
304,
- 305
+ 305,
+ 306
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 710bb7d584..f3095faad1 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -20,6 +20,7 @@ test/access-folder-multiconn.test.ts
test/access-folder-rules.test.ts
test/access-folder-scoped-role.test.ts
test/access-hidden-page-writes.test.ts
+test/access-labelled-only.test.ts
test/access-member-facts.test.ts
test/access-member-sweep.test.ts
test/access-members-read-lineage.test.ts