Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge #9171's slot head 4de92302 into qm-followups-attest-contextpack

garrytan616e33a8bb98
diff --cc CHANGELOG.md
index c721759fe0,74cbb999a1..b19785884a
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,17 -10,58 +10,69 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
- ## [Unreleased]
++## [0.60.704.0] - 2026-11-12
+
+### QM can read a room's context pack, and the owner sets how a client reads named sources from another machine
+
+**context_pack reads a room as its audience.** A QM client that reads named sources as the scope used to be refused when it asked `context_pack` for a room's source, so QM had no session brief in shared conversations. Now a call that names `source_id` reads only that source: its entities and `entity_refs`, the core block, the counterparty brief and hot facts. Nothing from the person's own member page or from pages kept to named readers comes back, and privacy is never relaxed.
+- A scope call is refused with `invalid_params` before anything is read when it sends `entity_refs` without `source_id`, names an `entity_refs` entry in another source, or sends `session_id` (a session's thread rows are the person's).
+- A client set `--attest-read person` keeps reading as the person, and its pack is narrowed to the named source the same way.
+- Contract `docs/contracts/qm-memory-provider/v5.json` marks `context_pack` `scope_read: true`. v1 to v4 stay byte for byte as published, and v4's markings are frozen in the builder.
+
+**`gbrain mcp admin attest <client> --attest-read person|scope|none`** sets the same `attest_read` that `gbrain auth rescope --attest-read` sets, over the owner session (`attestRead` on `/admin/api/access/attest`). It refuses what the local command refuses, previews with `--dry-run`, and logs `attest_read` in the `access_admin` row.
+
+ ## [0.60.703.0] - 2026-11-12
+
+ **A missing link target written while another page's links are being extracted now wakes the page that mentions it.** A `[[Name]]` reference to a page that did not exist yet was saved with the time of the save. If the target page was written during the extraction, after the extractor had looked for it but before the save, the target looked older than the saved reference, so the stale link sweep never went back to the mentioning page and the link stayed missing until one of the two pages was edited again. v0.60.679.0 named this narrow race as open. Name and basename references are now stamped with the database time taken just before the extraction reads the pages it resolves against, so a target written after that read wakes the mentioning page once on the next sweep, and a target the extractor already saw never loops.
+
+ - `src/core/wanted-links-store.ts`: `wantedReadAt` returns the database clock; `replaceWantedLinks` stamps name rows with the `readAt` its caller took before reading, and refuses name rows that arrive without one. Slug rows keep their v0.60.679.0 behaviour.
+ - Every caller that writes name rows takes the read time first: `gbrain extract` (full and `--stale`, on every run, including a page that turns stale after the pre-flight count), the wanted-link sweep, link reconciliation, and link preparation on page writes.
+ - Still open: on Postgres, a writer transaction that starts before the read time and commits after the extractor's read keeps an `updated_at` older than the stamp, so its mention waits for the next edit of either page.
+ - Tests: `nameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin` and `basenameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin` in `test/wanted-links.test.ts` and `test/e2e/wanted-links-postgres.test.ts` (both red first), and `test/wanted-links-stale-count-race.test.ts`. Idea from @akinduroifedayo's #9149.
+ - Also carries the nightly shard-weight refresh: `scripts/e2e-weights.json` and its metadata file, exactly as the weight miner wrote them from a full E2E nightly.
+
+ ## [0.60.702.0] - 2026-11-12
+
+ **A member can now be kept to pages labelled for it.** A group chat bot or a shared assistant bound to a member read every unlabelled page its source grant opened, and every summary, atom and fact made from them. `gbrain access member labelled-only <id> on` (off by default, unchanged on upgrade) keeps every credential of that member to pages that name it: the member or one of its groups in `readable_by`, or a folder or page rule listing them. Unlabelled pages, and derived pages and facts that name nobody, are hidden on every read path; with `access.members_read_lineage` on, a derived page passes only when every origin names the member. Writes follow the same rule. Only the operator on the brain host sets it, and never on the owner. It works the same on a repo-less brain and with rules in `access.yml`.
+
+ ### Itemized changes
+
+ #### Labelled-only members
+
+ - The labelled-only migration (`src/core/schema-migrations/`, numbered at merge): `access_members.labelled_only` (default false) and the SQL function `gbrain_access_origin_labelled_for()`, which passes a derived page only when it has an origin and every origin names the caller. Nothing is rewritten.
+ - `src/core/access/labelled-only.ts`: `gbrain access member labelled-only <id> [on|off]`, local operator only (remote callers get `permission_denied`), never on the owner (`access_labelled_only_owner`, exit 3; `gbrain access owner` refuses a labelled-only member the same way).
+ - `src/core/search/private-visibility.ts`: `CallerAccess.labelledOnly` adds one conjunct to every caller page, version and fact filter; derived pages and facts that name nobody fail closed, and under member lineage pass only when every origin names the caller. Facts on the member's own member page stay readable, lineage on or off. `src/core/access/caller.ts`, `actor.ts` and `src/cli/as-preview.ts` set it for a labelled-only member, and `labelledOnlyFor` never reports the configured owner, on any door.
+ - The remote read floor: `remoteReadFloorSql` and `remoteProvenanceFloorSql` (`private-visibility.ts`) are the plain page and fact fragments plus the labelled-only conjunct, and exactly the plain fragments for every other caller. Every remote read gate that is not caller-aware uses them: recorded-time reads (`get_page` and `get_versions` with `known_as_of`), the `as_of` amendment list, fact lookups by id (`remember replaces`, `forget`), belief history, proactive briefs, entity resolution and the sources-not-readable check. `test/remote-read-floor.test.ts` lists the write-side, maintenance and classification sites that keep the plain fragment, each with its reason.
+ - Attested reads: a read that names sources for a labelled-only person is refused (`permission_denied`, `src/core/access/scope-read.ts`), since the scope read drops the member identity and the grant with it.
+ - Writes: `src/core/persistence/page-visibility.ts` holds a labelled-only writer to the same read rule and refuses a create that would not name it (`access_labelled_only_unnamed`, checked in page preparation, streamed uploads and capture ingest); the enforced member CLI (`src/cli/enforced-member.ts`) does the same.
+ - The semantic cache key (`xlo=1`) and the per-caller key (`labelled_only`) separate a labelled-only caller.
+ - `gbrain access member list`, `access check` and `who-can-read` report it; doctor `access_labelled_only_members`.
+ - Docs: `docs/guides/access-designations.md` (labelled-only members), `docs/guides/error-codes.md`, key-files entry.
+ - Tests: `test/access-labelled-only.test.ts` (every read path, derived pages and facts with member lineage off and on, older versions, recorded-time and `as_of` reads, a fact by id, the member's own facts, the attested scope-read refusal and owner, writes over MCP, streamed uploads, capture ingest and the enforced CLI, the owner and remote refusals, cache keys, check, who-can-read and doctor; PGLite and Postgres, rules in the database and in `access.yml`); `test/remote-read-floor.test.ts`; migration, catalog and doctor goldens.
+
+ ## [0.60.701.0] - 2026-11-12
+
+ ### Flaky and slow tests fixed at their cause
+
+ **Four tests that failed at random in CI now pass reliably, one E2E file is back under its time limit, and one of the fixes is a real bug: a cycle could re-read pages it had already handled.** Each fix was proven with a forced probe that reproduces the CI failure before the fix and passes after it. No assertion, timeout or retry limit was loosened.
+
+ - `src/core/cycle/source-window.ts`: the cycle's page-listing cursor steps back to before the oldest transaction still open on another connection, so a page written by that transaction can't be missed. That count included Postgres autovacuum workers, which never write pages. An autovacuum pass open while the cycle listed pages made the next cycle read the pages written since that pass began a second time. Autovacuum workers no longer move the cursor (`test/sync-disabled-cycle-window.test.ts`).
+ - `test/facts-entity-moved-7602.test.ts`: the test created and killed the page write's facts-absorb job before the write's own background effect had queued it. When the effect ran later, it found a dead job under its key and queued a fresh one, so the preview reported a waiting job. The test now waits for the effect to finish before it touches the job.
+ - `test/persistence-index-lock-reclaim-6932.test.ts`: cleanup killed a helper shell whose `rm -rf` kept running after the shell died (dash forks a script's last command instead of replacing itself with it), and then ran `chmod -R` over the tree that `rm` was still deleting. Cleanup now waits for each helper to exit.
+ - `test/e2e/worktree-refresh-postgres.test.ts` ran six refresh suites in one file and took 139 to 156 s on CI against the 180 s per-file limit. Its crash-recovery, orphan and diverged-publish suites moved to `test/e2e/worktree-refresh-recovery-postgres.test.ts`; all 95 cases still run, and each file takes about 100 s on a 4-vCPU machine.
+ - `scripts/postgres-arm-weights.json`: the two PostgreSQL arm weights that were estimates now hold measured medians.
+ - `test/docs-repo-paths.test.ts` (the scripts/ and test/ paths named in docs must exist) runs in `bun run verify` as `check:docs-repo-paths`. Before, it ran only in the full suite and in `scripts/ci-doc-checks.sh`, so a pull request's own checks never ran it, and a doc edit could name a missing path and pass.
+
+ ## [0.60.700.0] - 2026-11-12
+
+ ### A gbrain commit no longer reverts someone else's commit of the same file
+
+ **When a script, an agent or a person commits their edit of a page file while gbrain is committing the same file, their commit now stays.** If that commit landed between gbrain reading HEAD and moving the branch, gbrain's one retry used to rebuild its commit on top of it with the bytes gbrain had staged earlier. HEAD silently went back to gbrain's version, the next sync reported success with nothing imported, the index kept the other version staged, and later edits to the page could be refused as an uncoordinated local edit. The other writer's bytes survived only in their own commit.
+
+ - A managed brain's Git effect now checks, before each commit attempt, that no commit since it staged its files changed any of them and that the index still holds what it staged. When one did, it commits nothing over it. A file whose edit the other writer committed completes `superseded` (reason `committed_by_another_writer`), the next sync imports the other version, and gbrain's write stays in the page's history. Every other file in the group is put back and retried on the new HEAD, so a file that still holds gbrain's bytes is committed on top.
+ - A strict (`canonical: git`) source's write refuses `git_target_changed` in the same case instead of rebuilding over the other commit, so recovery handles it the way it handles an edit made during the write.
+ - To find edits a brain already lost this way, [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md#effect-reverted-edits) has a read-only loop over the history.
+
## [0.60.699.0] - 2026-11-12
### The Ubicloud gate VMs run a current git
diff --cc docs/architecture/key-files/access.md
index de5ac31701,587efd197c..bde206388b
--- a/docs/architecture/key-files/access.md
+++ b/docs/architecture/key-files/access.md
@@@ -3,7 -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`; over HTTP `attestRead` on `/admin/api/access/attest`) is `person`, and handlers read the mode with `currentReadMode`. GST-2407: `context_pack` is a scope read too: its `entity_refs` count as naming sources, `assertPackConfined` refuses before any read a scope call without `source_id`, with an `entity_refs` entry in another source or with `session_id`, and the handler reads the named source as home (core block, pull brief, hot facts). `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v299; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. GST-2346 D1: the owner speaking for itself (`ownerSpeaksForItself`: `CallerAccess.owner`, no actor or audience, no subagent, no slug fence) takes the world route unless it passes `visibility: "private"` or the page or `facts.default_visibility` makes the default private (then its member page), is never refused `member_share_required`, and its `forget` of a fact off its member page takes the ordinary remote path when that path reads the fact. A fact off every member and scope page, on a page the owner reads under the GST-2490 rule with the opt-in off (`ownerReadPolicyFragment`) and may write as a member, a page whose readers name it included, with the fact's entity page judged the same way (`ownerReachesFact`, `forget-prepare.ts`), is withdrawn too: submission marks the request `owner_reach`, and preparation judges the owner again from the stored authority (`storedOwnerSpeaksForItself`, `page-visibility.ts`), so a writer that is no longer the owner gets `not_found`; a more trusted fact files the `forget_requires_owner` proposal. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); a remote save there meets only the page's own withdrawals and those of a claim its member reads (`memberPageWithdrawal`), and the insert guards mark a member-page row only by its page's own withdrawals (`schema-migrations/*-member-page-withdrawal-scope.ts`), so a claim the member never read cannot refuse or expire its save; consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) on the stored actor, else the stored audience, and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).
-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). GST-2490: an owner read (`CallerAccess.lineage` with `owner`, read-only ops only) uses `lineageAccessSql`: the owner's readers and folder rules as for any member, with `gbrain_access_origin_hidden_for()` (v304; per origin `gbrain_access_origin_closed_for()`) in place of the every-caller lineage, so a derivative or fact passes when the owner reads every origin; `ownerReadsRestricted` (config `access.owner_reads_restricted`, `owner.ts` `setOwnerReadsRestricted`, local only) also passes pages kept to other members except another member's own member page and pending coverage. `access check`, `who-can-read`, `whoami` (`ownerReadsRestrictedNotice`) and doctor `access_owner_reads_restricted` report it; test `test/owner-reads-restricted.test.ts` (both engines, database and access.yml rules). GBRA-108 (migration v305, `v305-access-lineage-designs.ts`): `access_rules.covers_derived` (default true) — a raw-only rule (`folder-rules.ts` `covers_derived: false`, `rule add --raw-only`; digest unchanged for covering rules; true→false is the held widening `derived_released`, false→true the narrowing `derived_covered`) is dropped from an origin's rule set by the SQL function `gbrain_access_lineage_rules()` inside `gbrain_access_origin_restricted()` and the 10-argument `gbrain_access_origin_closed_for()`, so it keeps its pages but not their lineage (a page's own readers still close it; fact provenance filters judge with `derived = true`). `access_members.kind` (`person` | `audience`, `members.ts` `setMemberKind`, local only): an owner read carries `CallerAccess.audienceKindMembers`, whose member pages pass the readers test and the member-page exemptions (`audiencePages`, `notOtherMemberPageSql`, the `p_audience_pages` argument of the 9-argument `gbrain_access_origin_hidden_for()`). Config `access.members_read_lineage` (`lineage.ts`, local only) sets `CallerAccess.lineage` for any member read speaking for itself (`caller.ts`; never an audience of several or an unbound credential; `withCallerAccess` drops it for several identities and keeps the owner opt-in and audience members owner-only). Cache keys: `knobsHash` `xol=3` and `xak=`, `callerIdentityKey` `owner_reads`/`audience_kind`. Doctor `access_lineage` (`checks/access-lineage.ts`). Tests: `test/access-raw-only-rules.test.ts`, `test/access-audience-members.test.ts`, `test/access-members-read-lineage.test.ts` (both engines, both stores; fixture `test/helpers/access-lineage-fixture.ts`). GBRA-108 design 1 (the labelled-only migration, `schema-migrations/v*-access-labelled-only.ts`): `access_members.labelled_only` (`labelled-only.ts` `setMemberLabelledOnly`, local only, refused on the owner with `access_labelled_only_owner` from `owner.ts`, which `setOwner` also raises) sets `CallerAccess.labelledOnly` (`caller.ts`, `actor.ts`, `as-preview.ts`; fails closed to true when the table cannot be read). `private-visibility.ts` `labelledOnlySql` ANDs `page_readers && identity OR folder_rule_ids && satisfied` into `callerAccessSql`, `callerReadersAllowedSql` (a snapshot needs its own readers or a rule on the live page) and the fact filters (`labelledOnlyFactSql`: a fact on the caller's own member page while it names the member, or under member lineage a provenance page that passes; else FALSE); under member lineage a derived row may pass through `gbrain_access_origin_labelled_for()` (every origin labelled, none missing). Remote read gates that are not caller-aware use `remoteReadFloorSql` / `remoteProvenanceFloorSql` (the plain fragment, plus the labelled-only conjunct only for a labelled-only caller); `test/remote-read-floor.test.ts` lists the sites that keep the plain fragment. `labelledOnlyFor` never reports the configured owner, and dispatch refuses a scope read for a labelled-only person (`scope-read.ts` `scopeReadLabelledOnlyRefused`). The entity page of a fact is judged by the ordinary policy. Writes: `persistence/page-visibility.ts` (`writerReadPolicySql`, `remoteLabelsChecked` → `assertLabelledOnlyCreate` → `access_labelled_only_unnamed`), `cli/enforced-member.ts` `memberPageView`. Cache keys `xlo=1`, `labelled_only`; doctor `access_labelled_only_members` (`checks/access-labelled-only.ts`). Test: `test/access-labelled-only.test.ts` (both engines, both storesA derivative of a page that names readers is otherwise hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v299; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. GST-2346 D1: the owner speaking for itself (`ownerSpeaksForItself`: `CallerAccess.owner`, no actor or audience, no subagent, no slug fence) takes the world route unless it passes `visibility: "private"` or the page or `facts.default_visibility` makes the default private (then its member page), is never refused `member_share_required`, and its `forget` of a fact off its member page takes the ordinary remote path when that path reads the fact. A fact off every member and scope page, on a page the owner reads under the GST-2490 rule with the opt-in off (`ownerReadPolicyFragment`) and may write as a member, a page whose readers name it included, with the fact's entity page judged the same way (`ownerReachesFact`, `forget-prepare.ts`), is withdrawn too: submission marks the request `owner_reach`, and preparation judges the owner again from the stored authority (`storedOwnerSpeaksForItself`, `page-visibility.ts`), so a writer that is no longer the owner gets `not_found`; a more trusted fact files the `forget_requires_owner` proposal. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); a remote save there meets only the page's own withdrawals and those of a claim its member reads (`memberPageWithdrawal`), and the insert guards mark a member-page row only by its page's own withdrawals (`schema-migrations/*-member-page-withdrawal-scope.ts`), so a claim the member never read cannot refuse or expire its save; consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) on the stored actor, else the stored audience, and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).
++- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). GST-2490: an owner read (`CallerAccess.lineage` with `owner`, read-only ops only) uses `lineageAccessSql`: the owner's readers and folder rules as for any member, with `gbrain_access_origin_hidden_for()` (v304; per origin `gbrain_access_origin_closed_for()`) in place of the every-caller lineage, so a derivative or fact passes when the owner reads every origin; `ownerReadsRestricted` (config `access.owner_reads_restricted`, `owner.ts` `setOwnerReadsRestricted`, local only) also passes pages kept to other members except another member's own member page and pending coverage. `access check`, `who-can-read`, `whoami` (`ownerReadsRestrictedNotice`) and doctor `access_owner_reads_restricted` report it; test `test/owner-reads-restricted.test.ts` (both engines, database and access.yml rules). GBRA-108 (migration v305, `v305-access-lineage-designs.ts`): `access_rules.covers_derived` (default true) — a raw-only rule (`folder-rules.ts` `covers_derived: false`, `rule add --raw-only`; digest unchanged for covering rules; true→false is the held widening `derived_released`, false→true the narrowing `derived_covered`) is dropped from an origin's rule set by the SQL function `gbrain_access_lineage_rules()` inside `gbrain_access_origin_restricted()` and the 10-argument `gbrain_access_origin_closed_for()`, so it keeps its pages but not their lineage (a page's own readers still close it; fact provenance filters judge with `derived = true`). `access_members.kind` (`person` | `audience`, `members.ts` `setMemberKind`, local only): an owner read carries `CallerAccess.audienceKindMembers`, whose member pages pass the readers test and the member-page exemptions (`audiencePages`, `notOtherMemberPageSql`, the `p_audience_pages` argument of the 9-argument `gbrain_access_origin_hidden_for()`). Config `access.members_read_lineage` (`lineage.ts`, local only) sets `CallerAccess.lineage` for any member read speaking for itself (`caller.ts`; never an audience of several or an unbound credential; `withCallerAccess` drops it for several identities and keeps the owner opt-in and audience members owner-only). Cache keys: `knobsHash` `xol=3` and `xak=`, `callerIdentityKey` `owner_reads`/`audience_kind`. Doctor `access_lineage` (`checks/access-lineage.ts`). Tests: `test/access-raw-only-rules.test.ts`, `test/access-audience-members.test.ts`, `test/access-members-read-lineage.test.ts` (both engines, both stores; fixture `test/helpers/access-lineage-fixture.ts`). GBRA-108 design 1 (the labelled-only migration, `schema-migrations/v*-access-labelled-only.ts`): `access_members.labelled_only` (`labelled-only.ts` `setMemberLabelledOnly`, local only, refused on the owner with `access_labelled_only_owner` from `owner.ts`, which `setOwner` also raises) sets `CallerAccess.labelledOnly` (`caller.ts`, `actor.ts`, `as-preview.ts`; fails closed to true when the table cannot be read). `private-visibility.ts` `labelledOnlySql` ANDs `page_readers && identity OR folder_rule_ids && satisfied` into `callerAccessSql`, `callerReadersAllowedSql` (a snapshot needs its own readers or a rule on the live page) and the fact filters (`labelledOnlyFactSql`: a fact on the caller's own member page while it names the member, or under member lineage a provenance page that passes; else FALSE); under member lineage a derived row may pass through `gbrain_access_origin_labelled_for()` (every origin labelled, none missing). Remote read gates that are not caller-aware use `remoteReadFloorSql` / `remoteProvenanceFloorSql` (the plain fragment, plus the labelled-only conjunct only for a labelled-only caller); `test/remote-read-floor.test.ts` lists the sites that keep the plain fragment. `labelledOnlyFor` never reports the configured owner, and dispatch refuses a scope read for a labelled-only person (`scope-read.ts` `scopeReadLabelledOnlyRefused`). The entity page of a fact is judged by the ordinary policy. Writes: `persistence/page-visibility.ts` (`writerReadPolicySql`, `remoteLabelsChecked` → `assertLabelledOnlyCreate` → `access_labelled_only_unnamed`), `cli/enforced-member.ts` `memberPageView`. Cache keys `xlo=1`, `labelled_only`; doctor `access_labelled_only_members` (`checks/access-labelled-only.ts`). Test: `test/access-labelled-only.test.ts` (both engines, both storesA derivative of a page that names readers is otherwise hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`; over HTTP `attestRead` on `/admin/api/access/attest`) is `person`, and handlers read the mode with `currentReadMode`. GST-2407: `context_pack` is a scope read too: its `entity_refs` count as naming sources, `assertPackConfined` refuses before any read a scope call without `source_id`, with an `entity_refs` entry in another source or with `session_id`, and the handler reads the named source as home (core block, pull brief, hot facts). `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v299; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. GST-2346 D1: the owner speaking for itself (`ownerSpeaksForItself`: `CallerAccess.owner`, no actor or audience, no subagent, no slug fence) takes the world route unless it passes `visibility: "private"` or the page or `facts.default_visibility` makes the default private (then its member page), is never refused `member_share_required`, and its `forget` of a fact off its member page takes the ordinary remote path when that path reads the fact. A fact off every member and scope page, on a page the owner reads under the GST-2490 rule with the opt-in off (`ownerReadPolicyFragment`) and may write as a member, a page whose readers name it included, with the fact's entity page judged the same way (`ownerReachesFact`, `forget-prepare.ts`), is withdrawn too: submission marks the request `owner_reach`, and preparation judges the owner again from the stored authority (`storedOwnerSpeaksForItself`, `page-visibility.ts`), so a writer that is no longer the owner gets `not_found`; a more trusted fact files the `forget_requires_owner` proposal. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); a remote save there meets only the page's own withdrawals and those of a claim its member reads (`memberPageWithdrawal`), and the insert guards mark a member-page row only by its page's own withdrawals (`schema-migrations/*-member-page-withdrawal-scope.ts`), so a claim the member never read cannot refuse or expire its save; consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) on the stored actor, else the stored audience, and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).
- `src/core/access/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 --cc src/core/access/scope-read.ts
index b5493a06eb,a04b27a133..143d6d0f84
--- a/src/core/access/scope-read.ts
+++ b/src/core/access/scope-read.ts
@@@ -55,22 -54,23 +55,33 @@@ export function attestedReadMode(op: st
return 'scope';
}
+/**
+ * GST-2407: a context_pack scope read reads one source, the source_id it names: its entities, every entity_refs entry,
+ * the core block, the pull brief and hot facts (ops/facts.ts reads the scope's source as home). session_id is refused,
+ * since a session's thread rows belong to the person. Each refusal comes before any read.
+ */
+function assertPackConfined(params: Record<string, unknown>): void {
+ const source = params.source_id;
+ const refused = (problem: string, fix: string) => opError('invalid_params', `context_pack: ${problem}, and this credential reads named sources as their audience, so it is refused. Nothing was read.`, fix,
+ { why: 'A scope read must name exactly the one source it reads, so the pack never reads past the scope the turn serves.' });
+ if (typeof source !== 'string' || !source) throw refused('a scope read of the pack names exactly one source in source_id, and this call names none', 'Pass source_id with the one source to read (the source every entity_refs entry names), or leave source_ids and entity_refs out to read as the person.');
+ if ((params.entity_refs as unknown[] | undefined)?.some(ref => (ref as { source_id?: unknown } | null)?.source_id !== source)) {
+ throw refused(`an entity_refs entry names a source other than source_id '${source}'`, 'Name only entities in the source_id the call reads, each with that source_id.');
+ }
+ if (params.session_id !== undefined && params.session_id !== null && params.session_id !== '') throw refused('a scope read cannot read a session\'s thread rows (session_id)', 'Leave session_id out of a call that names source_id.');
+}
+
+ /**
+ * GBRA-108 design 1: a scope read takes the member's identity away, and with it the labelled-only grant, so it would
+ * open every unlabelled page of the named sources. An attested read for a labelled-only member that names sources is
+ * refused instead, before anything is read.
+ */
+ export function scopeReadLabelledOnlyRefused(op: string): OperationError {
+ return opError('permission_denied', `${op}: this person is labelled-only, so a read that names sources cannot run as their audience. Nothing was read.`,
+ 'Leave source_id and source_ids out to read as the person, which shows only the pages labelled for them.',
+ { why: 'A scope read drops the member identity, and the labelled-only grant with it, so it would show pages nobody labelled for this person.' });
+ }
+
-function contextPackScopeRefused(): OperationError {
- return opError('invalid_params', 'context_pack: a call that names sources would read them as the person, and this credential reads named sources as their audience, so it is refused. Nothing was read.',
- 'Leave source_id, source_ids, all_sources and entity_refs out to read as the person, or call query, get_page or entity with source_id for the scope.',
- { why: 'context_pack is not yet confined to the named sources, so it cannot run as a scope read.' });
-}
-
function scopeAllSourcesRefused(op: string): OperationError {
return opError('invalid_params', `${op}: a call that names sources reads them as their audience, so '${ALL_SOURCES}' and all_sources are refused. Nothing was read.`,
'Name the sources to read in source_id or source_ids, or leave them out to read as the person.',
diff --cc test/access-labelled-only.test.ts
index 0000000000,ccb9bb0612..b15a102c6c
mode 000000,100644..100644
--- a/test/access-labelled-only.test.ts
+++ b/test/access-labelled-only.test.ts
@@@ -1,0 -1,457 +1,486 @@@
+ import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+ import { createHash, randomUUID } from 'node:crypto';
+ import type { DoctorContext } from '../src/commands/doctor/context.ts';
+ import { accessLabelledOnlyEntry } from '../src/commands/doctor/checks/access-labelled-only.ts';
+ import { accessCheck, runAccess, whoCanRead } from '../src/commands/access.ts';
+ import { setMembersReadLineage } from '../src/core/access/lineage.ts';
+ import { labelledOnlyFor, setMemberLabelledOnly } from '../src/core/access/labelled-only.ts';
+ import { linkMember } from '../src/core/access/actor.ts';
+ import { enableBeliefLedger } from '../src/core/belief/coverage.ts';
+ import { assertWebhookWriterMayReplace } from '../src/core/minions/handlers/ingest-capture.ts';
+ import { setOwner } from '../src/core/access/owner.ts';
+ import { bindCredential } from '../src/core/access/members.ts';
+ import { callerIdentityKey } from '../src/core/access/member-facts.ts';
+ 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, ENTITY as ENTITY_SLUG, factsOf, HUB, type LineageBrain, type Seen } from './helpers/access-lineage-fixture.ts';
+ import { testBackends } from './helpers/test-backends.ts';
+ import { withEnv } from './helpers/with-env.ts';
+
+ /**
+ * GBRA-108 design 1: the labelled-only grant (access_members.labelled_only, the labelled-only migration; 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;
+ const BOT_QM = 'U0BOTEXAMPLE';
+ const OWNER_QM = 'U0OWNEREXAMPLE';
+ const KAO = 'notes/recorded-open-example';
+ const KAO_CANARY = 'canarylorecordedx';
+ const AMENDED = 'notes/amended-lab-example';
+ const OWN_FACT = 'The group bot keeps its own planning checklist';
+ const MiB = 1024 ** 2;
+ const PART_CHARS = 3_900_000;
+
+ describe('labelled-only grant: the cache keys', () => {
+ test('the semantic cache and the caller identity key separate a labelled-only caller from an ordinary one', () => {
+ 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: '' };
+ const attestClient = { token: '' };
+ async function cli(args: string[]): Promise<any> {
+ const lines: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ 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);
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(b.engine), transaction: fn => b.engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ /** One remote call as the bot's write token, or (`actor`) as the attest client naming that person. */
+ async function wcall(op: string, params: Record<string, unknown>, actor?: string): Promise<{ isError: boolean; text: string; json: Record<string, any> }> {
+ const auth = await provider().verifyAccessToken(actor ? attestClient.token : writeToken.token) as unknown as AuthInfo;
+ const out = await dispatchToolCall(b.engine, op, params, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'], inboundFrameBytes: 4 * MiB,
+ ...(actor ? { actor: { header: actor } } : {}) });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, any> = {};
+ try { json = JSON.parse(text); } catch { /* prose */ }
+ return { isError: out.isError === true, text, json };
+ }
+ const note = (title: string, fm: string[]) => ['---', 'type: note', 'title: ' + title, ...fm, '---', '# ' + title, '', 'Written by the group bot.'].join('\n');
+ const put = (slug: string, fm: string[]) => wcall('put_page', { slug, content: note('Bot page', fm) });
+ const oldCanary = (key: string) => 'canaryold' + 'lo' + key.replace(/[^a-z]/g, '') + 'x';
+ /** The enforced member CLI's whole read surface (enforced-member-classes READ_OPS), for one origin key: which ops show it. */
+ async function enforcedSeen(key: 'lab' | 'open'): Promise<string[]> {
+ 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 });
+ const client = await provider().registerClientManual('lo-attest-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);
+ await bindCredential(b.engine, { kind: 'client', id: client.clientId }, { attestActor: 'qm', attestOps: ['get_page'] });
+ attestClient.token = (await provider().exchangeClientCredentials(client.clientId, client.clientSecret ?? '')).access_token;
+ await linkMember(b.engine, BOT, 'qm', BOT_QM);
+ await linkMember(b.engine, OWNER, 'qm', OWNER_QM);
+ }, 300_000);
+ afterAll(async () => { await b?.close(); }, 60_000);
+
+ 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);
+
+ test('on: a recorded-time read (get_page and get_versions with known_as_of) of an unlabelled page is page_not_found; an as_of read names no unlabelled amendment', async () => {
+ await enableBeliefLedger(b.engine, SRC);
+ await importFromContent(b.engine, KAO, ['---', 'type: note', 'title: recorded open', '---', '# recorded open', '', 'Harbor ledger planning notes ' + KAO_CANARY + ' here.'].join('\n'), { sourceId: SRC });
+ await importFromContent(b.engine, AMENDED, ['---', 'type: note', 'title: amended lab', 'readable_by: [group:team-a]', "valid_from: '2026-01-01'", '---', '# amended lab', '', 'Anchor page.'].join('\n'), { sourceId: SRC });
+ await b.engine.addLink(ORIGINS.open.slug, AMENDED, 'amends', 'amends', 'fixture', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });
+ const knownAsOf = new Date().toISOString();
+ const asOf = knownAsOf.slice(0, 10);
+ const reads = async (who: string) => [
+ await b.call(who, 'get_page', { slug: KAO, known_as_of: knownAsOf }),
+ await b.call(who, 'get_versions', { slug: KAO, known_as_of: knownAsOf, include_body: true }),
+ ];
+ for (const text of await reads('bot')) expect(text).toContain(KAO_CANARY);
+ expect(await b.call('bot', 'get_page', { slug: AMENDED, as_of: asOf })).toContain(ORIGINS.open.slug);
+ await grant(true);
+ try {
+ for (const text of await reads('bot')) {
+ expect(text).not.toContain(KAO_CANARY);
+ expect(JSON.parse(text).code).toBe('page_not_found');
+ }
+ const amended = JSON.parse(await b.call('bot', 'get_page', { slug: AMENDED, as_of: asOf }));
+ expect(amended.slug).toBe(AMENDED);
+ expect(JSON.stringify(amended)).not.toContain(ORIGINS.open.slug);
+ for (const text of await reads('bob')) expect(text).toContain(KAO_CANARY);
+ expect(await b.call('bob', 'get_page', { slug: AMENDED, as_of: asOf })).toContain(ORIGINS.open.slug);
+ } finally {
+ await grant(false);
+ }
+ }, 600_000);
+
+ test('on: a fact on an unlabelled page is not_found by id, like a fact that does not exist', async () => {
+ const [fact] = await b.engine.executeRaw<{ id: number | string }>("SELECT id FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND source = 'fixture'", [SRC, ORIGINS.open.slug]);
+ const replace = (id: string) => wcall('remember', { fact: 'A replacement planning claim', entity: ENTITY_SLUG, provenance: 'fixture chat 2026-11-01', replaces: id });
+ expect((await replace(String(fact!.id))).json.message).toContain('replaces_visibility_mismatch');
+ await grant(true);
+ try {
+ const hidden = await replace(String(fact!.id));
+ const missing = await replace('999999');
+ expect({ code: hidden.json.code, message: hidden.json.message.replace(String(fact!.id), 'N') }).toEqual({ code: missing.json.code, message: missing.json.message.replace('999999', 'N') });
+ expect(missing.json.code).toBe('not_found');
+ } finally {
+ await grant(false);
+ }
+ }, 600_000);
+
+ test('on: recall returns the member\'s own facts with lineage off and on, and still no fact of another page', async () => {
+ expect((await wcall('remember', { fact: OWN_FACT, entity: ENTITY_SLUG, provenance: 'fixture chat 2026-11-01' })).isError).toBe(false);
+ await grant(true);
+ try {
+ for (const on of [false, true]) {
+ await lineage(on);
+ const text = (await wcall('recall', { entity: ENTITY_SLUG })).text;
+ expect(text).toContain(OWN_FACT);
+ for (const key of on ? ['open', 'other'] : ['lab', 'rule', 'open', 'other']) expect(text).not.toContain(b.canary(key + '.fact'));
+ }
+ } finally {
+ await lineage(false);
+ await grant(false);
+ }
+ }, 600_000);
+
+ test('attested reads: a scope read for a labelled-only person is refused before anything is read; the person read stays labelled-only', async () => {
+ const scope = () => wcall('get_page', { slug: ORIGINS.open.slug, source_id: SRC }, BOT_QM);
+ expect((await scope()).text).toContain(b.canary('open'));
+ await grant(true);
+ try {
+ const refused = await scope();
+ expect({ isError: refused.isError, code: refused.json.code }).toEqual({ isError: true, code: 'permission_denied' });
+ expect(refused.json.message).toContain('labelled-only');
+ expect(refused.text).not.toContain(b.canary('open'));
+ expect((await wcall('get_page', { slug: ORIGINS.open.slug }, BOT_QM)).json.code).toBe('page_not_found');
+ expect((await wcall('get_page', { slug: ORIGINS.lab.slug }, BOT_QM)).text).toContain(b.canary('lab'));
+ } finally {
+ await grant(false);
+ }
+ }, 600_000);
+
++ test('GST-2407: a context_pack scope read for a labelled-only person is refused before anything is read, like every other scope read', async () => {
++ const client = await provider().registerClientManual('lo-pack-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);
++ await bindCredential(b.engine, { kind: 'client', id: client.clientId }, { attestActor: 'qm', attestOps: ['context_pack'] });
++ const token = (await provider().exchangeClientCredentials(client.clientId, client.clientSecret ?? '')).access_token;
++ const pack = async (params: Record<string, unknown>) => {
++ const out = await dispatchToolCall(b.engine, 'context_pack', params, { remote: true, transport: 'http', auth: await provider().verifyAccessToken(token) as unknown as AuthInfo,
++ sourceId: SRC, takesHoldersAllowList: ['world'], inboundFrameBytes: 4 * MiB, actor: { header: BOT_QM } });
++ 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, text, json };
++ };
++ const scope = { source_id: SRC, entity_refs: [{ source_id: SRC, slug: ORIGINS.open.slug }] };
++ expect((await pack(scope)).isError).toBe(false);
++ await grant(true);
++ try {
++ const refused = await pack(scope);
++ expect({ isError: refused.isError, code: refused.json.code }).toEqual({ isError: true, code: 'permission_denied' });
++ expect(refused.json.message).toContain('context_pack: this person is labelled-only');
++ expect(refused.text).not.toContain(b.canary('open'));
++ expect((await pack({ source_id: SRC, entity_refs: [{ source_id: 'other-src', slug: ORIGINS.open.slug }] })).json.code).toBe('invalid_params');
++ const person = await pack({ entities: 'Harbor' });
++ expect(person.isError).toBe(false);
++ expect(person.text).not.toContain(b.canary('open'));
++ } finally {
++ await grant(false);
++ }
++ }, 600_000);
++
+ test('the owner is never labelled-only, whatever the stored flag says, on the attested door too', async () => {
+ await b.engine.executeRaw('UPDATE access_members SET labelled_only = true WHERE id = $1', [OWNER]);
+ __resetPrivateVisibilityCacheForTests();
+ try {
+ expect(await labelledOnlyFor(b.engine, [['member:' + OWNER]])).toBe(false);
+ expect((await wcall('get_page', { slug: ORIGINS.open.slug }, OWNER_QM)).text).toContain(b.canary('open'));
+ expect(await b.call('owner', 'get_page', { slug: ORIGINS.open.slug })).toContain(b.canary('open'));
+ } finally {
+ await b.engine.executeRaw('UPDATE access_members SET labelled_only = false WHERE id = $1', [OWNER]);
+ __resetPrivateVisibilityCacheForTests();
+ }
+ }, 600_000);
+
+ test('creates: a webhook capture must name the member, as put_page does', async () => {
+ const writer = { principal: { kind: 'legacy_token', id: writeToken.id } };
+ await grant(true);
+ try {
+ await expect(assertWebhookWriterMayReplace(b.engine, writer, SRC, 'notes/capture-new', note('Capture', []))).rejects.toMatchObject({ code: 'access_labelled_only_unnamed' });
+ expect(await assertWebhookWriterMayReplace(b.engine, writer, SRC, 'notes/capture-new', note('Capture', ['readable_by: [group:team-a]']))).toBeNull();
+ } finally {
+ await grant(false);
+ }
+ expect(await assertWebhookWriterMayReplace(b.engine, writer, SRC, 'notes/capture-new', note('Capture', []))).toBeNull();
+ }, 600_000);
+
+ if (store === 'database') test('creates: a streamed upload over the single-string ceiling must name the member; nothing is written', async () => {
+ await b.engine.setConfig('write_gate.agent_mode', 'off');
+ await grant(true);
+ try {
+ const slug = 'notes/bot-upload-new';
+ const filler = 'We agreed to ship the review checklist first and revisit pricing next week. '.repeat(64) + '\n\n';
+ const text = note('Bot upload', []) + '\n\n' + filler.repeat(Math.ceil(25 * MiB / filler.length));
+ const sha = (s: string) => createHash('sha256').update(s).digest('hex');
+ const begin = await wcall('begin_page_upload', { slug, mode: 'create', total_bytes: Buffer.byteLength(text), sha256: sha(text), request_id: randomUUID() });
+ expect(begin.isError).toBe(false);
+ for (let part = 0, at = 0; at < text.length; part++, at += PART_CHARS) {
+ const piece = text.slice(at, at + PART_CHARS);
+ expect((await wcall('upload_page_part', { upload_id: begin.json.upload_id, part, text: piece, part_sha256: sha(piece) })).isError).toBe(false);
+ }
+ let commit = await wcall('commit_page_upload', { upload_id: begin.json.upload_id, wait_ms: 30_000 });
+ for (let attempt = 0; commit.json.code === 'write_pending' && attempt < 40; attempt++) commit = await wcall('commit_page_upload', { upload_id: begin.json.upload_id, wait_ms: 30_000 });
+ expect(commit.text).toContain('access_labelled_only_unnamed');
+ expect((await b.engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2', [SRC, slug])).length).toBe(0);
+ } finally {
+ await grant(false);
+ await b.engine.executeRaw("DELETE FROM config WHERE key = 'write_gate.agent_mode'");
+ }
+ }, 600_000);
+ });
+ }
+ }