Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/capy/attested-reads-that-name' into g1-wave-2-personal
garrytan7f1ffb73ba97
diff --cc CHANGELOG.mdindex cb6f83b155,c0dd44ac98..531c1dd1ed--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,10 -10,8 +10,10 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).- ## [Unreleased]+ ## [0.60.595.0] - 2026-11-06- **An attested person can now read their own DM and member sources through a shared QM client, and nobody else's.** Until now an attested client read only its credential's grant, usually the default source, so facts ingested into a member's own source were never recalled; granting every DM source to the client would have let every attested person read every other person's DM. `gbrain access member source add <member> <source>` now binds a source to the member it belongs to, and a bound source is personal: an attested call (`x-qm-actor`) reads its credential's grant minus every personal source bound to someone else, and a scope read (an attested read that names `source_id` or `source_ids` without `--attest-read person`) reads no personal source at all, not even the speaker's own. A personal source that is hidden is refused exactly like a source outside the grant (`permission_denied`, same message), and an unnamed read simply skips it. The rule only hides inside each credential's grant, so it never makes a source readable: add the DM sources to the client's `federated_read` and bind each to its member. It applies once in MCP dispatch (and to the tool calls of an agent job submitted for an attested person), so `memory_recall`, `query`, `search`, `get_page` and every other read inherit it. Unattested calls and member-bound credentials are unchanged, and nothing changes on upgrade until an operator binds a source. `gbrain access member source remove` previews first and says when the source would stop being personal; `list` shows the bindings. Database state (migration v291), so a repo-less brain works the same. `v1.json` and `v2.json` are unchanged.++**An attested person can now read their own DM and member sources through a shared QM client, and nobody else's.** Until now an attested client read only its credential's grant, usually the default source, so facts ingested into a member's own source were never recalled; granting every DM source to the client would have let every attested person read every other person's DM. `gbrain access member source add <member> <source>` now binds a source to the member it belongs to, and a bound source is personal: an attested call (`x-qm-actor`) reads its credential's grant minus every personal source bound to someone else, and a scope read (an attested read that names `source_id` or `source_ids` without `--attest-read person`) reads no personal source at all, not even the speaker's own. A personal source that is hidden is refused exactly like a source outside the grant (`permission_denied`, same message), and an unnamed read simply skips it. The rule only hides inside each credential's grant, so it never makes a source readable: add the DM sources to the client's `federated_read` and bind each to its member. It applies once in MCP dispatch (and to the tool calls of an agent job submitted for an attested person), so `memory_recall`, `query`, `search`, `get_page` and every other read inherit it. Unattested calls and member-bound credentials are unchanged, and nothing changes on upgrade until an operator binds a source. `gbrain access member source remove` previews first and says when the source would stop being personal; `list` shows the bindings. Database state (migration v295), so a repo-less brain works the same. `v1.json` and `v2.json` are unchanged.+**An attested read that names its sources now reads as those sources' audience for every read QM can list, and an operator can say whether a credential serves rooms or one person's own turns.** `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` and `query`, called with `x-qm-actor` and `source_id` or `source_ids`, now read the way `memory_recall` does: the person's restricted pages and their member page read as missing, a source outside the grant is refused, and `__all__` or `all_sources` is refused, so a shared turn can never pull one member's private pages into a channel. `get_timeline` gains `source_id` and `source_ids`, and `find_experts` and `volunteer_context` gain `source_ids`; `volunteer_context` refuses `stats: true` under that read. `gbrain auth rescope --attest-read person|scope|none` sets how a credential reads named sources: `person` narrows to them but reads as the person (for a DM client), and `scope` keeps the audience read and also refuses any call that names no person (`actor_not_attested`, reason `actor_required`). Unset keeps today's behavior, so no existing client changes. `gbrain doctor` warns (`attest_read_shared_scope`) when a person credential reads a source another attest credential reads as the scope. `context_pack` is not covered yet. `v1.json` and `v2.json` are unchanged; on a repo-less brain all of it is database state and works the same.**An attested call can no longer write pages directly: `add_timeline_entry`, `add_link`, `put_page` and `edit_page` are not attestable.** They write to pages that everyone who reads the page sees, so a trusted system acting as one person could put that person's words in front of a whole audience with no one approving them. They now wait for owner-approved proposals, the way `capture` and take writes already do. An operator whose `--attest-ops` list names one of them sees `gbrain auth rescope` refuse the list, and each attested call to it is refused (`actor_not_attested`, reason `op_not_attested`); a queued attested write of one fails when it publishes. Unattested calls, and credentials bound to a member, are unchanged. `v2.json` lists the new deferred operations; `v1.json` is unchanged.@@@ -32,6 -30,134 +32,134 @@@QM clients that read v1 keep working unchanged. A shared-scope turn should name its sources and read the v2 contract.+ **QM can now save a shared scope's memory (a project, channel or team) as well as each person's, and nothing else can read that scope.** `memory_write` gains `source_id`: named, the facts go to that scope source's `memory/scope` page, world-readable inside the source, still attested to the person who said them. The operator lists the scope sources on the QM credential with `gbrain auth rescope --attest-sources`, which marks each one a scope source for good. A scope source is never federated and never joins another credential's read grant, so its memory is read only by naming it from the scope credential, and a person read never sees it.++ | Situation | Before | Now |+ |---|---|---|+ | `memory_write` with `source_id` | refused (`unknown_param`) | saves on `memory/scope` in that source when the credential lists it in `--attest-sources`; otherwise `permission_denied` reason `source_not_attested`; the credential's own write source is `invalid_params` reason `source_is_member_source` |+ | `gbrain auth rescope --attest-sources a,b\|none` | no such flag | lists the scope sources; refuses `default`, a federated source, the own write source, a source another credential reads, ops beyond the memory tools and the private-pages grant |+ | A grant, token or registration that reads a scope source | n/a | refused (`QM scope source`), also after the scope credential is revoked |+ | `sources federate` / `sources restore` on a scope source | federates | refused / restored unfederated; a federated flag on a scope source is ignored |+ | Remote write to `memory/scope` (put_page, remember, delete_page, tags, links, timeline) | allowed like any page | refused unless it is a scope `memory_write` |+ | `memory_recall` without sources from a credential that reads a scope source | n/a | never reads the scope source |++ **A long recall question that opens with an instruction preamble finds the facts its last message asks about on a keyword-only brain, and refusals say what they need.** Recall used to score a question on its first 12 content words, so a provider preamble filled all 12 and nothing cleared the admission floor.++ | Situation | Before | Now |+ |---|---|---|+ | `recall` `question` over 12 content words | scored on its first 12 | searched on its last 24, scored on the 12 of those the fewest candidate facts hold; shorter questions unchanged |+ | Candidates found, none above the admission floor | empty `facts`, nothing else | empty `facts` plus `facts_below_floor: <n>` (absent when nothing matched) |+ | `recall` `question` over 2,000 characters | bare `invalid_params` | `invalid_params` reason `question_too_long`, detail `max_chars=2000 received_chars=<n>`; never cut |+ | `acting_user` refused `argument_without_attestation` | no detail | detail `missing=x-qm-actor`, `missing=attest_right` or both, also in `structuredContent.error` |++ ## [0.60.594.0] - 2026-11-06++ **A page write that reaches a checkout while `gbrain sources refresh` runs can now wait for the refresh instead of being refused, and every commit gbrain makes is recorded, so doctor can name commits made outside it.** The write barrier is off by default (`persistence.refresh_barrier`). With it on, a single page write that arrives while a refresh drains or merges the checkout is journaled and answered pending at once: MCP gets `isError: false` with `status: "pending"`, and the CLI exits 10 with the command that polls it, on the owner socket and on a thin client alike. The write commits after the refresh. It ends `revision_conflict` with nothing applied when the refresh changed its file, and `refresh_barrier_expired` when the refresh outlives `persistence.refresh_barrier_max_wait_ms` (15 minutes), even on an owner with nothing else to do. The commit ledger and doctor's new `foreign_writers` check run on every brain with a Git checkout. The owner-path guard installs only when you run `gbrain sources guard --install`.++ ### Itemized changes++ - Refresh write barrier (`src/core/persistence/refresh-barrier.ts`, journal admission and claim, the consumer): requests gain a `deferred` state tied to the refresh they wait behind. Only a claim that declares the barrier can move a deferred row, and only after its refresh is released. A released write replays its change check against the refresh's diff, so a blind write never overwrites a file the refresh changed. Syncs, jobs and batches keep the `worktree_refreshing` refusal, and a live consumer that cannot drain deferred rows keeps it too. Restore, cancel, token revocation and source lifecycle changes end a deferred write with nothing applied and release its counters. Schema migration v292 adds the columns, the release trigger and an online partial index over the four open request states, so receipt polls stay index-served on a long receipt history.+ - `gbrain upgrade --check-downgrade` exits 3 `downgrade_blocked_deferred_writes` while deferred writes wait. `gbrain sources writer status` lists them.+ - Commit ledger (`src/core/git/commit-ledger.ts`): every gbrain commit site appends one line to `<git common dir>/gbrain/commit-ledger.jsonl`, rotated at 4 MiB. A failed append never fails the commit.+ - New doctor check `foreign_writers`: a commit in a source checkout on this host that the ledger does not name fails the check with the newest such commit and a fix that asks who makes it. Unconfirmed commits and page files uncommitted for over 30 minutes warn. Its git reads take no optional locks, so a doctor run never holds `index.lock` against a commit. A repo-less brain reports not_applicable.+ - New `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]`: the commit guard on a managed source's worktree, from its owner host, in a hooks directory private to that worktree. gbrain's own hooks at the old hooks path, the brain-durability post-commit hook included, are copied along, so installing it never turns Git durability off. `--mode enforce` also refuses cherry-pick, revert, rebase and sequencer commits.+ - `gbrain git commit-push --base <path>=<blob>|absent` refuses `commit_base_moved`, committing nothing, when the file at HEAD is no longer the blob the caller read. It also refuses `checkout_not_a_source` when a managed brain's command resolved a checkout from the working directory that is none of its sources (#8662).+ - `gbrain repair file-drift` with `--held`, `--side`, `--state`, `--cursor` or `--provenance` and no `--prefer` refuses with the usage line instead of running the all-drifted survey (#8615).+ - A `gbrain sources refresh` run refused `refresh_source_changed` by a moving HEAD or late work retries once from a fresh precheck in the same run (#8617).+ - Tests on PGLite and Postgres: `test/refresh-write-barrier.test.ts` (every deferred outcome, including edit_page, forget and source lifecycle changes, the idle-owner expiry and the owner-socket exit 10), `test/commit-ledger.test.ts`, `test/doctor-foreign-writers.test.ts`, `test/sources-guard.test.ts`, `test/mcp-client.test.ts` (a thin client's pending deferred write) and the state audit in `test/refresh-barrier-state-audit.test.ts`. Design note: docs/designs/REFRESH_WRITE_BARRIER.md.++ ## [0.60.593.0] - 2026-11-06++ **`gbrain repair failed-writes` now previews a brain with a large write journal in about a second instead of timing out.** On Postgres, the preview of refused writes read the request table once per refused write, and one of those reads walked the table from that write to its end. With hundreds of refused writes and a journal of over a million requests, the preview ran for minutes and the server's statement timeout ended it with a bare `internal_error`, so the operator had no way to see or recover the lost writes. The preview now classes refused writes together in set reads, each sized so it stays short even on a page with hundreds of refused writes and a long history. On a synthetic journal of 1.5 million requests with over 800 refused writes it took about a second (it took 265 seconds before), with the same classes and the same preview hash. When a preview read does still run past the timeout, it refuses `repair_preview_timeout` with a fix instead of `internal_error`, and nothing is saved.++ ### Itemized changes++ - `src/core/repair/failed-writes.ts`: recovered fact requests are read once for all refused writes instead of inside the candidate read; replay attempts are read for every refused write together (`request_id = ANY`); the later requests of each refused write's page are read for groups of writes sized by how long their pages' later history is, so one page with hundreds of refused writes and a long history cannot make one read outlast the statement timeout; the file check runs once per page. The listing, classes, residuals and preview hash are unchanged.+ - New refusal `repair_preview_timeout`. When the request indexes the preview reads are missing or INVALID, it names them and its fix is the read-only `gbrain repair request-indexes --json` preview, whose apply command builds them; when they are valid, it tells the brain host to run the same preview once with a longer statement timeout.-- Schema migration v291 builds two request-table indexes online (`persistence_requests_replay_id` on the request id, `persistence_requests_slug_sequence` on source, slug and sequence). They join the indexes `gbrain repair request-indexes` and doctor's `persistence_request_indexes` check report. Without them the preview is still bounded, only slower. PGLite and repo-less brains get them unchanged.++- Schema migration v295 builds two request-table indexes online (`persistence_requests_replay_id` on the request id, `persistence_requests_slug_sequence` on source, slug and sequence). They join the indexes `gbrain repair request-indexes` and doctor's `persistence_request_indexes` check report. Without them the preview is still bounded, only slower. PGLite and repo-less brains get them unchanged.+ - The request-index states doctor and `gbrain repair request-indexes` print now come back in the order the indexes are declared on Postgres as well as PGLite.+ - `test/repair-failed-writes-bounded-8707.test.ts` (PGLite and Postgres) seeds a journal with refused writes of every class and checks that the preview's request-table reads stay flat as refused writes grow, that each write gets its class, and that a read ended at the statement timeout refuses `repair_preview_timeout` and saves nothing, and (Postgres) that 500 refused writes on one page followed by 20,000 later commits preview inside a 1 s statement timeout.++ ## [0.60.592.0] - 2026-11-06++ **On a page with no import record, converting a source to git-canonical, `sources git-gap` and `repair rows-behind` now pick the winner from content evidence, never from a timestamp, and nothing overwrites a page that changed after it was reviewed.**++ A page whose database copy differs from its committed file and that has no import record used to count as database-ahead. Converting a source to git-canonical then adopted it, so a plain Git edit of that page could be lost. Now its archived versions are compared with the blobs its path held in Git. An older version that equals the committed file means the database moved, so it is adopted. A page that equals an older committed blob means the file moved, so Git wins. A page where both sides moved, or where nothing is shared, waits for the owner's decision. A revert on either side counts as a move, and a history that was capped or pruned gives no verdict. The owner reviews a list, decides each page in a decisions file, or approves the whole plan once. Either way, only pages unchanged since the review apply.++ ### Itemized changes++ - `src/core/persistence/git-gap.ts`: one direction classifier (`adopt_db_moved`, `git_wins_file_moved`, `both_moved`, `no_evidence`) reads each page's newest 32 versions and 32 blobs from one scoped history walk run from the Git top level. Renames are followed, version bodies are read under a byte budget, and a segmented page or a version with no comparable content gives no one-sided verdict. `sources git-gap` reports `direction_evidence`.+ - `gbrain sources canonical <id> --to git`: each page is placed by its evidence kind, and the kind is bound into the preview hash. `both_moved` and `no_evidence` are new discards (`no_record_both_moved`, `no_record_no_evidence`). `--list-out <file>` writes the review list, `--decisions <file>` applies the owner's decisions, and `--approval-out` / `--approved` apply an approval across time. Only items unchanged since the approval apply, and the rest comes back as `git_conversion_delta` with counts. These files are written 0600 and refused inside a source checkout or the Git working tree that holds it (`conversion_file_in_source_root`).+ - The conversion's strict passes may replace a database version only where the plan approved it. A page that changes during the apply is held instead of overwritten, the apply stops with `changed_since_preview`, and the source stays mixed. A failed apply reports `recovery` (mode, commits, push, writes and the non-destructive rollback).+ - `gbrain repair rows-behind` never re-imports a row with no import record whose database moved since (`excluded:database_moved`). `--include-ambiguous` also no longer re-imports a row with no import record where both the page and its file moved. Such a row is listed `excluded:both_moved`, and `gbrain repair file-drift` decides it.+ - `sources git-gap` and doctor `db_ahead_of_git` report each source's `live_pages`. A scan the time budget stopped reads `PARTIAL, <read> of <live> live page(s) read`.+ - The hardened git runner accepts a second `log` shape for the history walk and bare `cat-file --batch-check`; every other form still refuses.+ - Tests: `test/git-gap-direction-evidence-d4.test.ts`, `test/git-canonical-conversion-evidence-d4.test.ts` and `test/rows-behind-checkpoint-8071.test.ts` run on PGLite and Postgres. Guides: docs/guides/git-canonical.md and docs/guides/repair.md.++ ## [0.60.591.0] - 2026-11-06++ **`gbrain repair file-drift --prefer file` now imports a page stored in segments that keeps protected parts, instead of refusing every apply with no next step.**++ A held page whose body is stored in segments (`pages.segmented_storage`, a page over 1 MiB) and whose database copy keeps a protected frontmatter key and a timeline row the file lacks previewed cleanly, listing both exceptions and an apply command. That apply refused every time with `invalid_params` "Unsupported or missing reconciliation fields." and no `fix`, so the page stayed held and blocked writes to it. The apply now imports the file with the same protections (the file keeps its bytes plus the appended key and row, the page keeps both), the page stays segmented and searchable, and the next sync releases the hold. A preview now refuses a page its own apply would refuse, and every refusal on this path names its next step.++ ### Itemized changes++ - `src/core/persistence/reconcile-state.ts`: a reconcile preview of a segmented page validates: its snapshot's `bodyGeneration` and the page's `body_storage` / `body_bytes` are accepted (the preimage checks are unchanged). A page with no revision yet (the revision backfill has not reached it) refuses `revision_backfill_pending` in the preview, with `gbrain apply-migrations --force-schema` in `fix` (or `gbrain repair orphan-children` when the backfill already used every attempt on the row), instead of a stale-preview refusal with none; `revision_backfill_pending` joins the error registry. Read-only drift classification and the audit read such a page as before.+ - `src/core/persistence/reconcile-prepare.ts`: the reconcile publication of a segmented page leaves its text seal to the segmented import (as the managed file repair does), runs the import's `afterCommit`, and reads the published page back materialized.+ - `src/core/repair/file-drift.ts`: the preview validates each page's reconcile artifact as the apply reads it back, so a page the apply would refuse is listed `refused` in the preview. A refused preview row carries the refusal's `fix` and its `why`; a refused or changed apply outcome carries both, with a read-only preview of that page alone (for a held deleted-side page, its held preview) when the refusal has no `fix`. `gbrain repair` prints each row's `fix` with its consent.+ - `src/core/persistence/reconcile-merge.ts`: "Unsupported or missing reconciliation fields." names the fields in `why`.++ ## [0.60.590.0] - 2026-11-06++ **A managed sync no longer stops for good when a write queues behind another write that waits on the sync, and the convergence nightly's kill loop tests only points a sync actually reaches.**++ A write queued behind an earlier write that waited on a sync row naming its page used to count as a write that could go first. That held back the very sync row the earlier write waited on, so the three rows waited on each other and nothing committed until the drain gave up, about an hour into the nightly run. The claim now skips such a write, so the sync row commits and both writes follow in order. The live `stalled Ns on queued` line also stops reporting a stall while the head keeps moving, for example while this process commits the in-flight writes of a serve that was killed.++ ### Itemized changes++ - `src/core/persistence/journal.ts`: the FIFO claim no longer counts a write that sits behind an earlier queued write waiting on a sync row naming its page. That write can't go first anyway, because a write never passes an earlier one.+ - `src/core/persistence/sync-drain.ts`: the in-pass stall line counts an unclaimed head's age from when that head became the head, and never from before the drain's own last commit.+ - `src/core/persistence/sync-run.ts` and `fault-points.ts`: a new `sync:passed_over` fault point after the cursor step that passes over an entry whose file changed after admission. It does nothing without a test hook.+ - `test/sync-convergence.serial.test.ts`: the kill loop drops `sync:prescreened` and `sync:retry_deferred`, which only company sources reach since #6712 PR 4b, and kills at `sync:passed_over` and `sync:batch_entries` instead. A primed edit that the round's sync never froze is now reported by the "every planned fault fired" check, where it used to crash the harness on an empty commit.+ - `test/claim-fifo-foreground-waiting.test.ts` covers the chained write on PGLite and Postgres, and `test/sync-drain-claims.test.ts` covers a head that keeps moving.++ ## [0.60.589.0] - 2026-11-06++ **gbrain can now wake an agent's conversation when a job it started finishes, through Wakeshift. It's off until the brain owner turns it on.**++ An agent that submits a long job no longer has to poll. With reporting back on, it calls `watch_job` with the job id and ends its turn. When the job completes, fails, dies or is cancelled, Wakeshift wakes that conversation with one line naming the job and the `get_job` call that reads the result. The wake is a pointer (the job id, kind, status and times), never page text, titles or slugs, so it can't widen what anyone reads. The owner turns it on with `gbrain wakeshift enable` on the brain host, using a key from their own Wakeshift app, and `gbrain wakeshift disable` turns it off at once. Until then nothing changes: the tools aren't listed, no rows are written and nothing is sent. This release reports back only on brains that serve their owner alone. `wait_job` and `gbrain jobs wait <id>` remain the way to wait with nothing leaving the machine. Guide: docs/guides/wakeshift.md.++ ### Itemized changes++ - New MCP tools `watch_job`, `list_watches` and `unwatch`, listed only while reporting back is on and a usable key is on the host. `watch_job` runs the same owner check as `get_job`: a job the caller doesn't own reads like a missing one and nothing is sent. A watch belongs to the credential that made it, and a revoked credential's watch ends without a wake.+ - New `gbrain wakeshift enable | disable | status | test`. `enable` asks consent (it sends data off the machine and stores a credential), refuses a brain with live access members, checks the key with Wakeshift and publishes gbrain's `gbrain.job.finished` event. The key comes from `WAKESHIFT_API_KEY` or a 0600 `~/.gbrain/wakeshift.key`, and is never stored in the database or printed (status shows its fingerprint).+ - Delivery runs inside `gbrain serve` (stdio and HTTP) and the job worker every 5 seconds, and once more at the end of `gbrain jobs work`. A watch on a job that already finished wakes at once. A failed delivery is retried at most 5 times over about 40 minutes, then the watch ends and the conversation is told. Jobs are never slowed by Wakeshift.+ - New doctor check `wakeshift`: a key file other users can read, reporting back enabled without a usable key, and watches that died or were refused as `id_reused` in the last 7 days.+ - Schema migration v294 adds `wake_subscriptions` (empty unless reporting back is on). Repo-less brains get it unchanged.+ - `--log-full-params` on `gbrain serve --http` now redacts a tool call's `session_key` argument.++ ## [0.60.588.0] - 2026-11-06++ **Engines that make their first write at the same moment no longer fail one of the writes registering the same writer.** Two or more engines opened from the same settings on one Postgres database (the same writer id, credential and lane), or two processes that share one credential file, could both find no registration and both insert it. The loser hit the credential's unique index and failed with `duplicate key value violates unique constraint "persistence_local_writers_credential_hash_key"`; four engines on a fresh database lost three of their four first writes. Registration is now idempotent under that race, and every refusal still holds. PGLite was never affected, because its single connection runs the read and the insert one after the other. Contributed by @bradgessler.++ ### Itemized changes++ - `src/core/persistence/identity.ts`: the registration insert names no conflict target, so a conflict on either unique index (the id or the credential hash) does nothing. When nothing was inserted, the row under the id is read again and checked exactly as an existing row is. The same credential and lane pass, while a revoked row or another credential or lane under the id refuses `permission_denied`. No row under the id means the credential belongs to another registration, which now refuses `permission_denied` with a fix where it used to raise a raw 23505.+ - `test/e2e/engine-open-postgres.test.ts`: four engines opened from one writer value make their first writes at once, twelve rounds on a scratch database (master: `['23505','resolved','resolved','resolved']`). A second case forces the lost-insert branch and checks each refusal on Postgres.+ - `test/engine-open.test.ts`: the same lost-insert cases on PGLite, plus four concurrent first writes on one engine landing under one registration.++ ## [0.60.587.0] - 2026-11-06++ **An HTTP MCP caller can now say which AI made a write, and attribution reads show it.** Send `X-Gbrain-Agent-Label: Claude Code` (or `Codex`, or a job name) on a request, and the writes that request makes itself show `agent_label` in `gbrain attribution` / `get_write_attribution` and in `get_versions` for admin and local readers. This answers "which of my AIs wrote this?" when several share one OAuth client or token. The label is text the caller declares and gbrain does not verify. The principal is still who was authorized, and no grant, access rule or trust tier reads it. A request without the header is recorded exactly as before, so nothing changes until a caller sends it. Contributed by @JamisonMercurio (#8664).++ ### Itemized changes++ - Both HTTP transports (the OAuth `serve --http` mount and the legacy bearer transport) read the header. Admission stores it on the request's existing `authority` record as `agentLabel`, so there's no new column or migration, and repo-less brains record it too. Stdio MCP and the local CLI have no request headers and record no label.+ - A label is 1 to 120 printable ASCII characters after trimming. Anything else (control, bidi, zero-width or non-ASCII characters, or a longer value) is dropped, never refused.+ - Jobs a labelled request queues (`submit_job` remote jobs and agent jobs) run under their own authority and record no label.+ - Both transports' CORS preflight now allows the header, so a browser client on an origin in `GBRAIN_HTTP_CORS_ORIGIN` can send it without its whole MCP call being blocked.+ - `test/write-agent-label.test.ts` covers both transports, a repo-less brain, the parser bounds, a stored authority that is otherwise identical with and without a label, and a read-only token that is still refused. The export-surface golden gains the optional `agentLabel` and `agent_label` fields.+## [0.60.586.0] - 2026-11-06**A `remember` refused for its arguments now names the whole valid call, so an agent that never read the schema saves on its next try.**@@@ -213,7 -339,7 +341,7 @@@ On a keyless 60-question fixture (old c| `gbrain trust review` | proposals, lowered pages, preferences, holds | also `contradiction` items (`dp<id>`) with supersede, forget, confirm and drop; `--accept-all` skips them || `recall` of a fact in a pending decide proposal | no label | `contested` with the other fact's id, only when the caller can read that fact |- A run files at most `dream.claim_conflicts.max_pairs` (default 500) proposals per source and leaves the rest for the next run. A new unique index keeps concurrent runs to one proposal per pair (migration v291); it rewrites no data. Everything reads and writes database rows, so it works the same on a brain with no git repository. Guide: the "Old and conflicting facts" section of `docs/guides/memory-trust.md`.-A run files at most `dream.claim_conflicts.max_pairs` (default 500) proposals per source and leaves the rest for the next run. A new unique index keeps concurrent runs to one proposal per pair (migration v288); it rewrites no data. Everything reads and writes database rows, so it works the same on a brain with no git repository. Guide: the "Old and conflicting facts" section of `docs/guides/memory-trust.md`.++A run files at most `dream.claim_conflicts.max_pairs` (default 500) proposals per source and leaves the rest for the next run. A new unique index keeps concurrent runs to one proposal per pair (migration v295); it rewrites no data. Everything reads and writes database rows, so it works the same on a brain with no git repository. Guide: the "Old and conflicting facts" section of `docs/guides/memory-trust.md`.### Page versions carry a human reason, and pages read by date (#7798, #7804)diff --cc docs/architecture/key-files/access.mdindex b1535e26cc,9ab14bf4ea..bf3d555b22--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@@ -3,5 -3,5 +3,5 @@@[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 `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; 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` (v287, `--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`, v291; `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`) are never attestable until each is keyed to the member: 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`; `--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`. 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`), 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; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. 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/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (a `regen:all` artifact). Tests: `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).-- `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 `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; 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` (v287, `--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`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: 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`; `--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`. 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`), 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; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. 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 `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; 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` (v287, `--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`, v295; `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`) are never attestable until each is keyed to the member: 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`; `--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`. 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`), 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; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. 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/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). A call that names `source_id` or `source_ids` (full surface only) reads as that scope instead: `recallSources` resolves them through `requestSourceScope` (a source outside the credential's grant is `permission_denied`), `SCOPE_READ_ACCESS` empties identity, actor and audience, so no own facts and no member-page fact are read, restricted pages stay hidden and privacy is never relaxed; the query is ranked on its first 2,000 characters (`MEMORY_RECALL_QUERY_CHARS`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (frozen, byte-identical) and `v2.json` (the scope read and write; `regen:all` artifacts). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v293, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines), `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).diff --cc scripts/module-size-limits.tsvindex af6e149954,b67f37fc2f..ad1862e368--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -47,4 -47,5 +47,5 @@@ src/commands/doctor/checks/extraction-ssrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)- src/core/behavior-change-notice.ts 1656 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot)-src/core/behavior-change-notice.ts 1669 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge++src/core/behavior-change-notice.ts 1670 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot)+ src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot movediff --cc src/core/access/member-sources.tsindex f2a5eb9641,0000000000..70b946dfe1mode 100644,000000..100644--- a/src/core/access/member-sources.ts+++ b/src/core/access/member-sources.ts@@@ -1,127 -1,0 +1,127 @@@+/**- * GBRA-284 (GST-359 G1 wave 2): personal sources. `access_member_sources` (v291) binds a source (a person's DM or++ * GBRA-284 (GST-359 G1 wave 2): personal sources. `access_member_sources` (v295) binds a source (a person's DM or+ * member source) to the member it belongs to; a source with at least one binding is personal. Sources are not keyed to+ * members otherwise, so without this an attest client granted every person's DM source would let every attested person+ * read every other person's DM source.+ *+ * The read rule (`attestedReadScope`, applied once in MCP dispatch for every attested call) only hides inside the+ * credential's grant: it drops every personal source not bound to the attested member, and under a scope read+ * (`SCOPE_READ_ACCESS`) every personal source, the speaker's own included. It never adds a source, so a narrowed read+ * refuses a hidden source exactly like an out-of-grant one (resolveRequestedScope's permission_denied). Unattested+ * callers and member-bound credentials are unchanged (a member-bound credential could take the same rule later).+ * Everything lives in the database, so a repo-less brain gets it unchanged.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, type AuthInfo, type ExplicitReadBinding } from '../ops/contract.ts';+import { isValidSourceId, NO_SOURCES } from '../source-id.ts';+import { isMissingSchemaObject } from '../utils.ts';+import { existingMember } from './members.ts';++export interface MemberSource { member_id: string; source_id: string; created_at: string | null }++function toBinding(row: Record<string, unknown>): MemberSource {+ return { member_id: String(row.member_id), source_id: String(row.source_id), created_at: row.created_at ? new Date(row.created_at as string).toISOString() : null };+}++async function liveSource(engine: BrainEngine, raw: unknown): Promise<string> {+ if (!isValidSourceId(raw)) {+ throw opError('invalid_params', `"${String(raw ?? '')}" is not a valid source id.`, 'Pass a source id from gbrain sources list.');+ }+ const [row] = await engine.executeRaw<{ ok: number }>('SELECT 1 AS ok FROM sources WHERE id = $1 AND archived IS NOT TRUE', [raw]);+ if (!row) throw opError('unknown_source', `No live source "${raw}" exists on this brain.`, 'Pick an id from gbrain sources list.');+ return raw;+}++/** Binds a source to a member (a narrowing: attested callers for anyone else stop reading it); dryRun previews. */+export async function bindMemberSource(engine: BrainEngine, rawMember: unknown, rawSource: unknown, opts: { dryRun?: boolean } = {}): Promise<{ binding: MemberSource; applied: boolean; changed: boolean; owners: string[] }> {+ const member = await existingMember(engine, rawMember, 'bound to a source');+ if (member.status === 'removed') {+ throw opError('access_member_invalid', `Member "${member.id}" was removed.`, 'Removed ids are never reused; bind the source to a live member.', { reason: 'removed' });+ }+ const source = await liveSource(engine, rawSource);+ const owners = await sourceOwners(engine, source);+ const changed = !owners.includes(member.id);+ if (changed && !opts.dryRun) {+ await engine.executeRaw('INSERT INTO access_member_sources (member_id, source_id) VALUES ($1, $2) ON CONFLICT DO NOTHING', [member.id, source]);+ }+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT member_id, source_id, created_at FROM access_member_sources WHERE member_id = $1 AND source_id = $2', [member.id, source]);+ return { binding: row ? toBinding(row) : { member_id: member.id, source_id: source, created_at: null }, applied: changed && !opts.dryRun, changed,+ owners: changed ? [...owners, member.id].sort() : owners };+}++/**+ * Unbinds a source from a member. When it was the source's last binding the source stops being personal, so every+ * attested person through a credential that grants it reads it again (a widening): preview unless apply is set.+ */+export async function unbindMemberSource(engine: BrainEngine, rawMember: unknown, rawSource: unknown, opts: { apply?: boolean } = {}): Promise<{ binding: MemberSource; applied: boolean; owners: string[]; still_personal: boolean }> {+ const member = await existingMember(engine, rawMember, 'unbound from a source');+ if (!isValidSourceId(rawSource)) throw opError('invalid_params', `"${String(rawSource ?? '')}" is not a valid source id.`, 'Pass a source id from gbrain access member source list.');+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT member_id, source_id, created_at FROM access_member_sources WHERE member_id = $1 AND source_id = $2', [member.id, rawSource]);+ if (!row) {+ throw opError('invalid_params', `Source "${rawSource}" is not bound to member "${member.id}".`, `List the bindings with gbrain access member source list ${member.id}.`, { reason: 'unknown_binding' });+ }+ if (opts.apply) await engine.executeRaw('DELETE FROM access_member_sources WHERE member_id = $1 AND source_id = $2', [member.id, rawSource]);+ const owners = (await sourceOwners(engine, rawSource)).filter(o => o !== member.id);+ return { binding: toBinding(row), applied: opts.apply === true, owners, still_personal: owners.length > 0 };+}++export async function listMemberSources(engine: BrainEngine, opts: { member?: string } = {}): Promise<MemberSource[]> {+ const member = opts.member === undefined ? undefined : (await existingMember(engine, opts.member, 'listed')).id;+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT member_id, source_id, created_at FROM access_member_sources${member ? ' WHERE member_id = $1' : ''} ORDER BY member_id, source_id`, member ? [member] : []);+ return rows.map(toBinding);+}++async function sourceOwners(engine: BrainEngine, source: string): Promise<string[]> {+ const rows = await engine.executeRaw<{ member_id: string }>('SELECT member_id FROM access_member_sources WHERE source_id = $1 ORDER BY member_id', [source]);+ return rows.map(r => r.member_id);+}++/**+ * The personal sources among `sources` an attested call for `member` must not read: every personal source not bound to- * that member, or every personal source under a scope read. A schema before v291 has no personal source.++ * that member, or every personal source under a scope read. A schema before v295 has no personal source.+ */+export async function hiddenPersonalSources(engine: Pick<BrainEngine, 'executeRaw'>, sources: readonly string[], member: string, scopeRead: boolean): Promise<Set<string>> {+ const ids = [...new Set(sources)];+ if (!ids.length) return new Set();+ let rows: { source_id: string; member_id: string }[];+ try {+ rows = await engine.executeRaw<{ source_id: string; member_id: string }>('SELECT source_id, member_id FROM access_member_sources WHERE source_id = ANY($1::text[])', [ids]);+ } catch (e) {+ if (!isMissingSchemaObject(e, 'table', 'access_member_sources')) throw e;+ return new Set();+ }+ const own = new Set(scopeRead ? [] : rows.filter(r => r.member_id === member).map(r => r.source_id));+ return new Set(rows.map(r => r.source_id).filter(s => !own.has(s)));+}++export interface ReadScopeOpts { auth?: AuthInfo; sourceId?: string; localFederatedSourceIds?: string[]; explicitReadBinding?: ExplicitReadBinding }++/**+ * The read scope of one attested call: the credential's granted read sources (its federated grant, else the+ * transport's federated set for an unqualified read, else its scalar source) minus the hidden personal sources, as an+ * explicit grant so every resolver (sourceScopeOpts, resolveRequestedScope, federatedSearchScope) reads the same set.+ * A hidden scalar source (the call's sourceId, which writes and scalar reads use directly) moves to the first kept+ * source, or to NO_SOURCES, which refuses. Unchanged (the same object) when nothing is hidden. A grant left empty reads+ * nothing (NO_SOURCES never names a source).+ */+export async function attestedReadScope<T extends ReadScopeOpts>(engine: Pick<BrainEngine, 'executeRaw'>, opts: T, member: string, scopeRead: boolean): Promise<T> {+ const auth = opts.auth;+ if (!auth || auth.sourceId === NO_SOURCES) return opts;+ const federated = opts.localFederatedSourceIds;+ const scalar = opts.sourceId ?? 'default';+ const grant = auth.allowedSources?.length ? auth.allowedSources : federated && federated.length > 1 ? federated : [scalar];+ const scalars = [scalar, ...(auth.sourceId ? [auth.sourceId] : [])];+ const hidden = await hiddenPersonalSources(engine, [...grant, ...scalars, ...(federated ?? []), ...(opts.explicitReadBinding?.sourceIds ?? [])], member, scopeRead);+ if (!hidden.size) return opts;+ const keep = (ids: string[]) => ids.filter(s => !hidden.has(s));+ const allowed = keep(grant);+ const moved = allowed[0] ?? NO_SOURCES;+ return {+ ...opts,+ ...(hidden.has(scalar) ? { sourceId: moved } : {}),+ auth: { ...auth, allowedSources: allowed.length ? allowed : [NO_SOURCES], ...(auth.sourceId && hidden.has(auth.sourceId) ? { sourceId: moved } : {}) },+ ...(federated ? { localFederatedSourceIds: keep(federated) } : {}),+ ...(opts.explicitReadBinding ? { explicitReadBinding: { ...opts.explicitReadBinding, sourceIds: keep(opts.explicitReadBinding.sourceIds) } } : {}),+ };+}diff --cc src/core/behavior-change-notice.tsindex 30fdfa0036,c0aaa752d3..c95ebf16e4--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -1450,14 -1450,27 +1450,28 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.577.0', id: 'refresh_fence_refusal_gst1387', text: 'A write refused because `gbrain sources refresh` is fast-forwarding its checkout (`worktree_refreshing`) is now a registered retryable refusal whose fix is `next: wait` with `retry_after_ms`, instead of class server with `fix: gbrain doctor`; the memory verbs keep `unavailable` and add `canonical: worktree_refreshing`. An interactive CLI or MCP write waits out the fence for up to 10 s before that refusal; a background write is refused at once as before. `remember` with `items` whose every item failed is now refused with the first item\'s error (CLI exit 1, MCP isError) instead of a success envelope with `failed`, and a batch with any failed item adds `status: "error"` and the first failed `code`, so the CLI exits 1 and MCP returns isError with every item\'s receipt.' },{ since: '0.60.583.0', id: 'sync_write_through_off_writeback_7084', text: 'With `sync.write_through` off, a managed `gbrain sync` no longer writes its canonical correction of a file (the frontmatter, title or tags the page keeps when an upstream edit drops them) back into the checkout (#7084, #8118). The page keeps the correction in the database only, as on a read-only mirror source, and `git status` stays clean. With `sync.write_through` on, nothing changes. Files already rewritten by earlier versions are not touched; restore them with `git checkout -- <paths>` or commit them.' },{ since: '0.60.583.0', id: 'managed_sync_dry_run_counts_7087', text: 'A managed `gbrain sync --dry-run` now reports the files the run would add, modify, soft-delete and rename, and prints them as one line (#7087). It used to report the cursor\'s committed counts: zero before a run, or the previous run\'s counts when nothing had changed.' },+ // Convergence PR A (GST-1500, evidence-based baseline). since is stamped at the merge slot.+ { since: '0.60.592.0', id: 'conversion_content_evidence_pr_a', text: '`gbrain sources canonical <id> --to git` now decides a page with no import record by content evidence instead of calling it database-ahead: an older version equal to the committed file adopts it, a page equal to an older committed blob lets Git win (`git_wins.by.file_moved`), and a page where both moved or nothing is shared is a new discard (`no_record_both_moved`, `no_record_no_evidence`) until the owner decides it. `--list-out <file>` writes the review list, `--decisions <file>` applies the decisions (bound into the hash), and `--approval-out` / `--approved` apply an approval across time: only items unchanged since the approval apply, and the rest returns as `git_conversion_delta` with counts. These files are written 0600 and refused inside a source checkout. A page that changes during the apply is held instead of overwritten, and a failed apply reports `recovery` (mode, commits, push, writes, rollback). See docs/guides/git-canonical.md#review-list-and-decisions.' },+ { since: '0.60.592.0', id: 'git_gap_live_pages_pr_a', text: '`gbrain sources git-gap` and doctor `db_ahead_of_git` now report each source\'s live pages (`live_pages`) beside the pages read, and a scan the time budget stopped reads `PARTIAL, <read> of <live> live page(s) read` instead of a bare count. `sources git-gap` also reports `direction_evidence` for pages with no import record. `gbrain repair rows-behind` never re-imports a row with no import record whose older version equals its committed file (the database moved since), even with `--include-ambiguous`: it is listed `excluded:database_moved`. Nor one whose page and file both moved since the last state they shared: it is listed `excluded:both_moved`, and `gbrain repair file-drift` decides it.' },{ since: '0.60.583.0', id: 'frontmatter_missing_source_dir_7889', text: 'A registered source whose directory does not exist is no longer reported frontmatter-clean (#7889). The frontmatter audit marks it `missing` (and lists it under `missing_sources`), and doctor `frontmatter_integrity` and `frontmatter_repairable` warn with the path and ask you to restore it or run `gbrain sources set-path <id> <path>`; they no longer call it clean or blame a timeout.' },- { since: 'TBD', id: 'memory_recall_scope_read_gst1094', text: '`memory_recall` now takes `source_id` and `source_ids`. A call that names sources reads as their audience, never as the attested person: no own recent facts first and no fact from any member page; a page restricted to named readers stays hidden and `visibility: private` is never relaxed. A source outside the credential\'s read grant is refused (`permission_denied`) and `__all__` is refused (`invalid_params`). Without sources, `memory_recall` is unchanged. The contract is `docs/contracts/qm-memory-provider/v2.json`; `v1.json` is unchanged.' },- { since: 'TBD', id: 'member_bound_acting_user_gst900', text: 'A credential bound to a member may now send `acting_user` with no `x-qm-actor` header: its own member id, or a canonical id linked to that member, is dropped and the call runs exactly as the credential; any other value is refused (`actor_not_attested` reason `argument_mismatch`). A credential bound to no member is still refused (`argument_without_attestation`).' },- { since: 'TBD', id: 'recall_max_chars_harn15', text: '`recall` now takes `max_chars` (a whole number from 200 to 12000, as `memory_recall`): it keeps the whole facts, then results, whose text fits, adds no marker and returns `truncated`; without it `recall` is unchanged.' },+ { since: '0.60.595.0', id: 'memory_recall_scope_read_gst1094', text: '`memory_recall` now takes `source_id` and `source_ids`. A call that names sources reads as their audience, never as the attested person: no own recent facts first and no fact from any member page; a page restricted to named readers stays hidden and `visibility: private` is never relaxed. A source outside the credential\'s read grant is refused (`permission_denied`) and `__all__` is refused (`invalid_params`). Without sources, `memory_recall` is unchanged. The contract is `docs/contracts/qm-memory-provider/v2.json`; `v1.json` is unchanged.' },+ { since: '0.60.595.0', id: 'member_bound_acting_user_gst900', text: 'A credential bound to a member may now send `acting_user` with no `x-qm-actor` header: its own member id, or a canonical id linked to that member, is dropped and the call runs exactly as the credential; any other value is refused (`actor_not_attested` reason `argument_mismatch`). A credential bound to no member is still refused (`argument_without_attestation`).' },+ { since: '0.60.595.0', id: 'qm_scope_writes_gst1113', text: '`memory_write` now takes `source_id`: a credential that lists the source in `gbrain auth rescope --attest-sources` saves the facts on that scope source\'s `memory/scope` page (`visibility: world`, attested to the person); any other source is refused (`permission_denied` reason `source_not_attested`, or `invalid_params` reason `source_is_member_source` for its own write source). Listing a source marks it a QM scope source for good: it is never federated (`sources federate` refuses, `sources restore` leaves it unfederated) and no other grant, token or registration may read it. Remote writes to `memory/scope` other than a scope `memory_write` are refused, and `memory_recall` without sources never reads a scope source.' },+ { since: '0.60.595.0', id: 'recall_question_terms_gst1304', text: '`recall` with a `question` over 12 content words (a provider\'s instruction preamble ahead of the turn) is now searched on its last 24 content words and scored on the 12 of those the fewest candidate facts hold, instead of on its first 12, so a keyword-only brain no longer returns no facts because the preamble filled the 12. Shorter questions rank as before. A response whose candidates all fell under the admission floor carries `facts_below_floor: <n>`, and a question over 2,000 characters is refused with reason `question_too_long` and detail `max_chars=2000 received_chars=<n>`. `actor_not_attested` reason `argument_without_attestation` now names what the call lacked, in its message and in detail `missing=attest_right`, `missing=x-qm-actor` or both; QM tools also carry `detail` in `structuredContent.error`.' },+ { since: '0.60.595.0', id: 'recall_max_chars_harn15', text: '`recall` now takes `max_chars` (a whole number from 200 to 12000, as `memory_recall`): it keeps the whole facts, then results, whose text fits, adds no marker and returns `truncated`; without it `recall` is unchanged.' },+ { since: '0.60.595.0', id: 'unknown_param_meta_only_harn15', text: 'A read that ignores a parameter the tool does not declare (`mcp.strict_params` `warn`, the default) no longer adds a `[gbrain notice unknown_param kind=info]` text block to the result: the warning is only in `_meta.warnings` (`{code: \'unknown_param\', param, suggestion?}`), so a harness that stores tool output in its turns never stores it. Writes still refuse unknown parameters, and `reject` mode is unchanged.' },+ // PR B (convergence lane L4): commit ledger, foreign_writers, owner-path guard. since is stamped at the merge slot.+ { since: '0.60.594.0', id: 'commit_ledger_prb', text: 'Every commit gbrain makes is now recorded as one line in `<git common dir>/gbrain/commit-ledger.jsonl` (inside `.git`, never tracked, rotated at 4 MiB to `commit-ledger.1.jsonl`). A failed append never fails the commit; it is logged once.' },+ { since: '0.60.594.0', id: 'doctor_foreign_writers_prb', text: 'New doctor check `foreign_writers`: in every source checkout on this host, managed worktrees included, a commit gbrain\'s commit ledger does not name fails the check with the newest such commit and a fix that asks who makes it; an unconfirmed commit (a crash between `git commit` and the ledger line) and page files left uncommitted for over 30 minutes warn. Commits before the ledger started are reported as uncovered, not foreign. A repo-less brain reports not_applicable.' },+ { since: '0.60.594.0', id: 'sources_guard_prb', text: 'New `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]`: the commit guard on a managed source\'s worktree, from its owner host only, installed in a hooks directory private to that worktree. `--mode enforce` also refuses cherry-pick, revert, rebase and sequencer commits. `gbrain git guard` is unchanged.' },+ { since: '0.60.594.0', id: 'refresh_barrier_prb', text: 'New setting `persistence.refresh_barrier` (off by default): with it on, a single page write (`put_page`, `remember` and the other single-page verbs) that reaches a checkout while `gbrain sources refresh` drains or merges it is journaled and answered `pending` at once (MCP `isError: false`, CLI exit 10) instead of refused `worktree_refreshing`. It commits after the refresh, or ends `revision_conflict` when the refresh changed its file, or `refresh_barrier_expired` after `persistence.refresh_barrier_max_wait_ms` (15 minutes). Syncs, jobs and batches keep the refusal. `gbrain upgrade --check-downgrade` exits 3 `downgrade_blocked_deferred_writes` while such writes wait.' },+ { since: '0.60.594.0', id: 'commit_push_base_prb', text: '`gbrain git commit-push` takes `--base <path>=<blob>|absent` (repeatable, each path one the command commits): it refuses `commit_base_moved`, committing nothing, when the file at HEAD is no longer the blob the caller read. Without `--base` nothing changes.' },+ { since: '0.60.594.0', id: 'file_drift_held_needs_prefer_8615', text: '`gbrain repair file-drift` with `--held`, `--side`, `--state`, `--cursor` or `--provenance` and no `--prefer` now refuses with the usage line (`invalid_params`, and `file_drift_state_required` for a deleted side without `--state`) instead of silently running the all-drifted survey, which counted a different set of pages (#8615).' },+ { since: '0.60.594.0', id: 'refresh_source_changed_retry_8617', text: 'A `gbrain sources refresh` run refused `refresh_source_changed` because the checkout HEAD moved (a writer committing) or work reached the checkout after the drain check now retries once from a fresh precheck in the same run, so the tick is not lost (#8617). When the retry is refused too, the run returns the first `refresh_source_changed` refusal with the retry\'s cause appended; ownership or source-membership changes are not retried.' },+ { since: '0.60.594.0', id: 'commit_push_checkout_not_a_source_8662', text: '`gbrain git commit-push` now refuses `checkout_not_a_source` before staging anything when this brain home records its source checkouts (a managed brain) and the checkout it resolved from the working directory (no `--path`) is none of them and has no `gbrain.sourceRoot`, for example a wrapper that changed into another repository (#8662). The refusal names the resolved path and the brain\'s checkouts; pass `--path` with the absolute brain checkout. Hosts whose brain records no source checkout behave as before.' },{ since: 'TBD', id: 'attest_scope_read_ops_gst1158', text: 'An attested call (`x-qm-actor`) to `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` or `query` that names `source_id` or `source_ids` now reads as those sources\' audience, as `memory_recall` already did: the person\'s pages restricted to named readers and their member page `memory/members/<member>` read as missing, a source outside the credential\'s read grant is refused, and `__all__` or `all_sources` beside a named source is refused (`invalid_params`). `get_timeline` gains `source_id` and `source_ids`, `find_experts` and `volunteer_context` gain `source_ids`, and `volunteer_context` refuses `stats: true` under that read. `gbrain auth rescope --attest-read person|scope|none` sets how an attest credential reads named sources: `person` narrows to them but reads as the person; `scope` reads them as their audience and refuses every call that names no person (`actor_not_attested` reason `actor_required`), reading nothing; unset (the default) keeps the scope read and still serves calls that name no person. `gbrain doctor` warns (`attest_read_shared_scope`) when a person credential reads a source another attest credential reads as the scope.' },{ since: 'TBD', id: 'attest_direct_page_writes_deferred_gst1158', text: 'An attested call (`x-qm-actor`) may no longer run `add_timeline_entry`, `add_link`, `put_page` or `edit_page`: they write pages every reader of the page sees, so they wait for owner-approved proposals. `gbrain auth rescope --attest-ops` refuses a list that names one, a credential whose list already names one is refused for it on every attested call (`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes. Unattested calls and member-bound credentials are unchanged.' },- { since: 'TBD', id: 'unknown_param_meta_only_harn15', text: 'A read that ignores a parameter the tool does not declare (`mcp.strict_params` `warn`, the default) no longer adds a `[gbrain notice unknown_param kind=info]` text block to the result: the warning is only in `_meta.warnings` (`{code: \'unknown_param\', param, suggestion?}`), so a harness that stores tool output in its turns never stores it. Writes still refuse unknown parameters, and `reject` mode is unchanged.' },- { since: 'TBD', id: 'personal_sources_gbra284', text: 'An operator can bind a source to the member it belongs to (`gbrain access member source add <member> <source>`, migration v291); a bound source is personal. An attested call (`x-qm-actor`) now reads its credential\'s grant minus every personal source bound to another member, and a read that names sources as their audience (the scope read) reads no personal source at all, not even the speaker\'s own. A hidden personal source named in `source_id` or `source_ids` is refused exactly like a source outside the grant (`permission_denied`); an unnamed read skips it. The rule only hides inside the grant and never makes a source readable, so it is within the existing trust posture (gate_rev 6). On an existing install nothing changes until an operator binds a source; after that, a credential whose grant already includes the bound source stops showing it to attested callers for anyone else. Unattested calls and member-bound credentials are unchanged.' },++ { since: 'TBD', id: 'personal_sources_gbra284', text: 'An operator can bind a source to the member it belongs to (`gbrain access member source add <member> <source>`, migration v295); a bound source is personal. An attested call (`x-qm-actor`) now reads its credential\'s grant minus every personal source bound to another member, and a read that names sources as their audience (the scope read) reads no personal source at all, not even the speaker\'s own. A hidden personal source named in `source_id` or `source_ids` is refused exactly like a source outside the grant (`permission_denied`); an unnamed read skips it. The rule only hides inside the grant and never makes a source readable, so it is within the existing trust posture (gate_rev 6). On an existing install nothing changes until an operator binds a source; after that, a credential whose grant already includes the bound source stops showing it to attested callers for anyone else. Unattested calls and member-bound credentials are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/schema-migrations/latest.generated.tsindex e9b5222f7a,84959b7547..0e755cb30c--- 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 = 291;-export const LATEST_SCHEMA_VERSION = 294;++export const LATEST_SCHEMA_VERSION = 295;diff --cc src/core/schema-migrations/registry.generated.tsindex 9f8563f7c2,7cbe1555de..1c2dcc56ea--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@@ -290,8 -290,11 +290,12 @@@ import { v286 } from './v286-qm-actor-limport { v287 } from './v287-multi-page-recovery-record.ts';import { v288 } from './v288-decide-proposals-claim-pair-index.ts';import { v289 } from './v289-page-change-reasons.ts';- import { v290 } from './v290-attest-read.ts';- import { v291 } from './v291-access-member-sources.ts';+ import { v290 } from './v290-wake-subscriptions.ts';+ import { v291 } from './v291-persistence-request-replay-indexes.ts';+ import { v292 } from './v292-refresh-write-barrier.ts';+ import { v293 } from './v293-qm-attest-sources.ts';+ import { v294 } from './v294-attest-read.ts';++import { v295 } from './v295-access-member-sources.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@@ -582,4 -585,7 +586,8 @@@ export const MIGRATIONS: Migration[] =v289,v290,v291,+ v292,+ v293,+ v294,++ v295,];diff --cc src/core/schema-migrations/v295-access-member-sources.tsindex 7d2560d142,0000000000..4b8dcb846emode 100644,000000..100644--- a/src/core/schema-migrations/v295-access-member-sources.ts+++ b/src/core/schema-migrations/v295-access-member-sources.ts@@@ -1,35 -1,0 +1,35 @@@+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-284 (GST-359 G1 wave 2): personal sources. A row binds a source (a+// person's DM or member source) to the member it belongs to; a source with at+// least one binding is personal. An attested call (x-qm-actor) reads its+// credential's grant minus every personal source not bound to the attested+// member, and a scope read never reads a personal source (access/member-sources.ts).+// The rule only hides inside the grant, so no source becomes readable. source_id+// has no foreign key on purpose: removing and re-adding a source with the same id+// keeps it personal (hidden), never public. Database only, so a repo-less brain+// gets it unchanged. Nothing is rewritten on upgrade; with no binding every read+// is unchanged. No schema.sql mirror, like v286. Numbered on the GBRA-284+// branch; expect a renumber at the merge slot.- export const v291: Migration = {- version: 291,++export const v295: Migration = {++ version: 295,+ name: 'access_member_sources',+ idempotent: true,+ sql: `+CREATE TABLE IF NOT EXISTS access_member_sources (+ member_id TEXT NOT NULL REFERENCES access_members(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (member_id, source_id)+);+CREATE INDEX IF NOT EXISTS access_member_sources_source_idx ON access_member_sources (source_id);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN+ ALTER TABLE access_member_sources ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+`,+};diff --cc src/mcp/dispatch.tsindex 26f231304c,782709baf5..d0695f1c93--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@@ -970,9 -1009,7 +1011,9 @@@ export async function dispatchToolCallauth: opts.auth, transport: opts.transport, audienceAsserted: audience !== null });// GST-1158 E1: an attested read that names sources reads as the scope (access/scope-read.ts), or as the person on an attest_read person credential.readMode = attested?.actor ? attestedReadMode(name, attested.params, attested.read) : null;- access = readMode === 'scope' ? SCOPE_READ_ACCESS : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);+ access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(engine, [])).folderCoverage } : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);+ // GBRA-284: an attested call reads its grant minus other members' personal sources, a scope read minus every personal source (access/member-sources.ts).+ if (attested?.actor) scoped = await attestedReadScope(engine, resolved, attested.actor.member, readMode === 'scope');} catch (e) {// GST-359: a call that names a person gets every failure here (a lock timeout reading its link included) in the// envelope QM reads, never a thrown call; anything else keeps the caller's own error path.diff --cc test/fixtures/goldens/migrations/records.jsonindex 8b3e3fc3c0,2e3e12d73e..149d23ea47--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@@ -1,6 -1,6 +1,6 @@@{"golden": {- "count": 286,- "count": 289,++ "count": 290,"gaps": [17,18,@@@ -94,7 -97,7 +97,7 @@@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 291,- "latest": 294,++ "latest": 295,"records": [{"handler": {@@@ -4699,20 -4799,7 +4799,20 @@@"sqlFor": "absent","transaction": "absent","verify": "absent",- "version": 290+ "version": 294+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "access_member_sources",+ "sql": {+ "length": 573,+ "sha256": "63da00dc6df6d19b1da78d752ab0e5566c1511a1cff16a2838e54b5fbf701ff9"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",- "version": 291++ "version": 295}],"versions": [@@@ -5001,7 -5088,10 +5101,11 @@@288,289,290,- 291+ 291,+ 292,+ 293,- 294++ 294,++ 295]},"normalizer": "migrations-record-v1"diff --cc test/qm-personal-sources.test.tsindex 560d4ee308,0000000000..ac663dfc00mode 100644,000000..100644--- a/test/qm-personal-sources.test.ts+++ b/test/qm-personal-sources.test.ts@@@ -1,300 -1,0 +1,300 @@@+/**- * GBRA-284 (GST-359 G1 wave 2): personal sources. A source bound to a member (access_member_sources, v291) is read by an++ * GBRA-284 (GST-359 G1 wave 2): personal sources. A source bound to a member (access_member_sources, v295) is read by an+ * attested call only for that member, and never by a scope read; the rule only hides inside the credential's grant.+ *+ * 1. Protects: the HARN-1 gate shape. An attest client granted {source-a, dm-alice-example, dm-bob-example}, each DM+ * source bound to its member: attested alice-example's unnamed memory_recall returns her DM-source fact and her+ * memory_write fact, never bob-example's DM-source fact (and the reverse for bob); query and get_page follow the same+ * rule; a scope read naming a DM source (even the speaker's own) is refused exactly like an out-of-grant source; a+ * person credential naming another member's DM source is refused the same way. A client whose grant omits the DM+ * sources never reads them (the rule adds nothing). Unattested calls are unchanged.+ * 2. Fails when: an attested person reads another member's personal source through any of those ops, a scope read+ * reads a personal source, a refusal differs from the out-of-grant refusal, a person loses their own personal source,+ * or the rule widens a grant.+ * 3. Existing coverage: test/qm-scope-read.test.ts pins the scope read; test/access-qm-actor.test.ts the attested actor.+ * 4. Real seams: OAuth clients issued tokens by the provider's client-credentials grant, verified by the provider,+ * dispatched through MCP dispatch with remote=true on a repo-less brain (no git checkout anywhere); writes go through+ * the persistence coordinator; embeddings stubbed. PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { addMember, bindCredential, removeMember } from '../src/core/access/members.ts';+import { linkMember } from '../src/core/access/actor.ts';+import { bindMemberSource, listMemberSources, unbindMemberSource } from '../src/core/access/member-sources.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { attestedCallerAccess } from '../src/core/access/actor.ts';+import { withCallerAccess } from '../src/core/search/private-visibility.ts';+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';+import { prepareRemoteAgent, withSubmissionAuthority, type RemoteAgentAuthority } from '../src/core/minions/submission-authority.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const DIMS = 1536;+function vectorFor(text: string): number[] {+ const v = new Array<number>(DIMS).fill(0);+ for (const w of text.toLowerCase().match(/[a-z]+/g) ?? []) {+ let h = 0;+ for (const ch of w) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ v[h % DIMS] += 1;+ }+ const n = Math.hypot(...v) || 1;+ return v.map(x => x / n);+}++const SRC = 'source-a';+const DM_A = 'dm-alice-example';+const DM_B = 'dm-bob-example';+const OTHER = 'source-other';+const ALICE_ID = 'U0ALICE';+const BOB_ID = 'U0BOB';+const OPS = ['entity', 'find_experts', 'get_backlinks', 'get_page', 'get_timeline', 'get_write_request', 'memory_recall', 'memory_write', 'query', 'search', 'volunteer_context', 'whois'];+const PAGE_A = 'notes/alice-dm-example';+const PAGE_B = 'notes/bob-dm-example';+const Q = 'harbor tide charts';+const note = (title: string, body: string) => ['---', 'type: note', 'title: ' + title, '---', '# ' + title, '', body].join('\n');++for (const kind of testBackends()) {+ describe('personal sources: an attested person reads only their own (' + kind + ', repo-less)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const clients: Record<string, string> = {};+ const verify = async (bearer: string) => await provider().verifyAccessToken(bearer) as unknown as AuthInfo;++ async function call(client: string, op: string, params: Record<string, unknown>, actor: string | null = ALICE_ID, extra: { writeWaitMs?: number } = {}) {+ const auth = await verify(clients[client]!);+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? SRC, takesHoldersAllowList: ['world'],+ ...(actor !== null ? { actor: { header: actor } } : {}), ...(extra.writeWaitMs ? { writeWaitMs: extra.writeWaitMs } : {}),+ });+ const text = out.content.map(c => c.text).join('\n');+ let json: Record<string, any> = {};+ try { json = JSON.parse(out.content[0]?.text ?? ''); } catch { /* prose */ }+ return { isError: out.isError === true, text, json, structured: out.structuredContent as Record<string, any> | undefined,+ all: text + JSON.stringify(out._meta ?? {}) + JSON.stringify(out.structuredContent ?? {}) };+ }+ const recall = (client: string, actor: string | null, extra: Record<string, unknown> = {}) => call(client, 'memory_recall', { query: Q, max_chars: 12_000, ...extra }, actor);+ /** The refusal a source outside the grant gets; a hidden personal source must get exactly this (no existence oracle). */+ async function outOfGrant(client: string, op: string, params: Record<string, unknown>, actor: string | null = ALICE_ID) {+ const out = await call(client, op, { ...params, ...('source_id' in params ? { source_id: OTHER } : { source_ids: [OTHER] }) }, actor);+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: 'permission_denied' });+ return out;+ }+ async function refusedLikeOutOfGrant(client: string, op: string, params: Record<string, unknown>, actor: string | null = ALICE_ID) {+ const out = await call(client, op, params, actor);+ const ref = await outOfGrant(client, op, params, actor);+ expect({ isError: out.isError, code: out.json.code, message: out.json.message }).toEqual({ isError: true, code: 'permission_denied', message: ref.json.message });+ const named = typeof params.source_id === 'string' ? params.source_id : Array.isArray(params.source_ids) && params.source_ids.length === 1 ? params.source_ids[0] as string : null;+ if (named) expect(JSON.stringify(out.json).replaceAll(named, OTHER)).toBe(JSON.stringify(ref.json));+ for (const c of ['canarydmalice', 'canarydmbob']) expect(out.all).not.toContain(c);+ }++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ for (const id of [SRC, DM_A, DM_B, OTHER]) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ for (const id of ['alice-example', 'bob-example', 'carol-example']) await addMember(engine, id);+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);+ await linkMember(engine, 'bob-example', 'qm', BOB_ID);+ // World facts and pages ingested locally into each DM source (what a DM import or a local remember leaves).+ await engine.insertFact({ fact: 'Alice keeps the harbor tide charts in a red folder canarydmalice', kind: 'fact', entity_slug: null, source: 'test', visibility: 'world' }, { source_id: DM_A });+ await engine.insertFact({ fact: 'Bob keeps the harbor tide charts in a blue folder canarydmbob', kind: 'fact', entity_slug: null, source: 'test', visibility: 'world' }, { source_id: DM_B });+ await importFromContent(engine, PAGE_A, note('Alice DM Example', 'Harbor tide charts from the alice thread canarydmalicepage.'), { sourceId: DM_A });+ await importFromContent(engine, PAGE_B, note('Bob DM Example', 'Harbor tide charts from the bob thread canarydmbobpage.'), { sourceId: DM_B });+ await importFromContent(engine, 'notes/world-example', note('World Example', 'Harbor tide charts for everyone canaryworldpage.'), { sourceId: SRC });+ const register = async (name: string, grant: string[], read?: 'person' | 'scope') => {+ const c = await provider().registerClientManual('personal-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], grant[0]!);+ await provider().rescopeClient(c.clientId, { federatedRead: grant });+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: OPS, ...(read ? { attestRead: read } : {}) });+ clients[name] = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;+ };+ await register('narrow', [SRC]);+ await register('wide', [SRC, DM_A, DM_B]);+ await register('person', [SRC, DM_A, DM_B], 'person');+ await register('scope', [SRC, DM_A, DM_B], 'scope');+ await register('bobdm', [DM_B]);+ await register('bobfirst', [DM_B, SRC]);+ for (const [actor, who] of [[ALICE_ID, 'alice'], [BOB_ID, 'bob']] as const) {+ const wrote = await call('wide', 'memory_write', { facts: [{ fact: `${who} wants the harbor tide charts by Friday canarymember${who}`, provenance: 'turn 1' }], idempotency_key: randomUUID() }, actor, { writeWaitMs: 30_000 });+ expect(wrote.structured?.status).toBe('committed');+ }+ expect((await bindMemberSource(engine, 'alice-example', DM_A)).applied).toBe(true);+ expect((await bindMemberSource(engine, 'bob-example', DM_B)).applied).toBe(true);+ __resetPrivateVisibilityCacheForTests();+ }, 240_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await close?.();+ }, 60_000);++ test('HARN-1: attested alice-example recalls her own DM-source fact and memory_write fact, never bob-example\'s; bob gets the reverse', async () => {+ const alice = await recall('wide', ALICE_ID);+ expect(alice.isError).toBe(false);+ expect(alice.text).toContain('canarydmalice');+ expect(alice.text).toContain('canarymemberalice');+ expect(alice.all).not.toContain('canarydmbob');+ expect(alice.all).not.toContain('canarymemberbob');+ const bob = await recall('wide', BOB_ID);+ expect(bob.text).toContain('canarydmbob');+ expect(bob.text).toContain('canarymemberbob');+ expect(bob.all).not.toContain('canarydmalice');+ expect(bob.all).not.toContain('canarymemberalice');+ for (const client of ['scope', 'person']) {+ const out = await recall(client, ALICE_ID);+ expect(out.text).toContain('canarydmalice');+ expect(out.all).not.toContain('canarydmbob');+ }+ }, 120_000);++ test('a grant without the DM sources never reads them (0 of 2): the rule only hides, it never adds a source', async () => {+ const out = await recall('narrow', ALICE_ID);+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canarymemberalice');+ for (const c of ['canarydmalice', 'canarydmbob']) expect(out.all).not.toContain(c);+ await refusedLikeOutOfGrant('narrow', 'memory_recall', { query: Q, source_ids: [DM_A] });+ }, 120_000);++ test('a scope read never reads a personal source, not even the speaker\'s own: refused like an out-of-grant source', async () => {+ for (const client of ['wide', 'scope']) {+ for (const dm of [DM_A, DM_B]) {+ await refusedLikeOutOfGrant(client, 'memory_recall', { query: Q, source_ids: [dm] });+ await refusedLikeOutOfGrant(client, 'memory_recall', { query: Q, source_ids: [SRC, dm] });+ await refusedLikeOutOfGrant(client, 'query', { query: Q, source_ids: [dm] });+ await refusedLikeOutOfGrant(client, 'get_page', { slug: dm === DM_A ? PAGE_A : PAGE_B, source_id: dm });+ }+ const room = await recall(client, ALICE_ID, { source_ids: [SRC] });+ expect(room.isError).toBe(false);+ for (const c of ['canarydmalice', 'canarydmbob', 'canarymemberalice']) expect(room.all).not.toContain(c);+ }+ }, 120_000);++ test('a person read names its own personal source; another member\'s is refused like an out-of-grant source', async () => {+ expect((await recall('person', ALICE_ID, { source_ids: [DM_A] })).text).toContain('canarydmalice');+ expect((await call('person', 'get_page', { slug: PAGE_A, source_id: DM_A })).text).toContain('canarydmalicepage');+ await refusedLikeOutOfGrant('person', 'memory_recall', { query: Q, source_ids: [DM_B] });+ await refusedLikeOutOfGrant('person', 'memory_recall', { query: Q, source_ids: [DM_A, DM_B] });+ await refusedLikeOutOfGrant('person', 'get_page', { slug: PAGE_B, source_id: DM_B });+ await refusedLikeOutOfGrant('person', 'query', { query: Q, source_ids: [DM_B] });+ await refusedLikeOutOfGrant('person', 'get_page', { slug: PAGE_A, source_id: DM_A }, BOB_ID);+ }, 120_000);++ test('get_page: another member\'s DM page reads as missing, the person\'s own reads', async () => {+ const missing = await call('wide', 'get_page', { slug: 'notes/nobody-example' });+ expect(missing.json.code).toBe('page_not_found');+ const theirs = await call('wide', 'get_page', { slug: PAGE_B });+ expect({ isError: theirs.isError, code: theirs.json.code, message: theirs.json.message })+ .toEqual({ isError: true, code: missing.json.code, message: missing.json.message.replace('notes/nobody-example', PAGE_B) });+ expect(theirs.all).not.toContain('canarydmbobpage');+ expect((await call('wide', 'get_page', { slug: PAGE_A })).text).toContain('canarydmalicepage');+ expect((await call('wide', 'get_page', { slug: PAGE_B }, BOB_ID)).text).toContain('canarydmbobpage');+ }, 120_000);++ test('query and search: unnamed reads span the grant minus other members\' personal sources', async () => {+ for (const op of ['query', 'search']) {+ const alice = await call('wide', op, { query: Q, limit: 20 });+ expect(alice.isError).toBe(false);+ expect(alice.text).toContain('canaryworldpage');+ expect(alice.text).toContain('canarydmalicepage');+ expect(alice.all).not.toContain('canarydmbobpage');+ const bob = await call('wide', op, { query: Q, limit: 20 }, BOB_ID);+ expect(bob.text).toContain('canarydmbobpage');+ expect(bob.all).not.toContain('canarydmalicepage');+ }+ }, 120_000);++ test('a linked member with no personal source reads neither DM source; unattested calls are unchanged', async () => {+ await linkMember(engine, 'carol-example', 'qm', 'U0CAROL');+ const carol = await recall('wide', 'U0CAROL');+ expect(carol.isError).toBe(false);+ for (const c of ['canarydmalice', 'canarydmbob']) expect(carol.all).not.toContain(c);+ const bare = await recall('wide', null);+ expect(bare.isError).toBe(false);+ for (const c of ['canarydmalice', 'canarydmbob']) expect(bare.text).toContain(c);+ expect((await call('wide', 'get_page', { slug: PAGE_B, source_id: DM_B }, null)).text).toContain('canarydmbobpage');+ }, 120_000);++ test('an agent job submitted for an attested person reads the same way: its own personal source, never another member\'s', async () => {+ const { clientId } = await provider().registerClientManual('personal-agent-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);+ await bindCredential(engine, { kind: 'client', id: clientId }, { attestActor: 'qm', attestOps: ['get_page', 'query'] });+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', bound_tools = ARRAY['get_page','query'], bound_source_id = source_id, federated_read = $2::text[], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 1 WHERE client_id = $1", [clientId, [SRC, DM_A, DM_B]]);+ const actor = { system: 'qm', external_id: ALICE_ID, member: 'alice-example' };+ const agentAuth = { token: 'x', clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC, DM_A, DM_B], principal: { kind: 'oauth_client', id: clientId } } as unknown as AuthInfo;+ const submitted = await withCallerAccess(await attestedCallerAccess(engine, actor, ['member:alice-example']),+ () => prepareRemoteAgent({ engine, auth: agentAuth, remote: true } as unknown as OperationContext, { source_id: SRC, allowed_tools: ['get_page', 'query'], allowed_slug_prefixes: [] }));+ const tools = buildBrainTools({ subagentId: 12, engine, config: { engine: 'pglite' } as never, sourceId: SRC,+ delegatedAuth: { clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC, DM_A, DM_B] } });+ const authority: RemoteAgentAuthority = { ...submitted, payloadHash: '0'.repeat(64) };+ const run = async (tool: string, input: Record<string, unknown>) => {+ try { return JSON.stringify(await withSubmissionAuthority(authority, () => tools.find(t => t.name === tool)!.execute(input, { engine, jobId: 1, remote: true } as never))); }+ catch (e) { return 'ERR ' + String((e as Error).message); }+ };+ expect(await run('brain_get_page', { slug: PAGE_A, source_id: DM_A })).toContain('canarydmalicepage');+ const theirs = await run('brain_get_page', { slug: PAGE_B, source_id: DM_B });+ expect(theirs).toContain('outside your granted sources');+ expect(theirs).not.toContain('canarydmbobpage');+ expect(await run('brain_get_page', { slug: PAGE_B })).not.toContain('canarydmbobpage');+ const found = await run('brain_query', { query: Q, limit: 20 });+ expect(found).toContain('canarydmalicepage');+ expect(found).not.toContain('canarydmbobpage');+ }, 120_000);++ test('a credential whose scalar source is another member\'s personal source neither reads nor writes there for the attested person: reads move to the kept grant, writes refuse', async () => {+ const memberPageIn = async (source: string, member: string) => Number((await engine.executeRaw<{ n: number | string }>(+ 'SELECT count(*) AS n FROM pages WHERE source_id = $1 AND slug = $2', [source, 'memory/members/' + member]))[0]!.n);+ const factsIn = async (source: string, canary: string) => Number((await engine.executeRaw<{ n: number | string }>(+ "SELECT count(*) AS n FROM facts WHERE source_id = $1 AND fact LIKE '%' || $2 || '%'", [source, canary]))[0]!.n);+ expect((await verify(clients.bobdm!)).sourceId).toBe(DM_B);+ const page = await call('bobdm', 'get_page', { slug: PAGE_B });+ expect(page.isError).toBe(true);+ expect(page.all).not.toContain('canarydmbobpage');+ const wrote = await call('bobdm', 'memory_write', { facts: [{ fact: 'Alice note on the harbor tide charts canaryscalaralice', provenance: 'turn 2' }], idempotency_key: randomUUID() }, ALICE_ID, { writeWaitMs: 30_000 });+ expect({ isError: wrote.isError, status: wrote.structured?.status }).toEqual({ isError: true, status: undefined });+ expect(wrote.json.code).toBe('permission_denied');+ expect({ page: await memberPageIn(DM_B, 'alice-example'), facts: await factsIn(DM_B, 'canaryscalaralice') }).toEqual({ page: 0, facts: 0 });+ expect((await call('bobdm', 'get_page', { slug: PAGE_B }, BOB_ID)).text).toContain('canarydmbobpage');++ const first = await call('bobfirst', 'get_page', { slug: PAGE_B });+ expect(first.json.code).toBe('page_not_found');+ expect(first.all).not.toContain('canarydmbobpage');+ expect((await call('bobfirst', 'get_page', { slug: 'notes/world-example' })).text).toContain('canaryworldpage');+ const moved = await call('bobfirst', 'memory_write', { facts: [{ fact: 'Alice second note on the harbor tide charts canaryscalarfirst', provenance: 'turn 3' }], idempotency_key: randomUUID() }, ALICE_ID, { writeWaitMs: 30_000 });+ expect({ isError: moved.isError, code: moved.json.code, status: moved.structured?.status }).toEqual({ isError: true, code: 'scope_denied', status: undefined });+ expect({ dm: await factsIn(DM_B, 'canaryscalarfirst'), src: await factsIn(SRC, 'canaryscalarfirst'), page: await memberPageIn(DM_B, 'alice-example') }).toEqual({ dm: 0, src: 0, page: 0 });+ expect((await recall('bobfirst', ALICE_ID)).text).toContain('canarymemberalice');+ }, 120_000);++ test('bindings: add is idempotent and previews with dryRun; remove previews, says when the source stops being personal, and applies with apply', async () => {+ expect(await bindMemberSource(engine, 'alice-example', DM_A)).toMatchObject({ applied: false, changed: false, owners: ['alice-example'] });+ expect(await bindMemberSource(engine, 'carol-example', DM_A, { dryRun: true })).toMatchObject({ applied: false, changed: true, owners: ['alice-example', 'carol-example'] });+ expect((await listMemberSources(engine)).map(b => [b.member_id, b.source_id])).toEqual([['alice-example', DM_A], ['bob-example', DM_B]]);+ expect((await listMemberSources(engine, { member: 'bob-example' })).map(b => b.source_id)).toEqual([DM_B]);+ await expect(bindMemberSource(engine, 'alice-example', 'source-missing')).rejects.toMatchObject({ code: 'unknown_source' });+ await expect(bindMemberSource(engine, 'nobody-example', DM_A)).rejects.toMatchObject({ code: 'access_member_invalid' });+ await expect(unbindMemberSource(engine, 'carol-example', DM_A)).rejects.toMatchObject({ code: 'invalid_params' });+ const preview = await unbindMemberSource(engine, 'bob-example', DM_B);+ expect(preview).toMatchObject({ applied: false, still_personal: false, owners: [] });+ expect((await listMemberSources(engine, { member: 'bob-example' })).length).toBe(1);+ await addMember(engine, 'dora-example');+ await bindMemberSource(engine, 'dora-example', DM_B);+ expect(await unbindMemberSource(engine, 'dora-example', DM_B, { apply: true })).toMatchObject({ applied: true, still_personal: true, owners: ['bob-example'] });+ await removeMember(engine, 'dora-example');+ await expect(bindMemberSource(engine, 'dora-example', DM_B)).rejects.toMatchObject({ code: 'access_member_invalid' });+ expect((await recall('wide', ALICE_ID)).all).not.toContain('canarydmbob');+ }, 120_000);+ });+}