Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge #9211's slot head a0d31305 into labelled-only-grant

garrytanac2f0106d8b4
diff --cc CHANGELOG.md
index 95ad87368c,927b2836bc..ae624c07cc
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,25 -10,155 +10,174 @@@ 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]
+
+**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.699.0] - 2026-11-12
+
+ ### The Ubicloud gate VMs run a current git
+
+ **The test suite passes on a gate VM again.** Gate VMs ran stock Ubuntu 24.04's git 2.43. GitHub's runners and dev machines are on 2.5x. Three test files depend on newer git:
+ - `test/effect-git-secret-gate.test.ts` needs `git maintenance run --detach`, which arrived in git 2.47.
+ - `test/sync-partial-clone-2331.test.ts` (both the unit and PostgreSQL arms) needs newer partial-clone behaviour.
+
+ Because of that, every VM gate (`bun run ci:ubicloud`, `scripts/pregate-remote-gate.sh` when it can't reuse a CI run) failed those files no matter what the change was.
+
+ - `scripts/ubicloud/setup-ci-vm.sh` now installs git from the git-core PPA, as GitHub's runner images do. It requires at least git 2.47.0 (`GIT_MIN`) and fails setup with the version it found when git is older. A prebuilt image whose git is older than that no longer counts as ready, so it runs the apt step too. On one standard-16 VM, setup took 97 s and installed git 2.56.1. All three files passed there: effect-git-secret-gate 29/0, sync-partial-clone-2331 unit 12/0, its PostgreSQL arm 23/0. sync-disabled-cycle-window's PostgreSQL arm also passed, 7/0.
+ ## [0.60.698.0] - 2026-11-12
+
+ **A stalled background sync of a large source is retried with a budget that can finish it, and the retries no longer stop silently**
+
+ - A large source that the background syncer could not finish no longer retries forever with the same short budget. A resident gives its first run 30 seconds, and every resident restart or change of the process holding the notifier counted as "first" again, so each retry stopped at the same point having saved nothing. That short budget now goes only to a source with no failed attempts on record, and a retry after a run that saved nothing gets the full sync budget.
+ - A source the background syncer marked stalled (`notifier_stalled`, "retrying every 300 s") now really is retried every five minutes. With `sync.on_commit` off (the default), the retry only happened while the original sync request was still on record, and a run that stopped early could clear that request, so the source sat stalled with nothing retrying it and nothing in the log. The retry now continues until a run completes, also after a restart or when another resident takes over the notifier, which now reads the state the previous one recorded. Turning `sync.on_commit` off, or excluding the source, still ends a retry that a HEAD move started.
+ - `gbrain sync --skip-failed`, and the automatic skip after three failed syncs, no longer skip files that were refused because of how the source is set up rather than because anything is wrong with them (`strict_requires_managed`: a `canonical: git` source on a brain without managed persistence). Skipping them moved the sync checkpoint to the latest commit with no pages imported, after which `sync status` said synced and later syncs found nothing to do, even once the setup was fixed. The sync now stays blocked, says why, and names the two fixes: turn on managed persistence, or remove `canonical: git`, after which the next plain sync imports every page. A brain that was already skipped past this way needs one `gbrain sync --source <id> --full`. A scheduled `gbrain sync --skip-failed && …` on such a source now stops at the blocked sync until the setup is fixed.
+ - A background job that went back to the queue because its worker was killed while running other jobs no longer waits for as long as the next worker stays busy. Such a job only runs alone, so a memory-watchdog stop can be blamed on the right job, and a worker that always had another job running never picked it up: a sync job requeued this way after a restart waited more than ten minutes. Once it has waited a minute, a worker now takes no new jobs until the ones it is running finish, then runs it first. A worker checks for such a job every five seconds, so a queue with none claims exactly as fast as before.
+
+ **Every push gbrain makes from an unmanaged checkout now scans the commits it publishes for secrets, and a long first push can finish.** `gbrain git commit-push` scanned only with `--push-only --scan-secrets`, so its commit mode, `--pending`, the post-commit hook `gbrain sources harden` installs and `scripts/brain-commit-push.sh` pushed earlier local commits unscanned; they now refuse `publish_secret_found` or `publish_scan_unreadable` like the four pushes below, and the refusal is logged in `brain-push.log`. The helper's fallback for a machine without gbrain commits and no longer pushes, since it cannot scan. A scan that runs out of its 300 s budget refuses naming the same command with `--scan-timeout <seconds>`, which `gbrain git commit-push`, `gbrain sources push` and `gbrain bootstrap repo` now take; the scan reads every commit either way, prints its progress on stderr and keeps its temporary disk use to one batch of commits. No push follows tags any more, so `push.followTags` cannot publish an annotated tag's message unscanned. `gbrain sources push` reads origin's branch tip from origin itself when the branch tracks another remote (it used to fail the push, never skip commits), prints its refusal with `--json` and exits 5, and the access-policy commit reports a refusal as `committed_not_pushed` instead of failing.
+
+ ### Itemized changes
+
+ - `src/commands/git.ts`: every mode passes `scanSecrets` (`--scan-secrets` is still accepted), `--scan-timeout <s>` (whole seconds, not with `--pull`), progress lines on stderr, and a scan refusal logged as `LOCAL-ONLY, NEEDS ATTENTION ... the push was refused (<code>)`.
+ - `src/core/git/range-secret-scan.ts`: commit messages read with one `cat-file --batch` and patches with one `diff-tree` per 256 commits (the patch file holds one batch, not the whole history), progress lines, `PublishScanOptions` (budget, progress, retry command), and a timed-out scan refused with an agent fix that reruns with four times the budget (at least 1200 s).
+ - `src/core/git/commit-push.ts`, `src/core/workspace-push.ts`, `src/core/bootstrap/repo.ts`: `--no-follow-tags --recurse-submodules=no` on every push, so no tag or submodule commit goes out unscanned; `gbrain sources push` fetches origin's branch before it scans and returns the scan refusal as `blocked_history`.
+ - `src/commands/git.ts`: `gbrain git scan [--from <rev>] [--to <rev>] [--json]` runs the push's scan over a range and changes nothing (no fetch, lock or push), printing what a push would refuse and each finding's fingerprint for `.gbrain-scan-allow`; `commit-push --dry-run` names the managed-worktree marker, or none.
+ - `src/commands/sources.ts`, `src/commands/bootstrap.ts`: `--scan-timeout`; `sources push` prints a `blocked_history` refusal and exits 5.
+ - `src/core/access/policy-git.ts`: a scan refusal returns `committed_not_pushed` with the refusal in its note.
+ - `src/core/brain-repo-durability.ts`: the post-commit hook and the helper pass `--scan-secrets` (so an older gbrain still scans), the helper uses only a gbrain whose `git commit-push --help` names `--scan-timeout`, and its fallback commits, logs the commit as local-only and exits 4 (0 when the branch is already on the remote).
+ - Tests: `test/unmanaged-push-every-site-gst2456.serial.test.ts` (each push site against a local bare remote, tags, another upstream remote, the `--json` refusal, the budget and progress); the #8902, fallback and bootstrap argv tests follow the new contracts.
+
+ ## [0.60.697.0] - 2026-11-12
+
+ **A quarantined fact or take for a page that already exists is now held for review on a strict source, instead of failing.** With trust protections on (`write_gate.external_mode = quarantine`), a `remember` or `takes_add` of tool output that reads like an instruction is held for the owner's review (`write_held`, a ref such as `h1`). On a source whose pages are canonical in Git (`canonical: git`), that write failed when its page already existed (for a fact, also when it had no entity and `memory/unattributed` already existed). Nothing was saved and nothing was held, so the owner had nothing to review, and the caller was told storage failed: `remember` answered `unavailable` with `write_error: storage_error` ("The write did not commit"), and `takes_add` answered `git_home_required` with `write_error: storage_error`. Now the write is held there exactly as on any other source. Nothing of the held text reaches a fact or take row, a page or Git until the owner decides. Releasing a fact commits it to the page's file before its database row, so a database rebuilt from Git keeps it; a held take still cannot be released on any source, and the owner drops it (`gbrain trust drop h1`). Sources that are not strict and brains with no Git repository answer as before.
+
+ ### Itemized changes
+
+ - `src/core/persistence/memory-prepare.ts`, `takes-prepare.ts`: a held `remember` or take is a no-op publication (`noop: true`), as a duplicate fact already was. It writes no page content, so the strict-source check no longer reads it as a page stored without a file in Git (`git_home_required`), and it no longer queues an embedding effect for the unchanged page.
+ - `docs/guides/write-refusals.md`: the `git_home_required` row says a held fact or take is not refused this way.
+ - Tests: `test/gated-hold-strict-page-gst2535.test.ts` (a held fact on a strict source with the page, local and over MCP, and with `memory/unattributed` present: nothing stored before the release, the release committed to the page in Git before its row and kept by a rebuild from a clone of HEAD; a held take on a strict source: nothing stored, the release refused as on every source, the owner's drop; a source that is not strict and a brain with no Git repository unchanged for both); PGLite and Postgres.
+
+ ## [0.60.696.0] - 2026-11-12
+
+ **`gbrain mcp verify` now passes its write check on a credential bound to a member.** The verifier's test fact was always sent with `visibility: "world"`, which `remember` refuses for a member credential, so every member-bound connection showed "write" and "write_readback" as failed even when it was set up correctly. A member-bound credential now saves the test fact the way a member's own saves go by default. It is kept private on that member's page, where no other member reads it. The verifier reads the fact back and withdraws it, as before. A credential bound to no member still shares its test fact explicitly, so a brain whose `facts.default_visibility` is private still reads it back. Page mode (`coding-agent` profiles and credentials with direct-write prefixes) had a second mistake: its `put_page` call passed a `title` parameter the tool doesn't declare, so every page-mode write was refused. The title now goes in the page's frontmatter. The same fixes apply to the verify step inside `gbrain connect … --install`.
+
+ ### Itemized changes
+
+ - `src/core/harness/verify.ts`: the fact-mode write reads the credential's bound member from `whoami` (`access.member`) and sends `visibility: "world"` only when there is none. The page-mode `put_page` drops the undeclared `title` parameter for a frontmatter title.
+ - Tests: `test/harness-verify-member-credential.test.ts` covers a non-owner member, the owner and an unbound credential, in fact mode and page mode, on PGLite and Postgres (repo-less). It also checks that a member's fixture is private on its member page and unreadable by another member, and that an unbound credential passes under a private `facts.default_visibility`.
+ ## [0.60.695.0] - 2026-11-12
+
+ **An upgrade no longer adopts another application's OAuth table and then stops halfway, and rerunning `gbrain apply-migrations --force-schema` now recovers a brain that stopped.** gbrain creates `oauth_tokens`, `oauth_clients` and `oauth_codes` with `CREATE TABLE IF NOT EXISTS`, so when another application sharing the Postgres database already had a table with one of those names, gbrain took it over, added its own columns to it, and a later upgrade stopped at v210 with `operator does not exist: timestamp with time zone > bigint`. That error named neither the table nor the column, and it came after earlier migrations in the same run had already applied. The documented recovery, rerunning the same command, then could not create gbrain's own table.
+
+ ### Itemized changes
+
+ - **Schema setup refuses a table gbrain did not create, before changing anything.** Before the schema replay (`gbrain init`, every engine start that applies migrations) and before any migration in a run, gbrain checks that each OAuth table that already exists has every column gbrain has always given it, with the same type. When one does not, it stops with the new `foreign_table` error, which names the table, the column, the type it found, the type gbrain needs and the fix: give gbrain its own database, or move the other table with `ALTER TABLE <table> SET SCHEMA <other_schema>`, then run `gbrain apply-migrations --force-schema --yes`. A correctly shaped brain runs exactly as before, and v210 is unchanged. Guide: [foreign table](docs/guides/troubleshooting.md#foreign-table).
+ - **`gbrain apply-migrations` replays the schema before the pending migrations on every path.** With the migration lease held (every PGLite brain, and every Postgres brain whose schema has the lease table) it ran the pending migrations without the schema replay, so a table the replay creates that was missing stayed missing and the next migration failed with `relation "<table>" does not exist`. It now goes through the same schema setup as `gbrain init --migrate-only` on every path. A brain an older release stopped at v210 recovers with `gbrain upgrade` and the steps the guide lists.
+ - Tests: `test/upgrade-foreign-oauth-table.test.ts` runs on PGLite and Postgres: the refusal on an upgrade (a foreign `oauth_tokens`) and on a fresh install (a foreign `oauth_codes` or `oauth_clients`), the rerun that recreates a missing table, and the full recovery of a brain stopped at v210.
+
+ Reported by @jonahberg (#9190, #9191); first fixed by @Masashi-Ono0611 in #9195 and #9193.
+
+ ## [0.60.694.0] - 2026-11-12
+
+ **Labels you set on an agent's page now hold, and an agent can no longer take you out of a page's readers.** When you made an agent-written page private with `gbrain repair visibility` (or set its readers with `--readers`), the page kept its agent tier, so a later agent write at that tier could drop the label again with nothing held. Your label repairs now raise the page's label guard to your tier, so that write is held the same way as one over a page you wrote: it publishes with your labels kept and waits for you in `gbrain trust review`. Separately, a local write below your tier whose `readable_by` would leave you, the brain owner, out of a page you read now keeps you in the list (the rest of the narrowing still applies), and its `lower_page` item records the readers it asked for, which `gbrain trust confirm tp<id>` applies. Confirming such an item on a page whose own tier is an agent's changes only its labels and leaves the page at the agent's tier, so saying yes to a label change never vouches for the body; on a page of yours, confirm still endorses the edit at your tier. Your own readers changes, synced edits, agent narrowing that keeps you, and brains with the owner opt-in to read restricted pages are unaffected. The guard lives in a new database table and is set only by label repairs run after the upgrade, so labels you set earlier, and a managed Git brain rebuilt from a clone, start unguarded: running `gbrain repair visibility --slug <page>` or `--readers <list>` again on a page that already has those labels raises the guard without changing the labels or writing the page (GST-2521).
+
+ - A new schema migration: new `page_label_guards` table, one row per page, removed with the page. `src/core/repair/label-write.ts` and the maintenance door's `keep_trust` path (`src/core/persistence/prepared-maintenance.ts`) raise it to `operator_curated` in the label write's transaction when the page is left private or naming readers, and remove it otherwise.
+ - `src/core/trust/page-write.ts`: the label guard reads the page's guard row as a floor, and names the owner as a reader the write must keep when the owner reads the page by its readers and `access.owner_reads_restricted` is off. The held readers are the requested ones with the owner added, or the stored ones when the request is malformed. An error reading the owner fails the write instead of dropping the owner. The `lower_page` item records the page's own tier before the write (`before_state.page_tier`).
+ - `src/core/trust/page-handlers.ts`: accepting a held item whose page's own tier was below `operator_curated` writes only the requested labels, keeps the page's tier and resolves the item `labels_applied` (status `labelled`); on an owner page the confirm is unchanged. Undo of either restores the kept labels.
+ - `src/core/repair/visibility.ts`, `src/core/repair/readers.ts`: a named page that is already private, or already names the requested readers, and has no guard row is listed (`visibility private kept, label guard raised`, `readers [...] kept, label guard raised`) and applied by raising the guard under the page's row lock, with no page write or commit.
+ - Tests: `test/owner-label-guard.test.ts` covers both routes with unbound, other-member and owner-bound reads before, during and after, accept and reject, an agent's own page, a page that named no readers, accept on an agent page keeping its tier, a re-run of the label repair raising the guard on already-labelled pages (repo-less and a managed batch with no commit), the cases that must pass, and the committed file on a managed Git source, on PGLite and Postgres.
+
+ **A less trusted write that makes a private fenced fact world no longer stores a world fact before the owner decides.** An agent `put_page` that turned a more trusted private `## Facts` row world (the same claim at its row number or restated at another, or a different claim at its row number) stored its row world at once, so remote recall returned the private claim while the owner's proposal waited, and accepting that proposal then failed as stale. The writer's row is now stored private and contested, its proposal records the widening, `gbrain trust confirm tp<id>` makes the claim world and `gbrain trust drop tp<id>` keeps it private, and later writes of that fence by the same writer, and the background facts reconcile, keep it private meanwhile. A claim the page already holds world is not treated as a widening, and an accept applies the widening only while the page's fence row still asks for world. A `remember` that restates a private claim world is not covered by this change. The page text still holds the visibility the writer wrote, so a remote page read shows that row until the owner decides (GST-2511).
+
+ - `src/core/trust/fence-guard.ts`, `src/core/trust/supersede-handlers.ts`: a contested replacement that would make a guarded private row world, or a new world row restating a more trusted private claim of the page, is inserted private, its `supersede_fact` proposal carries `visibility: {from, to}`, the owner's accept sets it (undo restores it), and a lower-tier write keeps that contested row private while its widening is pending, rejected or undone (GST-2511).
+ - `src/core/cycle/extract-facts.ts`: the fence reconcile keeps the visibility of a contested row whose widening proposal is pending, rejected or undone, instead of widening it to the page's cell (GST-2511).
+
+ **An agent edit can no longer make a private page readable before you decide.** A local `put_page` (or `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) from a writer less trusted than the page used to publish at once even when it dropped or widened the page's `visibility`, `access`, `confidentiality` or `readable_by`. The only safeguard was a `lower_page` item in `gbrain trust review`, and until you dealt with it, remote callers and other members could read the page. The usual cause was an agent that rewrote a page and forgot its frontmatter. Now that write publishes with the page's earlier labels kept, in the database and in the file it commits, and its receipt names the kept keys (`privacy_labels_kept`). The `lower_page` item shows the labels the edit asked for. `gbrain trust confirm tp<id>` applies exactly those labels if the page hasn't changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm puts them back while the page is still as the confirm left it. The same hold covers a derived page publication by a maintenance job (for example a dream patterns run that rewrites one of your pages), a page with no trust tier recorded yet (`unknown`), which counts as yours, and an agent that deletes a page and writes it again: a delete no longer lowers the page's tier. A credential bound to you reads the page throughout. Unaffected: writes that only narrow a label, writes that leave the labels alone, writers at or above the page's tier, your own synced edits, and `gbrain repair visibility` (GST-2518).
+
+ ### Itemized changes
+
+ - `src/core/trust/page-write.ts`, `src/core/persistence/page-prepare.ts`: a local content write below `operator_curated`, and below the page's label guard tier, keeps the stored labels it would widen, and so does a derived page publication. The guard tier is the page's tier (`operator_curated` lowered by its frontmatter caps when the tier is `unknown`), raised to the earlier tier recorded on every `lower_page` item of the page since the last one you confirmed. The `lower_page` item records the kept and requested labels, and a later write by the same tier replaces them with what it asked for, so a write that puts the label back withdraws the request. A write that changes only labels publishes nothing and still files its item.
+ - `src/core/trust/page-handlers.ts`: confirming a held item writes the requested labels in the same owner page write that confirms the page. New undo for a confirmed held item restores the kept labels and the edit's tier, and only while the page is at the revision the confirm wrote.
+ - `src/core/persistence/page-prepare.ts`: a soft delete keeps the page's tier (it writes no content). `src/core/persistence/prepared-maintenance.ts`: a derived publication whose labels were kept files one item, with the labels.
+ - `src/core/trust/owner-actions.ts`, `src/core/trust/review.ts`: the confirm and drop previews and the review item name the held labels.
+ - Tests: `test/lower-tier-label-hold.test.ts` covers each label dropped and widened, remote reads (unbound, another member, the owner), accept, reject, undo, a stale undo, a withdrawn request, the two-step and reject-then-lower bypasses, a delete then a write, an `unknown` page, a derived maintenance publication, the cases that must pass unheld, and the committed file on a managed Git source, on PGLite and Postgres.
+
+ ## [0.60.693.0] - 2026-11-12
+
+ **The brain owner's own agents can now withdraw a private fact the brain host saved.** A credential bound to the brain owner (`gbrain access owner set`) reads private facts, but its `forget` refused one the host had saved with `visibility: "private"` and said only the brain host could withdraw it. Now, speaking for itself, the owner's credential (or a stdio server started with `--stdio-member <owner>`) withdraws a private fact it reads when the page that holds it is one the credential can already write. The fact is struck in the page's file on a brain with a Git repository, and on a strict source a fact held for an entity with no page is struck in `memory/unattributed`, so a rebuild from Git keeps it withdrawn. Three things stay as they were. A fact on a `visibility: private` page, on a page whose readers leave the owner out or on another member's page is still withdrawn on the brain host (`gbrain forget <id>`). A fact the owner confirmed or curated still asks the owner first (`forget_requires_owner`). Member credentials, attested calls (`x-qm-actor`), audiences, subagent jobs, slug-fenced clients and unbound connections get exactly the answers they got before.
+
+ **The owner's agents can also withdraw a fact on a page that lists the owner as a reader.** Since 0.60.682.0 the owner's `recall` shows facts on a page whose `readable_by` names the owner, but its `forget` and `forget_fact` answered `not_found` for them. Now they withdraw such a fact, private or shared, when the owner's credential may also write that page and the page of the entity the fact is about, if it has one, is one the owner reads the same way. The owner opt-in that lets the owner read pages kept to other members (`gbrain access owner reads-restricted on`) does not extend to `forget`: those facts are still withdrawn on the brain host. Every caller that is not the owner speaking for itself gets the answer it got before.
+
+ **A member's save no longer reveals that a claim it never read was withdrawn.** When the brain host or the owner withdrew a claim, a member that later saved the same claim on its own member page was refused with `fact_withdrawn`, which told it that a claim it could never read had existed and been forgotten. Now that save succeeds and gets the same reply it would get if the other claim had never existed. The fact is the member's own, it stays active, and the member's `recall` returns it. A save is still refused when the member could read what was withdrawn, which means a fact it forgot itself, its own copy that the brain host's `forget` withdrew, or for the owner, a fact it reads anywhere. A schema migration changes the two database guards that mark a newly saved row as withdrawn so a row on a member page is marked only by that page's own withdrawals; it rewrites no rows. Brains with and without a Git repository behave the same way.
+
+ ### Itemized changes
+
+ - `src/core/persistence/memory-mutations.ts`, `forget-prepare.ts`: the owner's `forget` reaches a fact on a page that names it as a reader (`ownerReachesFact`): that page, and the fact's entity page where one exists, must pass GST-2490's owner read rule (`ownerReadPolicyFragment` in `search/private-visibility.ts`, the opt-in off) and the read rule a member write is held to, for the owner's identity. Preparation re-resolves that identity from the stored principal and checks the fact again under the publication's locks, so a page that drops the owner from its readers after submission refuses `not_found`.
+ - `src/core/facts/single-prepare.ts`: a remote save onto a member page meets the page's own withdrawals and a withdrawal of another subject only when a withdrawn row is one the page's member reads (`memberPageWithdrawal`). Callers in `memory-prepare.ts` and `ops/qm-memory.ts` pass `remote`.
+ - `src/core/facts/withdrawal-schema.ts`, `insert-guard-schema.ts` and a new schema migration make the insert guards mark a row on a member page only by that page's own withdrawals; `access/member-facts.ts` (`withdrawalCoversFactSql`) and `facts/embedding-identity.ts` treat such a row as covered by its own page's withdrawals only. A withdrawal still expires every matching row, member pages included, when it is made.
+ - Tests: `test/owner-facts-d1-gst2346.test.ts` (the owner's forget on a page that names it, the nine non-owner caller shapes and a member reader unchanged, the opt-in, preparation from the stored principal and under locks, the managed-brain file; the member's save compared byte for byte after a host and an owner withdrawal, and the refusals that stay); PGLite and Postgres.
+
+ - `src/core/persistence/memory-mutations.ts`: `forget` and `forget_fact` let the owner speaking for itself through for a private fact off every member and scope page, on a page no remote writer is kept from, and mark the stored request. The refusal that names the brain host now tells the owner what its credential does withdraw.
+ - `src/core/persistence/forget-prepare.ts`, `src/core/persistence/page-visibility.ts`: preparation judges the owner again from the stored principal (`storedOwnerSpeaksForItself`), and once more under the publication's locks. A writer that is no longer the enabled owner, or that named an actor, an audience, a subagent or a slug fence, reads the fact as any remote caller does and gets `not_found`.
+ - Guards kept: the same claim active on a page kept from remote writers refuses `claim_linked` and withdraws nothing; a more trusted fact files the `forget_requires_owner` proposal, which stores the fact's id and tier only.
+ - Docs: access designations, `MEMORY_VERBS_v1.md`, the access key-files entry; behavior-change notice.
+ - Tests: `test/owner-facts-d1-gst2346.test.ts` (the owner's forget and forget_fact, every other caller shape unchanged, the trust proposal and its accept, preparation from the stored principal, the managed-brain file) and `test/remember-strict-held-gst2492.test.ts` (a held private fact on a strict source, with a rebuild); PGLite and Postgres.
+ ## [0.60.692.0] - 2026-11-12
+
+ **On a source whose pages are canonical in Git, every fact writer now commits a fact with no page of its own to Git, and doctor and a new repair find the ones an older gbrain left in the database only.** In the last release only `remember` did this. Google loops, fact extraction, the managed facts writer and an owner releasing a quarantined fact now also commit a fact with no entity, or for an entity with no page, as a row of `memory/unattributed`. Before, they kept it in the database only, where a rebuild from Git lost it, or were refused with `git_home_required` once that page existed. Sources that are not strict, and brains with no Git repository, behave as before.
+
+ - **A fact saved under a bare name moves when its page appears in a folder.** `remember` keys a new name such as "Kofi Example" as `kofi-example`. Once exactly one page with that name exists, such as `people/kofi-example`, the maintenance cycle moves the held fact into it in one commit and re-keys it to that page. If two pages could be meant, the fact stays held, and the doctor check and the repair preview name both pages.
+ - **New doctor check: `strict_facts_outside_git`.** For each strict source it counts facts with no Git home, facts held more than 30 days for a page that never appeared, and held facts that cannot move. Its fix is the read-only preview of the new repair.
+ - **New repair: `gbrain repair facts-home --source <id>`.** It is explicit-only and preview-bound: `--apply --expect <hash>` writes the listed facts to `memory/unattributed`, at most 500 per run, and it never runs on upgrade. It lists, without moving, the facts it cannot place. Those are facts for an entity under a folder access rule, a row the Facts table cannot show, an ontology observation, a row of a deleted page, and a fact whose entity page is deleted (that page may have been private, and purging it would not reach a row on the holding page, so the fact is listed until the page is restored or purged). The new writers skip such an entity the same way.
+ - **Known limit:** a fact for an entity under a folder access rule that has no page yet still stays in the database only, because the holding page is readable by everyone. The doctor check counts these facts and the repair lists them as `folder_restricted`.
+ - **The `entity_page_missing` notice asks before it creates a page.** While the fact is in the database only, the notice's step is now `next: ask_user`: its `user_message` says the fact is saved in the database only and asks whether to create a page for the entity, and the `put_page` call is the fix once the user agrees. When the fact is already held in Git, the notice only says where it is and that it moves once the page exists, with no step to run. This holds for single and batch `remember`, over MCP and in the CLI's `[AGENT]` block.
+ - **A sync into a strict source on a brain without managed persistence says why it imported nothing.** The failure ledger, the summary and `--json` (`failureCodes`, plus a new `failureAdvice`) now carry `strict_requires_managed` instead of `UNKNOWN`. The advice no longer sends you to fix YAML or to use `--skip-failed`. `docs/guides/git-canonical.md` now shows how to rebuild a strict source's database from a clean clone.
+ - **The same claim held for two entities stays two facts.** Fact extraction, and the repair, treated two `memory/unattributed` rows with the same text but different `entity` cells as one duplicate, so one was dropped from the index and the repair could not apply.
+ - **Purge readers now read `memory/unattributed`'s `entity` column.** The guard that drops a failed write's stored copy of purged content, and a page purge's claim inventory, used to see that page's held rows as a malformed table and miss them.
+ - Docs: `docs/guides/repair.md#facts-home`, `docs/guides/git-canonical.md`, `docs/guides/write-refusals.md`, `docs/guides/entity-scoped-facts.md`, the `remember` section of `docs/mcp/TOOL_REFERENCE.md` and `docs/protocol/MEMORY_VERBS_v1.md`. Behaviour-change rows disclose each change after an upgrade.
+ - Tests, on PGLite and Postgres: `test/strict-background-writers-gst2492.test.ts`, `test/repair-facts-home-gst2492.test.ts`, `test/held-bare-name-move-gst2492.test.ts`, `test/sync-strict-unmanaged-gst2492.test.ts`, `test/held-fence-readers-gst2492.test.ts`, `test/facts-home-review-gst2492.test.ts` and `test/doctor-strict-facts-outside-git.test.ts`. The `entity_page_missing` assertions in `test/remember-pageless-entity-gst2446.test.ts` and `test/remember-strict-held-gst2492.test.ts` now pin `ask_user` and the held form.
+
+ ## [0.60.691.0] - 2026-11-12
+
+ **A privacy label repair on a database-only page now sticks, and a supported command stops tracking a folder's files without deleting their pages.** Pages under a folder declared `storage.db_only` in `gbrain.yml` live in the database. Some of those folders still had files Git tracked from before the declaration, and on a git-canonical source every sync put the committed file back over the database, undoing a `gbrain repair visibility` that had made the page private. Sync now keeps the database version there, a commit to such a file can no longer widen who reads the page, and `gbrain git commit-push --untrack` takes the old files out of Git safely so the problem cannot come back.
+
+ ### Itemized changes
+
+ - **Label repairs under `storage.db_only` stick.** On a strict (git-canonical) source a page whose file Git still tracks under a declared `storage.db_only` folder keeps a database change across `gbrain sync` and `gbrain sync --full`. A commit that changes the file still imports.
+ - **An import there never widens.** On every managed source, a commit to a tracked file under `storage.db_only` keeps each privacy label (`visibility`, `access`, `confidentiality`, `readable_by`) the page has and the file does not state. A label the file states applies, a wider one included, so the owner can still widen on purpose. Files outside `storage.db_only` import exactly as before.
+ - **Ignored pages take label repairs.** On a strict source, `gbrain repair visibility` on a page saved under a path Git ignores (`git_ignored`, no file) writes the label in the database instead of holding the page `canonical_file_missing`.
+ - **`gbrain git commit-push --untrack -m <msg> -- <paths>`** removes the named files from Git and the index, keeps them on disk and commits only those deletions under the commit lock; `--dry-run --untrack` previews and refuses the same way. In a managed canonical worktree it only takes files under a `storage.db_only` folder that `gbrain.yml` at HEAD declares and `.gitignore` ignores (else `untrack_not_db_only`, nothing changed), never pushes, and every page stays live with its content. A plain commit-push of a removal staged by hand with `git rm --cached` now points at `--untrack`. Guide: [untrack](docs/guides/shared-checkout-git.md#untrack).
+ - Tests: `test/db-only-labels-gst2519.test.ts`, `test/sync-classify-strict-g3.test.ts` and `test/git-commit-push-untrack-gst2519.test.ts` run on PGLite and Postgres, strict and non-strict sources.
+
+ ## [0.60.690.0] - 2026-11-12
+
+ ### Nightly checks stop failing on their own fixtures and sampling
+
+ **Three nightly checks were failing because of how they measure, not because of gbrain. All three now test what users get.** The Codex plugin check expected gated tools to be listed even when their publish gate was off. The pre-v0.18 upgrade fixture couldn't build its legacy database because a newer trigger depends on the column it removes.
+
+ - `test/e2e/codex-plugin-install-real.serial.test.ts`: the expected tool list now resolves publish gates the way `gbrain serve` does for the seeded brain over stdio. Wakeshift's `watch_job`, `list_watches` and `unwatch` (#8670) and `set_memory_writeback` (#8481) are listed only when their gate is on. Before this change the check failed every night from 2026-11-06 on; it now passes against codex 0.147.0, the version the workflow pins.
+ - `tests/heavy/fixtures/down-mutate-pre-v0.18.sql`: before dropping `pages.source_id`, the fixture drops every trigger that depends on that column. The first such trigger was the per-folder access stamp from #8134. The walk forward re-creates those triggers. `tests/heavy/pg_upgrade_matrix.sh` failed on the pre-v0.18 shape before this change and passes on both shapes after it.
+ - `scripts/bench/sync-freshness-gate.ts`: the Postgres managed serve-watch cell is now measured 3 times, and the gate uses the median of the three p50s, as the PGLite managed cell already did. The baseline and the 25% limit are unchanged. The cell's nightly p50 moves in steps of the 50 ms probe. Single runs at 656.5, 659.2 and 706.8 ms failed the 627 ms limit on 3 of 19 nightlies, and each passed when rerun on the same commit. A regression that slows every run still fails.
+ - `scripts/ci-census-tests.sh`: the pull-request census job now also runs `test/scripts/run-unit-shard.test.ts` (1.5 s, no database). It reads every test file's per-test timeouts, so a bad timeout now fails the pull request instead of a later full run.
+ - `scripts/sharding.ts`, `.github/workflows/test.yml`, `.github/workflows/e2e.yml`: the unit suite now splits into 30 shards instead of 28, run two per job (15 jobs), and the shard weights are refreshed from the median of five Test nightlies and the latest full E2E nightly. On the new weights 28 shards came to about 601 s each, over the 600 s per-shard budget; 30 shards come to about 561 s. Both coverage merges now expect shards 29 and 30.
+ - `scripts/ci-typecheck.sh`, `.github/workflows/test.yml`: when the typecheck job's tsc aborts without a type error (exit 134 or a signal, as when V8 hits the heap limit), the job deletes the restored `tsbuildinfo` and runs tsc once more from cold. A run seeded with a distant head's state could go past the heap cap where a cold run of the same tree fits, and because the aborted run saved that same state under its own head's key, every rerun failed the same way. A type error (exit 1 or 2) still fails at once with no retry, and a run whose tsc aborted or timed out no longer saves its state. `test/scripts/ci-typecheck.test.ts` pins the retry to aborts only. The macOS validation typecheck job (`.github/workflows/macos-validation.yml`) uses the same step, with two 15-minute attempts.
+ - `scripts/postgres-unit-arms.ts`, `.github/workflows/persistence-validation.yml`: the PostgreSQL arms of unit-lane suites now run in 21 shards instead of 19. On current weights the largest shard planned at 554.6 s against its 570 s budget, so the next few arm files would have failed the budget test; at 21 it plans at 502.3 s. The budget and its assertion are unchanged.
+
## [0.60.689.0] - 2026-11-12
**Three opt-in ways to share what is derived from member-restricted pages: raw-only folder rules, audience members the owner reads, and member lineage reads.** A folder rule kept the summaries, atoms, chronicle events and facts made from its pages as tightly as the pages themselves, so a transcript folder kept to one member hid every summary of those calls from everyone else; a group chat's own memory page was closed to the brain owner; and only the owner could read the derived pages and facts of pages it already reads. Each now has an operator setting, off by default, and nothing changes on upgrade: `gbrain access rule add --raw-only` keeps a folder's pages to its readers but lets whoever reads a derived page read it (use it for transcripts, never for a folder whose content is itself the secret: summaries of a raw-only page, and the facts extracted from it, are readable like any other derived page, so the facts pulled out of a fenced transcript are not fenced); `gbrain access member kind <id> audience` lets the owner read that member's own member page, versions, derived pages and facts; and `gbrain access members-read-lineage on` lets every member read the derived pages and facts of pages it reads, as the owner does. All three work the same on a repo-less brain and with rules in `access.yml`, only the operator on the brain host sets them, and no write widens.
diff --cc docs/architecture/key-files/access.md
index f68aa3086c,1c7cb22888..587efd197c
--- 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`). GBRA-108 design 1 (the labelled-only migration, `schema-migrations/v*-access-labelled-only.ts`): `access_members.labelled_only` (`labelled-only.ts` `setMemberLabelledOnly`, local only, refused on the owner with `access_labelled_only_owner` from `owner.ts`, which `setOwner` also raises) sets `CallerAccess.labelledOnly` (`caller.ts`, `actor.ts`, `as-preview.ts`; fails closed to true when the table cannot be read). `private-visibility.ts` `labelledOnlySql` ANDs `page_readers && identity OR folder_rule_ids && satisfied` into `callerAccessSql`, `callerReadersAllowedSql` (a snapshot needs its own readers or a rule on the live page) and the fact filters (`labelledOnlyFactSql`: a fact on the caller's own member page while it names the member, or under member lineage a provenance page that passes; else FALSE); under member lineage a derived row may pass through `gbrain_access_origin_labelled_for()` (every origin labelled, none missing). Remote read gates that are not caller-aware use `remoteReadFloorSql` / `remoteProvenanceFloorSql` (the plain fragment, plus the labelled-only conjunct only for a labelled-only caller); `test/remote-read-floor.test.ts` lists the sites that keep the plain fragment. `labelledOnlyFor` never reports the configured owner, and dispatch refuses a scope read for a labelled-only person (`scope-read.ts` `scopeReadLabelledOnlyRefused`). The entity page of a fact is judged by the ordinary policy. Writes: `persistence/page-visibility.ts` (`writerReadPolicySql`, `remoteLabelsChecked` → `assertLabelledOnlyCreate` → `access_labelled_only_unnamed`), `cli/enforced-member.ts` `memberPageView`. Cache keys `xlo=1`, `labelled_only`; doctor `access_labelled_only_members` (`checks/access-labelled-only.ts`). Test: `test/access-labelled-only.test.ts` (both engines, both stores). A derivative of a page that names readers is otherwise hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v299; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. GST-2346 D1: the owner speaking for itself (`ownerSpeaksForItself`: `CallerAccess.owner`, no actor or audience, no subagent, no slug fence) takes the world route unless it passes `visibility: "private"` or the page or `facts.default_visibility` makes the default private (then its member page), is never refused `member_share_required`, and its `forget` of a fact off its member page takes the ordinary remote path when that path reads the fact. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`) on the stored actor, else the stored audience, and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member) and `grant.actingFor` (the same distinct audience entries; `jobActorSql` in `minions/types.ts`), so a job or receipt with an actor or audience reads as missing to the bare client and to other actors and audiences, and one with neither to every actor and audience. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).
-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `serve --stdio-member`, else `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). GST-2490: an owner read (`CallerAccess.lineage` with `owner`, read-only ops only) uses `lineageAccessSql`: the owner's readers and folder rules as for any member, with `gbrain_access_origin_hidden_for()` (v304; per origin `gbrain_access_origin_closed_for()`) in place of the every-caller lineage, so a derivative or fact passes when the owner reads every origin; `ownerReadsRestricted` (config `access.owner_reads_restricted`, `owner.ts` `setOwnerReadsRestricted`, local only) also passes pages kept to other members except another member's own member page and pending coverage. `access check`, `who-can-read`, `whoami` (`ownerReadsRestrictedNotice`) and doctor `access_owner_reads_restricted` report it; test `test/owner-reads-restricted.test.ts` (both engines, database and access.yml rules). GBRA-108 (migration v305, `v305-access-lineage-designs.ts`): `access_rules.covers_derived` (default true) — a raw-only rule (`folder-rules.ts` `covers_derived: false`, `rule add --raw-only`; digest unchanged for covering rules; true→false is the held widening `derived_released`, false→true the narrowing `derived_covered`) is dropped from an origin's rule set by the SQL function `gbrain_access_lineage_rules()` inside `gbrain_access_origin_restricted()` and the 10-argument `gbrain_access_origin_closed_for()`, so it keeps its pages but not their lineage (a page's own readers still close it; fact provenance filters judge with `derived = true`). `access_members.kind` (`person` | `audience`, `members.ts` `setMemberKind`, local only): an owner read carries `CallerAccess.audienceKindMembers`, whose member pages pass the readers test and the member-page exemptions (`audiencePages`, `notOtherMemberPageSql`, the `p_audience_pages` argument of the 9-argument `gbrain_access_origin_hidden_for()`). Config `access.members_read_lineage` (`lineage.ts`, local only) sets `CallerAccess.lineage` for any member read speaking for itself (`caller.ts`; never an audience of several or an unbound credential; `withCallerAccess` drops it for several identities and keeps the owner opt-in and audience members owner-only). Cache keys: `knobsHash` `xol=3` and `xak=`, `callerIdentityKey` `owner_reads`/`audience_kind`. Doctor `access_lineage` (`checks/access-lineage.ts`). Tests: `test/access-raw-only-rules.test.ts`, `test/access-audience-members.test.ts`, `test/access-members-read-lineage.test.ts` (both engines, both stores; fixture `test/helpers/access-lineage-fixture.ts`). A derivative of a page that names readers is otherwise hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit (GST-2331: every read under `HARDENED_GIT_ARGS` and `NO_LAZY_FETCH_ENV`, so a partial clone fetches nothing; a policy file the commit names that the clone lacks, or a history the replay cannot read, makes the source read as nobody until the objects are fetched: the problem names the exact `git cat-file -p` or `git log --first-parent -p` that fetches them, and the next sync applies the rules and clears the mark); a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v298, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v299; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`, and since GST-2249 W1 every page write; `test/qm-attest-write-boundary.test.ts` classifies every attestable mutating operation) are never attestable: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v301, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`, unless the call passes `share: true` (GST-2243), which takes the ordinary world route to the subject's page; a member's explicit `visibility: "world"` is refused in `remember`'s validation (`member_share_required`), so a batch with one such item saves nothing. 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/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/facts/single-prepare.ts
index 18d86cb8bb,eb543db4c5..425f1a5db5
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@@ -7,10 -7,14 +7,14 @@@ import { assertFactNotPurged } from './
import { cosineVerdict } from './capture-dedup.ts';
import { interleaveFusion } from '../search/fusion-lists.ts';
import { readSupersessionThreshold } from './supersession-threshold.ts';
- import { remoteProvenanceFloorSql } from '../search/private-visibility.ts';
-import { ownerReadPolicyFragment, privateProvenanceFilterFragment, readPolicyFragment } from '../search/private-visibility.ts';
++import { ownerReadPolicyFragment, readPolicyFragment, remoteProvenanceFloorSql } from '../search/private-visibility.ts';
+ import { folderAccessForAll } from '../access/caller.ts';
+ import { memberIdentity } from '../access/members.ts';
+ import { ownerMemberId } from '../access/owner.ts';
+ import { MEMBER_PAGE_PREFIX } from '../access/principals.ts';
import { pageNotVisibleError } from '../persistence/page-visibility.ts';
import { slugUnderBoundPrefixes } from '../ops/context.ts';
- import { ownedPageWithdrawalSubject, onOwnedMemoryPageSql, withdrawalCoversFactSql } from '../access/member-facts.ts';
+ import { ownedPageWithdrawalSubject, onOwnedMemoryPageSql, withdrawalCoversFactSql, withdrawalReachedFactSql } from '../access/member-facts.ts';
import { UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';
import { sameClaimSlot } from './typed-claim.ts';
diff --cc src/core/persistence/forget-prepare.ts
index eb2999778a,183f0c7cf4..d3f6fb456d
--- a/src/core/persistence/forget-prepare.ts
+++ b/src/core/persistence/forget-prepare.ts
@@@ -21,7 -21,8 +21,8 @@@ import { serializePageToMarkdown } fro
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { planFactWithdrawal, recordFactWithdrawal } from '../facts/withdrawal.ts';
import { rebuildPendingPageProjections } from '../page-state/projections.ts';
- import { remoteProvenanceFloorSql, resolveExcludePrivatePages } from '../search/private-visibility.ts';
-import { ownerReadPolicyFragment, privateProvenanceFilterFragment, readPolicyFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
++import { ownerReadPolicyFragment, readPolicyFragment, remoteProvenanceFloorSql, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+ import { folderAccessForAll, memberIdentityFor } from '../access/caller.ts';
import { remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';
import { materializedPage } from './segmented-apply.ts';
import { prepareFileTarget, snapshotLedger, unreadPageFile } from './page-prepare.ts';
diff --cc src/core/schema-migrations/latest.generated.ts
index 70b544043e,66e025f253..1a22223036
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@@ -4,4 -4,4 +4,4 @@@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
- export const LATEST_SCHEMA_VERSION = 306;
-export const LATEST_SCHEMA_VERSION = 307;
++export const LATEST_SCHEMA_VERSION = 308;
diff --cc src/core/schema-migrations/registry.generated.ts
index 5081de84b8,154782fc2d..e87c5410a2
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -306,7 -306,8 +306,9 @@@ import { v302 } from './v302-link-trans
import { v303 } from './v303-access-page-rules.ts';
import { v304 } from './v304-access-owner-origin.ts';
import { v305 } from './v305-access-lineage-designs.ts';
- import { v306 } from './v306-access-labelled-only.ts';
+ import { v306 } from './v306-member-page-withdrawal-scope.ts';
+ import { v307 } from './v307-page-label-guards.ts';
++import { v308 } from './v308-access-labelled-only.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -612,4 -613,5 +614,6 @@@ export const MIGRATIONS: Migration[] =
v304,
v305,
v306,
+ v307,
++ v308,
];
diff --cc src/core/schema-migrations/v308-access-labelled-only.ts
index 9610a45255,0000000000..a21c72ae84
mode 100644,000000..100644
--- a/src/core/schema-migrations/v308-access-labelled-only.ts
+++ b/src/core/schema-migrations/v308-access-labelled-only.ts
@@@ -1,76 -1,0 +1,76 @@@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GBRA-108 design 1, the labelled-only grant (operator-set, off on upgrade):
+//
+// access_members.labelled_only (default false). A credential bound to a member that carries it reads only pages that
+// name that member: its id or one of its groups in readable_by, or a folder or page rule listing it
+// (search/private-visibility.ts labelledOnlySql). It lives on the member, so every token, OAuth client and stdio binding
+// of that member inherits it and no second credential can forget it.
+//
+// gbrain_access_origin_labelled_for(page, identity, satisfied rules) is the lineage arm: under
+// access.members_read_lineage a derived page with no label of its own passes only when it has an origin and every
+// origin names the caller. The origins are v305's (an atom's source page, a synthesized concept's or question's inputs,
+// an input atom's own origin, a Life Chronicle event's meeting, a declared derived_from page; aliases and renames
+// followed). No origin found, a declared derived_from that resolves to nothing, or one origin that names someone else
+// returns false (fail closed). The ordinary lineage rule (gbrain_access_origin_hidden_for) still applies on top.
+//
+// Nothing is rewritten: every member keeps labelled_only false, so every read is unchanged. No schema.sql mirror: like
+// v283, v285, v304 and v305, these exist only through migrations. Provisional number: renumbered at the merge slot.
+const LABELLED = (o: string) => `(COALESCE(${o}.page_readers && p_identity, false) OR COALESCE(${o}.folder_rule_ids && p_satisfied, false))`;
+const RESOLVED = (source: string, slug: string) => `SELECT ${slug} UNION SELECT a.canonical_slug FROM slug_aliases a WHERE a.source_id = ${source} AND a.alias_slug = ${slug}
+ UNION SELECT h.new_slug FROM slug_rename_history h WHERE h.source_id = ${source} AND h.old_slug = ${slug}`;
+const DECLARED = `jsonb_array_elements_text(CASE WHEN jsonb_typeof(fm->'derived_from') = 'array' THEN fm->'derived_from' ELSE jsonb_build_array(fm->'derived_from') END)`;
+
- export const v306: Migration = {
- version: 306,
++export const v308: Migration = {
++ version: 308,
+ name: 'access_labelled_only',
+ idempotent: true,
+ sql: `
+ALTER TABLE access_members ADD COLUMN IF NOT EXISTS labelled_only BOOLEAN NOT NULL DEFAULT false;
+CREATE OR REPLACE FUNCTION gbrain_access_origin_labelled_for(p_id INTEGER, p_source_id TEXT, p_type TEXT, fm JSONB,
+ p_identity TEXT[], p_satisfied TEXT[]) RETURNS boolean
+ LANGUAGE plpgsql STABLE PARALLEL SAFE SET search_path = pg_catalog, public, pg_temp AS $fn$
+DECLARE
+ found boolean := false;
+BEGIN
+ IF p_type = 'atom' THEN
+ IF NOT EXISTS (SELECT 1 FROM pages o WHERE o.source_id = p_source_id AND o.slug IN (${RESOLVED('p_source_id', "fm->>'source_slug'")}))
+ OR EXISTS (SELECT 1 FROM pages o WHERE o.source_id = p_source_id AND o.slug IN (${RESOLVED('p_source_id', "fm->>'source_slug'")}) AND NOT ${LABELLED('o')}) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ ELSIF p_type = 'question' OR (p_type = 'concept' AND fm->>'synthesized_by' IS NOT NULL) THEN
+ IF NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p_id AND l.link_source = 'concept-provenance' AND l.link_type = 'synthesized_from')
+ OR EXISTS (SELECT 1 FROM links l JOIN pages i ON i.id = l.to_page_id
+ WHERE l.from_page_id = p_id AND l.link_source = 'concept-provenance' AND l.link_type = 'synthesized_from'
+ AND NOT ${LABELLED('i')}
+ AND NOT (i.type = 'atom'
+ AND EXISTS (SELECT 1 FROM pages io WHERE io.source_id = i.source_id AND io.slug IN (${RESOLVED('i.source_id', "i.frontmatter->>'source_slug'")}))
+ AND NOT EXISTS (SELECT 1 FROM pages io WHERE io.source_id = i.source_id AND io.slug IN (${RESOLVED('i.source_id', "i.frontmatter->>'source_slug'")}) AND NOT ${LABELLED('io')}))) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ ELSIF p_type = 'event' AND fm->>'captured_via' LIKE 'life-chronicle:%' THEN
+ IF NOT EXISTS (SELECT 1 FROM pages c WHERE c.source_id = p_source_id AND c.slug IN (${RESOLVED('p_source_id', "fm->'event'->>'depth'")}))
+ OR EXISTS (SELECT 1 FROM pages c WHERE c.source_id = p_source_id AND c.slug IN (${RESOLVED('p_source_id', "fm->'event'->>'depth'")}) AND NOT ${LABELLED('c')}) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ END IF;
+ IF jsonb_typeof(fm->'derived_from') IN ('array', 'string') THEN
+ IF NOT EXISTS (SELECT 1 FROM ${DECLARED})
+ OR EXISTS (SELECT 1 FROM (SELECT regexp_replace(x, '\\.md$', '') AS slug FROM ${DECLARED} AS x) declared
+ WHERE NOT EXISTS (SELECT 1 FROM pages d WHERE d.source_id = p_source_id AND d.slug IN (${RESOLVED('p_source_id', 'declared.slug')}))
+ OR EXISTS (SELECT 1 FROM pages d WHERE d.source_id = p_source_id AND d.slug IN (${RESOLVED('p_source_id', 'declared.slug')}) AND NOT ${LABELLED('d')})) THEN
+ RETURN false;
+ END IF;
+ found := true;
+ END IF;
+ RETURN found;
+END
+$fn$;
+`,
+};