Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Guest notes: refuse writes from a role that cannot read guest_sources, and close promotion, mark, init, doctor and docs gaps
garrytan275bced15f84
diff --git a/behavior-changes.d/guest_sources_scoped_role_fail_closed_9354.md b/behavior-changes.d/guest_sources_scoped_role_fail_closed_9354.mdnew file mode 100644index 0000000000..e2e9f1341d--- /dev/null+++ b/behavior-changes.d/guest_sources_scoped_role_fail_closed_9354.md@@ -0,0 +1 @@+Brains whose gbrain process connects to Postgres as a scoped row-level-security role now need that role to read the guest_sources table. Before, such a role read it as empty, so guest-source checks passed every write as if no source were a guest source. Now a role that row-level security keeps from reading guest_sources is refused with writer_coordinator_required (unreadable_state, state guest_sources) on page, fact, take and timeline writes, because it cannot tell a guest source from an ordinary one. The table owner, a role that bypasses row-level security, and PGLite brains are unaffected. To keep writing, give the scoped writer the SELECT policy on guest_sources from the maintainer recipe in docs/ENGINES.md (derived-state maintainers).diff --git a/changelog.d/garrytan-guest-notes-follow-ups.md b/changelog.d/garrytan-guest-notes-follow-ups.mdnew file mode 100644index 0000000000..0fa629067c--- /dev/null+++ b/changelog.d/garrytan-guest-notes-follow-ups.md@@ -0,0 +1,18 @@+**Guest notes now refuse writes from a database role that cannot see which sources are guest sources, and several smaller guest-note gaps from the first release are closed.**++A brain whose gbrain process connects to Postgres as a scoped row-level-security role used to read the guest source list as empty, so a write into a guest source passed as if the source were ordinary. Such a role is now refused with `writer_coordinator_required` until it can read `guest_sources` (one SELECT policy, added to the maintainer recipe in docs/ENGINES.md). The owner, a role that bypasses row-level security and PGLite brains see no change.++### Fixed+- Schema migration v314 re-creates the guest guard in the trust trigger and the guest-record guard so they refuse a role that row-level security keeps from reading `guest_sources`; guest admission, `remember`, links and remote deletes refuse the same way instead of treating the source as ordinary.+- `gbrain guests promote` no longer answers `already_promoted` when the kept page was purged: promoting again writes the page and keeps one link. v314 adds a unique index on the promotion link (a brain that already holds duplicate links keeps them, gets no index and a warning).+- A guest note whose mark writes no row now fails the save instead of committing a guest page with no mark.+- `gbrain guests init` counts the source's pages under the source row's lock, so no page can land between the check and the change.+- The repair `gbrain doctor` suggests for a source whose config says guest but has no guest record, `gbrain guests init --source <id> --yes`, now works when the source holds pages.+- A cycle phase skipped because the guest-source lookup failed now says the lookup failed (`reason: guest_source_lookup_failed`, with the error), instead of reporting a plain guest-source skip.+- A read the guest-note stamp cannot copy is refused, instead of marking the handler's own object.+- A page write on a brain whose schema is behind the guest-notes migration is refused `migrations_pending` instead of failing with a missing-table error.+- The owner-credential read behind `gbrain guests grant-owner-clients` and doctor's `guest_source` check no longer loads token hashes.+- `gbrain auth rescope --client <id>` with no grant flag now prints the client's operations and slug prefixes, and `gbrain delete --help` says `--expected-revision` is required unless `--force`.+- docs/guides/guest-notes.md gives the setup order that works (init, register the broker client, rescope its operations, then add it as a writer), and says that deletes need a revision or `--force` and that a put with attribution but no audience is refused `readable_by_invalid`.++<!-- behavior-change: guest_sources_scoped_role_fail_closed_9354 -->diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 74a1173443..1b5c502bf4 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -489,7 +489,10 @@ migration v281 (#7637) each refuses with `writer_coordinator_required` (relationnames the table) when row-level security applies to the role on a table it needs and no permissive policy for the rolecovers a command it runs there. Before, such a role kept stale derived state (a deleted page's retrieval rows stayed)or failed with a raw RLS error. The owner (without `FORCE ROW LEVEL SECURITY`) and a role that bypasses RLS are not-affected. A scoped write role that does not own these tables needs these policies; the maintainer tables hold ids,+affected. The guest-source guard in the trust trigger and guest admission read `guest_sources` the same way: since+migration v314 a role that row-level security keeps from reading it is refused (`writer_coordinator_required`,+`unreadable_state`, state `guest_sources`) on every page, fact, take and timeline write, because it cannot tell a guest+source from an ordinary one. A scoped write role that does not own these tables needs these policies; the maintainer tables hold ids,timestamps and counters but no page text, so the writer sees every row, and a policy that filters them would leave therows it hides stale:@@ -518,6 +521,9 @@ CREATE POLICY page_projection_jobs_writer ON page_projection_jobs FOR ALL TO <wrUSING (true) WITH CHECK (true);CREATE POLICY trust_policy_state_writer ON trust_policy_state FOR ALL TO <writer-role>USING (true) WITH CHECK (true);+-- Which sources are guest sources and who writes them: every row, read only.+CREATE POLICY guest_sources_writer ON guest_sources FOR SELECT TO <writer-role>+ USING (true);```<!-- gbrain:maintainer-rls-recipe:end -->diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.mdindex d6e26dbb68..0e049c716d 100644--- a/docs/guides/guest-notes.md+++ b/docs/guides/guest-notes.md@@ -42,24 +42,53 @@ Brains without a guest source are unchanged.## Set one up-Preview first. Nothing is written without `--yes`:--```bash-gbrain guests init --writer oauth_client:client-a-```--```text-Preview: gbrain guests init (nothing written; run again with --yes to apply)- Source "guests": will be created, database-only (no local path) and federated.- Trust ceiling: external_untrusted (no page there is ever stored above it).- Writers: oauth_client:client-a-```--Then apply it:--```bash-gbrain guests init --writer oauth_client:client-a --yes-```+The broker's OAuth client can only be registered on a source that already exists,+so create the source first, register the client, then put the client on the+writer list. Every `init` previews first and writes nothing without `--yes`.++1. Create the guest source with no writer yet:++ ```bash+ gbrain guests init+ gbrain guests init --yes+ ```++ ```text+ Preview: gbrain guests init (nothing written; run again with --yes to apply)+ Source "guests": will be created, database-only (no local path) and federated.+ Trust ceiling: external_untrusted (no page there is ever stored above it).+ Writers: none yet: nobody can save notes there until you add one (gbrain sources writers guests --add <oauth_client|legacy_token|local_cli|local_stdio|application>:<id>)+ ```++2. Register the broker's client on that source. The client secret is printed+ once, here only. `--may-act-for` lists the members and groups the broker may+ speak for:++ ```bash+ gbrain auth register-client guest-broker --grant-types client_credentials --scopes read,write \+ --source guests --federated-read guests --bound-slug-prefixes guests/ \+ --may-act-for bob-example,group:team-a+ ```++3. Limit the client to the operations a broker uses. `register-client` has no+ `--operations` flag, so this is a `rescope` (preview with `--dry-run`, then+ run it without):++ ```bash+ gbrain auth rescope --client <client id> --operations put_page,get_page,delete_page,get_write_request,get_brain_identity --dry-run+ ```++4. Put the client on the writer list:++ ```bash+ gbrain guests init --writer oauth_client:<client id>+ gbrain guests init --writer oauth_client:<client id> --yes+ ```++Plain `gbrain auth rescope --client <client id>` prints the client's operations+and slug prefixes but not who it may act for. `gbrain auth rescope --client+<client id> --json` prints the whole grant, and `gbrain access check --client+<client id>` prints "May act for" and the member it is bound to.The source is called `guests` unless you pass `--source <id>`. Running initagain on a guest source adds the new writers and keeps the old ones. If the@@ -67,11 +96,14 @@ source exists already, it must have no local path and hold no pages; init thenmarks it as a guest source. A source that already holds pages is refused, becauseevery page in a guest source would then read as a guest's words. Deleted pagesthat haven't been purged yet count too, because restoring one would bring it back-into the guest source.+into the guest source. The one exception is the repair `gbrain doctor` names: a+source whose config already says `guest: true` but has no guest source record+is fixed whatever it holds, because its pages already read as guest notes.-Before a brain that uses a scoped row-level-security write role turns guests on,-the guest guard and admission must check maintainer policies on guest_sources;-until then a scoped write role sees no guest rows and the checks fail open.+A brain whose writer connects as a scoped row-level-security role needs that+role to read `guest_sources`: without the policy in the+[maintainer recipe](../ENGINES.md#derived-state-maintainers), every write it makes+is refused with `writer_coordinator_required` instead of being let through.## Change who may write@@ -122,11 +154,20 @@ saved_at: 2026-11-13T10:00:00ZThe offsite moved to Friday.```+Every call names the audience, reads and deletes included. A `put_page` with+guest attribution but no audience is refused `readable_by_invalid`, because the+readers can't be checked against anyone.+A guest note is saved once, as a new page. Saving to a slug that exists isrefused `revision_required`, and `force`, `expected_revision`, `edit_page`,`append_page`, `add_timeline_entry`, `add_link`, `remember`, `put_raw_data`,`put_pages` and uploads are refused `guest_page_immutable`; a writer may delete the notesit saved, and deleting another writer's note is refused `permission_denied`.+A delete needs the note's revision: the broker passes `expected_revision` (from+`get_page`) to `delete_page`, and without it the delete is refused+`revision_required`. The same holds for your own `gbrain delete --source guests+-- <slug>`: pass `--expected-revision <revision>` (from `gbrain get --source guests+--json -- <slug>`) or `--force`.gbrain checks the writer list again when the note publishes, so a writer youremove in between is refused `source_writer_restricted`. Every refusal is in[write refusals](write-refusals.md#guest-source-refusals).diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 6963c72c1a..52f97984c8 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -59,7 +59,7 @@ of making a duplicate.| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: wait for the source's running sync owner (`gbrain serve`, autopilot or a sync job) to import the commit, which the refusal's read-only fix `gbrain sync status --source <source> --json` shows, then read the page again and resubmit with a new request ID. Neither refusal tells the caller to start a sync, because a second sync beside a running owner competes with it; when status shows no owner running, ask the user to sync the source on its host. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. With `persistence.refresh_barrier` on, a `put_page`, `capture`, `remember` or `add_timeline_entry` waits for the import instead of being refused ([deferred writes](#pending_import_expired)). || <a id="sync_write_through_off"></a>`sync_write_through_off` | `unavailable` (`forget` / `forget_fact`, detail `sync_write_through_off`) | `sync.write_through` is off and a canonical file carries the claim. The struck row would not reach the file, so a brain rebuilt from Git would bring the claim back; nothing was withdrawn. A claim that only database-only pages carry is still withdrawn. A sandboxed subagent's forget of such a claim refuses the same way with `scope_denied`, detail `subagent_sandbox`. | `gbrain config set sync.write_through true`, then forget the fact again; from a subagent sandbox, forget it from the main session. || <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. An owner purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted --older-than 72h --yes`) of such a page once it is soft-deleted writes no tombstone, so it removes the page row, its chunks, links and facts database-only and leaves the file and the surviving page untouched (#7311); a census that changed under it defers to the next run, which re-reads the claimants and, when the tombstone now owns the file alone, purges it normally, file included. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge of a live page, soft-delete it instead; a soft-deleted one is removed by the retention purge (a tombstone an older release parked after its refusals is retried once by the first purge run after the upgrade). After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. |-| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The exception is relationship `unreadable_state` (#7636), message "writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)": the database role gbrain connects as cannot fully read the writer state the guard reads, because row-level security hides the `persistence_brain` or `git_canonical_brain` row or the source or page row the write names, or row-level security applies to `sources` at all (the Git-canonical recount refuses then, even under a policy that shows every row), or a `persistence_brain` / `git_canonical_brain` row is missing. The guard refuses instead of letting the write through as if the brain were unmanaged or the row absent. A derived-state maintainer trigger raises the same refusal (#7637, raiser `gbrain_forget_page_retrievals`, `gbrain_queue_page_projection` and the others [listed in ENGINES.md](../ENGINES.md#derived-state-maintainers)) when row-level security applies to the role on a table it keeps up to date and the role holds no policy for it there, instead of leaving that derived state stale. The owner-only `error_detail.state` in `gbrain sources writer status --probe --json` names the table (`persistence_brain`, `git_canonical_brain`, `sources` or `pages`; #7780); the public receipt does not carry it. A `write_error_detail.sqlstate` of `42501` is a persistence protocol guard, not the managed-writer guard: see [protocol guard](#protocol-guard). The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. For relationship `unreadable_state` the build is not the cause, and the receipt's suggestion says so: run gbrain as a role that can read the table `error_detail.state` names (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows, though protocol activation and a change to which sources are Git-canonical pass only the first two; see [writer-protocol fences](../ENGINES.md#writer-protocol-fences), and for a maintainer's table the [policies a scoped writer needs](../ENGINES.md#derived-state-maintainers)), then retry with a **new** request ID; a missing row, which `gbrain init` never leaves, is reported like a defect. Never force-write, edit SQL or disable the guard. |+| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The exception is relationship `unreadable_state` (#7636), message "writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)": the database role gbrain connects as cannot fully read the writer state the guard reads, because row-level security hides the `persistence_brain` or `git_canonical_brain` row or the source or page row the write names, or row-level security applies to `sources` at all (the Git-canonical recount refuses then, even under a policy that shows every row), or a `persistence_brain` / `git_canonical_brain` row is missing. The guard refuses instead of letting the write through as if the brain were unmanaged or the row absent. A derived-state maintainer trigger raises the same refusal (#7637, raiser `gbrain_forget_page_retrievals`, `gbrain_queue_page_projection` and the others [listed in ENGINES.md](../ENGINES.md#derived-state-maintainers)) when row-level security applies to the role on a table it keeps up to date and the role holds no policy for it there, instead of leaving that derived state stale. The owner-only `error_detail.state` in `gbrain sources writer status --probe --json` names the table (`persistence_brain`, `git_canonical_brain`, `sources`, `pages` or, for the guest-source guard, `guest_sources`; #7780); the public receipt does not carry it. A `write_error_detail.sqlstate` of `42501` is a persistence protocol guard, not the managed-writer guard: see [protocol guard](#protocol-guard). The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. For relationship `unreadable_state` the build is not the cause, and the receipt's suggestion says so: run gbrain as a role that can read the table `error_detail.state` names (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows, though protocol activation and a change to which sources are Git-canonical pass only the first two; see [writer-protocol fences](../ENGINES.md#writer-protocol-fences), and for a maintainer's table the [policies a scoped writer needs](../ENGINES.md#derived-state-maintainers)), then retry with a **new** request ID; a missing row, which `gbrain init` never leaves, is reported like a defect. Never force-write, edit SQL or disable the guard. || <a id="protocol-guard"></a>`database_guard` with `write_error_detail.sqlstate` `42501` | `writer_upgrade_required`, `writer_not_quiesced`, `unsupported_mutation_protocol` or `writer_coordinator_required` | A persistence protocol guard (`write_error_detail.raiser`: `gbrain_require_persistence_protocol`, `gbrain_guard_request_protocol`, `gbrain_guard_effect_protocol`, `gbrain_guard_protocol_activation` or `gbrain_guard_skill_publication`) refused a row while a write was published, so nothing was committed (#7777). The error code is the guard's own: `writer_upgrade_required` (the gbrain process that ran the write does not declare the protocol the brain's floor requires: an older gbrain), `writer_not_quiesced` (shared skill publication is not active, or the canonical owner's protocol-2 capability changed after activation), `unsupported_mutation_protocol` (a request's target or protocol does not fit its operation), or `writer_coordinator_required`, either with relationship `unreadable_state` (the role gbrain connects as cannot read the `persistence_brain` writer state: row-level security hides it, or the row is missing; owner-only `error_detail.state` is `persistence_brain`) or without it (a shared-skill row outside the coordinated source capability). Only a guard's exact diagnostic, raised by that guard's own function, is typed; any other 42501 stays an ordinary permission error. Outside publication (write admission, protocol activation) the same refusal reaches the command as the database error itself, `Error [database_error]: <code>: <diagnostic>`, followed by the generic `permission_denied` grant advice; the code at the start of the message is the refusal. | Follow the receipt's suggestion. `unreadable_state`: upgrading does not help; run gbrain as a role that can read `persistence_brain` (the table owner, a role that bypasses RLS, or a scoped role with a `SELECT` policy on it), then retry with a **new** request ID. Protocol activation, like a change to which sources are Git-canonical, passes only the table owner (without `FORCE ROW LEVEL SECURITY`) or a role that bypasses RLS. `writer_upgrade_required`: compare `recent_failures[].error_detail.attempt.consumer_version` from `gbrain sources writer status --probe --json` with `gbrain --version`, upgrade or restart every older gbrain process sharing the database, then retry with a new request ID; never lower the protocol floor. `writer_not_quiesced`: see [writer_not_quiesced](#writer_not_quiesced). `unsupported_mutation_protocol` and the skill-capability case: upgrade or restart older processes and submit again with a new request ID, and report `error_detail` on the gbrain issue tracker if the builds match. Never edit SQL or disable the guard. || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. || <a id="owner_marker_missing"></a>`owner_marker_missing` | `owner_marker_missing` | The ownership marker `.gbrain-owner.json` is gone from the checkout root while the reservation beside the checkout still names this owner and identifies this exact directory: device, inode and birth time all equal (a cleanup or a restore that dropped dotfiles). A directory the reservation does not identify exactly, a birth time within the 1 µs tolerance included, keeps the generic `recovery_required` and its [recreated-root](#recreated-root) exit. No write publishes there, and a retry never brings the marker back, so the owner finishes each refused write `failed` (its outstanding-request slot is released); a sync stops `blocked_by_failures` on the refused file, without a hold. | Re-create the marker with the verified self-transfer on the brain host: `gbrain sources writer status --source <source> --json` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Then run the same `gbrain sync` again. Never create or copy the marker by hand. |diff --git a/llms-full.txt b/llms-full.txtindex 3b4ab9febb..832556f491 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5245,7 +5245,10 @@ migration v281 (#7637) each refuses with `writer_coordinator_required` (relationnames the table) when row-level security applies to the role on a table it needs and no permissive policy for the rolecovers a command it runs there. Before, such a role kept stale derived state (a deleted page's retrieval rows stayed)or failed with a raw RLS error. The owner (without `FORCE ROW LEVEL SECURITY`) and a role that bypasses RLS are not-affected. A scoped write role that does not own these tables needs these policies; the maintainer tables hold ids,+affected. The guest-source guard in the trust trigger and guest admission read `guest_sources` the same way: since+migration v314 a role that row-level security keeps from reading it is refused (`writer_coordinator_required`,+`unreadable_state`, state `guest_sources`) on every page, fact, take and timeline write, because it cannot tell a guest+source from an ordinary one. A scoped write role that does not own these tables needs these policies; the maintainer tables hold ids,timestamps and counters but no page text, so the writer sees every row, and a policy that filters them would leave therows it hides stale:@@ -5274,6 +5277,9 @@ CREATE POLICY page_projection_jobs_writer ON page_projection_jobs FOR ALL TO <wrUSING (true) WITH CHECK (true);CREATE POLICY trust_policy_state_writer ON trust_policy_state FOR ALL TO <writer-role>USING (true) WITH CHECK (true);+-- Which sources are guest sources and who writes them: every row, read only.+CREATE POLICY guest_sources_writer ON guest_sources FOR SELECT TO <writer-role>+ USING (true);```<!-- gbrain:maintainer-rls-recipe:end -->diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 0da8df27c3..886c642022 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -939,7 +939,7 @@ async function rescopeClientWith(engine: BrainEngine, clientId: string, parsed:function printClientGrantAxes(grant: ClientGrant) {console.log(` Scopes: ${grant.scopes.join(' ') || '<none>'}`);console.log(` Write source: ${grant.sourcesNone ? 'none (every read and write refused)' : grant.sourceId}`);- console.log(` Federated reads: ${grant.federatedRead.join(', ') || '<none>'}`);+ console.log(` Federated reads: ${grant.federatedRead.join(', ') || '<none>'}\n Operations: ${grant.allowedOperations === null ? 'all (no snapshot)' : grant.allowedOperations.join(', ') || 'none'}\n Slug prefixes: ${grant.boundSlugPrefixes?.join(', ') || '<none>'}`);console.log(` Takes holders: ${grant.takesHolders === null ? 'world (default)' : grant.takesHolders.join(', ') || 'none (every take hidden)'}`);console.log(` Private pages: ${renderPrivatePages(grant.privatePages)}`);console.log(` Tool surface: ${grant.surface ?? '<server default>'}`);diff --git a/src/commands/doctor/checks/guest-source.ts b/src/commands/doctor/checks/guest-source.tsindex 4e705c0e04..922ed1a200 100644--- a/src/commands/doctor/checks/guest-source.ts+++ b/src/commands/doctor/checks/guest-source.ts@@ -18,7 +18,7 @@ import { connectedEngine, type DoctorContext, type DoctorEntry } from '../conteximport { authSourcesFromGrant, grantFromClient, grantFromRow, grantFromTokenRow } from '../../../core/grants/model.ts';import { guestSourceSql } from '../../../core/guests/marker.ts';import { GUEST_TRUST_CEILING } from '../../../core/guests/sources.ts';-import { ownerCredentials } from '../../../core/guests/owner-credentials.ts';+import { ownerCredentials, tokenGrantJsonSql } from '../../../core/guests/owner-credentials.ts';import { GUEST_NOTES_MIGRATION } from '../../../core/guests/migration.ts';import { isMissingSchemaObject } from '../../../core/utils.ts';@@ -34,7 +34,7 @@ async function writerFindings(engine: BrainEngine, source: string, writer: strinif (kind !== 'oauth_client' && kind !== 'legacy_token') return [{ level: 'warn', text: 'writer ' + writer + ' is not a remote credential (only an OAuth client or token can be a broker)' }];const [row] = kind === 'oauth_client'? await engine.executeRaw<{ row: unknown; live: boolean }>("SELECT to_jsonb(c) - 'client_secret_hash' AS row, (to_jsonb(c)->>'deleted_at') IS NULL AS live FROM oauth_clients c WHERE c.client_id = $1", [id])- : await engine.executeRaw<{ row: unknown; live: boolean }>('SELECT to_jsonb(t) AS row, t.revoked_at IS NULL AS live FROM access_tokens t WHERE t.id::text = $1', [id]);+ : await engine.executeRaw<{ row: unknown; live: boolean }>('SELECT ' + tokenGrantJsonSql('t') + ' AS row, t.revoked_at IS NULL AS live FROM access_tokens t WHERE t.id::text = $1', [id]);const drop = ['gbrain', 'sources', 'writers', source, '--remove', writer];if (!row || !row.live) return [{ level: 'fail', text: 'writer ' + writer + (row ? ' was removed or revoked' : ' names no credential'), fix: drop }];const grant = kind === 'oauth_client' ? grantFromClient(grantFromRow(json(row.row))) : grantFromTokenRow(json(row.row));diff --git a/src/commands/guests.ts b/src/commands/guests.tsindex c2ad034d24..d59f60f541 100644--- a/src/commands/guests.ts+++ b/src/commands/guests.ts@@ -6,7 +6,7 @@*/import type { BrainEngine } from '../core/engine.ts';import { isValidSourceId } from '../core/source-id.ts';-import { GUEST_TRUST_CEILING, GUEST_WRITER_FORMAT, initGuestSource, isGuestWriter, planGuestSource } from '../core/guests/sources.ts';+import { GUEST_TRUST_CEILING, GUEST_WRITER_FORMAT, GuestSourceHoldsPages, initGuestSource, isGuestWriter, planGuestSource } from '../core/guests/sources.ts';import { grantOwnerCredentials, ownerCredentials } from '../core/guests/owner-credentials.ts';import { exitCliError } from '../cli/cli-error.ts';import { loadConfig } from '../core/config.ts';@@ -86,24 +86,27 @@ async function runInit(engine: BrainEngine, rest: string[]): Promise<void> {console.error(`Source "${sourceId}" has a local path (${plan.localPath}). A guest source is database-only, so gbrain will not make this one a guest source. Pick another name with --source.`);process.exit(2);}- if (plan.exists && !plan.guest) {- const [held] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1', [sourceId]);- if (Number(held?.n ?? 0) > 0) {- console.error(`Source "${sourceId}" already holds ${held!.n} page(s), counting deleted pages not yet purged (a restore would bring them back). Every page in a guest source reads as an outside guest's words and only listed writers can change it, so gbrain will not make this one a guest source. Pick another name with --source.`);- process.exit(2);- }+ if (plan.pages > 0) {+ console.error(new GuestSourceHoldsPages(sourceId, plan.pages).message);+ process.exit(2);}const writerLine = (list: readonly string[]) => list.length > 0 ? list.join(', '): `none yet: nobody can save notes there until you add one (gbrain sources writers ${sourceId} --add ${GUEST_WRITER_FORMAT})`;if (!yes) {console.log('Preview: gbrain guests init (nothing written; run again with --yes to apply)');console.log(` Source "${sourceId}": ${!plan.exists ? 'will be created, database-only (no local path) and federated'- : plan.guest ? 'is already a guest source' : 'exists with no local path; it becomes a guest source and is federated'}.`);+ : plan.guest ? 'is already a guest source' : plan.configGuest ? 'says guest: true in its config but has no guest_sources row; init adds it, so its writer list and ceiling are enforced'+ : 'exists with no local path; it becomes a guest source and is federated'}.`);console.log(` Trust ceiling: ${GUEST_TRUST_CEILING} (no page there is ever stored above it).`);console.log(` Writers: ${writerLine(plan.writers)}`);return;}- const guest = await initGuestSource(engine, sourceId, writers);+ let guest: Awaited<ReturnType<typeof initGuestSource>>;+ try { guest = await initGuestSource(engine, sourceId, writers); } catch (e) {+ if (!(e instanceof GuestSourceHoldsPages)) throw e;+ console.error(e.message);+ process.exit(2);+ }console.log(`Source "${sourceId}" is ${plan.exists ? 'now' : 'created as'} a guest source: database-only, federated, trust ceiling ${guest.trust_ceiling}.`);console.log(` Writers: ${writerLine(guest.writers)}`);}diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 9012621910..801399a070 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1917,10 +1917,13 @@ const notifyPhaseStart = (opts: CycleOpts, phase: CyclePhase, phases: readonly C/** GBRA-504: a cycle scoped to a guest source skips every phase that would derive rows from guest pages (guests/derived.ts); each is reported skipped. */async function withoutGuestPhases(engine: BrainEngine | null, sourceId: string | undefined, phases: CyclePhase[], phaseResults: PhaseResult[]): Promise<CyclePhase[]> {- if (!engine || !sourceId || !await (await import('./guests/note.ts')).isGuestSource(engine, sourceId)) return phases;+ if (!engine || !sourceId) return phases;+ const { guestSourceVerdict, guestSkipDetails } = await import('./guests/note.ts');+ const verdict = await guestSourceVerdict(engine, sourceId);+ if (!verdict.guest) return phases;+ const { summary, details } = guestSkipDetails(sourceId, verdict.lookupError);const guestSkipped = new Set((await import('./guests/derived.ts')).guestSkippedPhases());- for (const phase of phases.filter(p => guestSkipped.has(p))) phaseResults.push({ phase, status: 'skipped', duration_ms: 0,- summary: 'skipped on a guest source: guest notes feed no derived rows', details: { reason: 'guest_source', source_id: sourceId } });+ for (const phase of phases.filter(p => guestSkipped.has(p))) phaseResults.push({ phase, status: 'skipped', duration_ms: 0, summary: `skipped: ${summary}`, details });return phases.filter(p => !guestSkipped.has(p));}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 792230e5ae..bc044b205c 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -709,9 +709,8 @@ export async function runPhaseExtractAtoms(opts: ExtractAtomsOpts = {},): Promise<PhaseResult> {const sourceId = opts.sourceId ?? 'default';- if (await (await import('../guests/derived.ts')).skipsGuestSource(engine, 'extract_atoms', sourceId)) {- return { phase: 'extract_atoms', status: 'skipped', duration_ms: 0, summary: 'extract_atoms: a guest source is never extracted', details: { reason: 'guest_source', source_id: sourceId } };- }+ const guestSkip = await (await import('../guests/derived.ts')).guestSourceSkip(engine, 'extract_atoms', sourceId);+ if (guestSkip) return { phase: 'extract_atoms', status: 'skipped', duration_ms: 0, summary: `extract_atoms: ${guestSkip.summary}`, details: guestSkip.details };const chat = opts._chat ?? gatewayChat;const managed = await managedAtomSession(engine, sourceId, opts._managedRetry, opts.attempt?.writeWait, opts.signal);// v0.41.2.1: loadConfigWithEngine() so the dream.* DB-plane merge from Phase 1 reaches this phase.diff --git a/src/core/guests/admission.ts b/src/core/guests/admission.tsindex 435f6d3817..02b6619be4 100644--- a/src/core/guests/admission.ts+++ b/src/core/guests/admission.ts@@ -17,7 +17,9 @@ import { normalizeReaders } from '../access/principals.ts';import { ownerMemberId } from '../access/owner.ts';import type { Principal } from '../persistence/model.ts';import type { GuestSource } from './sources.ts';-import type { GuestAttribution } from './note.ts';+import { GUEST_SOURCES_HIDDEN_SQL, type GuestAttribution } from './note.ts';+import { schemaAdmissionRefusal } from '../persistence/schema-admission.ts';+import { isMissingSchemaObject } from '../utils.ts';export { GUEST_NOTE_INTENT_KEY, type GuestAttribution } from './note.ts';@@ -65,6 +67,39 @@ export function parseGuestAttribution(channels: GuestChannels | undefined): Guesreturn fromMeta ?? fromHeader;}+/** A lookup of guest_sources by a role that row-level security keeps from reading it (GUEST_SOURCES_HIDDEN_SQL). */+export function guestSourcesUnreadable(sourceId: string): OperationError {+ return new OperationError('writer_coordinator_required',+ `writer_coordinator_required: writer state is unreadable to this database role: row-level security hides guest_sources, so gbrain cannot tell whether source ${sourceId} is a guest source. Nothing was written.`,+ 'Run gbrain as a database role that can read guest_sources (the table owner, a role that bypasses row-level security, or a scoped write role holding the guest_sources SELECT policy in docs/ENGINES.md#derived-state-maintainers), then retry with a new request ID.',+ 'docs/guides/write-refusals.md#writer-coordinator-required');+}++/**+ * A guest-table read that failed: on a brain whose schema is behind the guest-notes migration (no guest_sources table)+ * the write is refused migrations_pending (schema-admission.ts), as admission refuses any write on a schema behind this+ * build, instead of failing with the raw missing-table error. Any other error is rethrown.+ */+export async function schemaBehindGuests(exec: Pick<BrainEngine, 'executeRaw'>, error: unknown): Promise<never> {+ if (isMissingSchemaObject(error, 'table', 'guest_sources')) {+ const refusal = await schemaAdmissionRefusal(exec as BrainEngine);+ if (refusal) throw refusal;+ }+ throw error;+}++/**+ * The guest_sources row of `sourceId`, or null when it is not a guest source. One statement; refuses+ * (guestSourcesUnreadable) when row-level security hides guest_sources from the role instead of answering null.+ */+export async function lookupGuestSource(exec: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<GuestSource | null> {+ const [row] = await exec.executeRaw<GuestSource & { hidden: boolean }>(+ `SELECT ${GUEST_SOURCES_HIDDEN_SQL} AS hidden, g.source_id, g.writers, g.trust_ceiling FROM (SELECT 1) AS one LEFT JOIN guest_sources g ON g.source_id = $1`, [sourceId])+ .catch(e => schemaBehindGuests(exec, e));+ if (row?.hidden) throw guestSourcesUnreadable(sourceId);+ return row?.source_id ? { source_id: row.source_id, writers: row.writers, trust_ceiling: row.trust_ceiling } : null;+}+export function sourceWriterRestricted(sourceId: string): OperationError {return new OperationError('source_writer_restricted', `Source ${sourceId} is a guest source: only its listed writers create pages there, and nothing else writes to it. Nothing was written.`,"Do not retry. Write to another source, or ask the brain owner whether this content belongs in the guest source; changing who may write there is the owner's decision.",@@ -92,9 +127,11 @@ export function guestNoteNotYours(slug: string): OperationError {* mark names another writer than `principal` (a writer deletes only what it saved). Checked at submission and in publication.*/export async function refuseRemoteGuestDelete(exec: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string, principal: Principal): Promise<void> {- const [page] = await exec.executeRaw<{ guest: boolean; kept: boolean; writer: string | null }>(- `SELECT EXISTS (SELECT 1 FROM guest_sources g WHERE g.source_id = p.source_id) AS guest, EXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = p.id) AS kept,- (SELECT m.writer_kind || ':' || m.writer_id FROM guest_marks m WHERE m.page_id = p.id) AS writer FROM pages p WHERE p.source_id = $1 AND p.slug = $2 LIMIT 1`, [sourceId, slug]);+ const [page] = await exec.executeRaw<{ hidden: boolean; guest: boolean; kept: boolean; writer: string | null }>(+ `SELECT ${GUEST_SOURCES_HIDDEN_SQL} AS hidden, EXISTS (SELECT 1 FROM guest_sources g WHERE g.source_id = p.source_id) AS guest, EXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = p.id) AS kept,+ (SELECT m.writer_kind || ':' || m.writer_id FROM guest_marks m WHERE m.page_id = p.id) AS writer FROM pages p WHERE p.source_id = $1 AND p.slug = $2 LIMIT 1`, [sourceId, slug])+ .catch(e => schemaBehindGuests(exec, e));+ if (page?.hidden) throw guestSourcesUnreadable(sourceId);if (!page?.guest && !page?.kept) return;if (page.kept) throw guestPagePromoted(slug);if (page.writer !== principalKey(principal)) throw guestNoteNotYours(slug);@@ -126,7 +163,7 @@ export function admitGuestOperation(guest: GuestSource, input: { principal: Prin/** Refuses any write other than a page through admitGuestOperation (remember, links, import) on a guest source. */export async function refuseGuestSourceWrite(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, principalOf: () => Promise<Principal>, operation: string): Promise<void> {- const [guest] = await engine.executeRaw<{ writers: string[] }>('SELECT writers FROM guest_sources WHERE source_id = $1', [sourceId]);+ const guest = await lookupGuestSource(engine, sourceId);if (!guest) return;if (isListedWriter(guest, await principalOf())) throw guestPageImmutable(`${operation} on a guest source`);throw sourceWriterRestricted(sourceId);@@ -178,10 +215,17 @@ export async function assertGuestWriterAtPublication(tx: Pick<BrainEngine, 'execif (!guest || !guest.writers.includes(`${row.principal_kind}:${row.principal_id}`)) throw sourceWriterRestricted(row.source_id);}-/** The guest mark, written in the publication transaction right after the page row. */+/**+ * The guest mark, written in the publication transaction right after the page row. A mark that writes no row (the page+ * row is not there to mark) throws, so the publication rolls back instead of leaving a guest page with no mark.+ */export async function insertGuestMark(tx: Pick<BrainEngine, 'executeRaw'>, row: { source_id: string; slug: string; principal_kind: string; principal_id: string; request_id: string },note: GuestAttribution, audience: string): Promise<void> {- await tx.executeRaw(`INSERT INTO guest_marks (page_id, source_id, slug_at_write, audience_member, group_slug, sender_label, saved_at, writer_kind, writer_id, request_id)- SELECT p.id, p.source_id, p.slug, $3, $4, $5, now(), $6, $7, $8 FROM pages p WHERE p.source_id = $1 AND p.slug = $2`,+ const marked = await tx.executeRaw(`INSERT INTO guest_marks (page_id, source_id, slug_at_write, audience_member, group_slug, sender_label, saved_at, writer_kind, writer_id, request_id)+ SELECT p.id, p.source_id, p.slug, $3, $4, $5, now(), $6, $7, $8 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 RETURNING page_id`,[row.source_id, row.slug, audience, note.group, note.sender_label, row.principal_kind, row.principal_id, row.request_id]);+ if (marked.length !== 1) {+ throw new OperationError('storage_error', `The guest mark for ${row.slug} wrote ${marked.length} rows instead of one, so the guest note was not saved. Nothing was written.`,+ 'Retry the save with a new request_id; if it fails the same way, run gbrain doctor --json on the brain host and report the result.');+ }}diff --git a/src/core/guests/derived.ts b/src/core/guests/derived.tsindex 46e778d703..25a6b67e74 100644--- a/src/core/guests/derived.ts+++ b/src/core/guests/derived.ts@@ -8,7 +8,7 @@*/import type { BrainEngine } from '../engine.ts';import type { CyclePhase } from '../cycle.ts';-import { guestSourceSql, isGuestSource, readGuestSourceIds, storedGuestNote } from './note.ts';+import { guestSkipDetails, guestSourceSql, guestSourceVerdict, readGuestSourceIds, storedGuestNote } from './note.ts';export type GuestDerivedProducer = CyclePhase | 'publication_projections' | 'auto_links' | 'remote_links_effect' | 'facts_backstop' | 'think_writeback';type GuestDerivedEntry = { guest: 'skip'; sites: readonly string[] } | { guest: 'none'; reason: string };@@ -73,7 +73,14 @@ export function guestSkippedPhases(): CyclePhase[] {/** True when `producer` skips `sourceId` because it is a guest source, or because the lookup failed. */export async function skipsGuestSource(engine: Pick<BrainEngine, 'executeRaw'>, producer: GuestSkipProducer, sourceId: string): Promise<boolean> {- return skips(producer) && isGuestSource(engine, sourceId);+ return (await guestSourceSkip(engine, producer, sourceId)) !== null;+}++/** Why `producer` skips `sourceId` (guestSkipDetails: a guest source, or a lookup that failed), or null when it runs. */+export async function guestSourceSkip(engine: Pick<BrainEngine, 'executeRaw'>, producer: GuestSkipProducer, sourceId: string): Promise<ReturnType<typeof guestSkipDetails> | null> {+ if (!skips(producer)) return null;+ const verdict = await guestSourceVerdict(engine, sourceId);+ return verdict.guest ? guestSkipDetails(sourceId, verdict.lookupError) : null;}/**diff --git a/src/core/guests/note.ts b/src/core/guests/note.tsindex d23bf2c5e6..486e6d94d9 100644--- a/src/core/guests/note.ts+++ b/src/core/guests/note.ts@@ -24,6 +24,16 @@ export function storedGuestNote(intent: Record<string, unknown> | null | undefinexport const guestSourceSql = (config: string, id: string) =>`(COALESCE(${config}->>'guest' = 'true', false) OR EXISTS (SELECT 1 FROM guest_sources gs WHERE gs.source_id = ${id}))`;+/**+ * SQL true when row-level security keeps the current database role from reading guest_sources: it applies to the role+ * and no permissive SELECT policy covers it, the test the trust trigger's guest guard refuses on (trust/schema.ts,+ * derived-state-maintainers.ts requireMaintainerPoliciesSql). Such a role reads guest_sources empty, so every lookup+ * that reads it reads this too and refuses instead of treating a guest source as ordinary (follow-up 3 of #9354).+ */+export const GUEST_SOURCES_HIDDEN_SQL = `(pg_catalog.row_security_active('guest_sources') AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_policy p`+ + ` WHERE p.polrelid = 'guest_sources'::regclass::oid AND p.polpermissive AND p.polcmd::text IN ('*', 'r')`+ + ` AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id) WHERE CASE WHEN r.id = 0::oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END)))`;+/** The guest sources among `sourceIds`, by guestSourceSql. Throws when the lookup fails (a schema behind the guest-notes migration included). */export async function readGuestSourceIds(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds: readonly string[]): Promise<Set<string>> {if (sourceIds.length === 0) return new Set();@@ -31,7 +41,22 @@ export async function readGuestSourceIds(engine: Pick<BrainEngine, 'executeRaw'>return new Set(rows.map(row => row.id));}+/** Whether `sourceId` is a guest source; a lookup that failed answers guest, with its error, so a caller can say it failed. */+export async function guestSourceVerdict(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<{ guest: boolean; lookupError?: string }> {+ try { return { guest: (await readGuestSourceIds(engine, [sourceId])).has(sourceId) }; } catch (e) {+ return { guest: true, lookupError: e instanceof Error ? e.message : String(e) };+ }+}+/** For a derived producer: true when `sourceId` is a guest source, or when that cannot be told (the lookup failed). */export async function isGuestSource(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<boolean> {- try { return (await readGuestSourceIds(engine, [sourceId])).has(sourceId); } catch { return true; }+ return (await guestSourceVerdict(engine, sourceId)).guest;+}++/** The skip a cycle phase reports on `sourceId`: a guest source, or a guest lookup that failed, named as such. */+export function guestSkipDetails(sourceId: string, lookupError: string | undefined): { summary: string; details: Record<string, unknown> } {+ return lookupError === undefined+ ? { summary: 'a guest source feeds no derived rows', details: { reason: 'guest_source', source_id: sourceId } }+ : { summary: 'could not tell whether the source is a guest source (the lookup failed), so it was treated as one',+ details: { reason: 'guest_source_lookup_failed', source_id: sourceId, error: lookupError } };}diff --git a/src/core/guests/owner-credentials.ts b/src/core/guests/owner-credentials.tsindex e094d18d18..c9b28882cb 100644--- a/src/core/guests/owner-credentials.ts+++ b/src/core/guests/owner-credentials.ts@@ -12,7 +12,7 @@*/import type { BrainEngine } from '../engine.ts';import { ownerMemberId } from '../access/owner.ts';-import { GrantError, grantFromClient, grantFromRow, grantFromTokenRow, type PrincipalGrant } from '../grants/model.ts';+import { GrantError, grantFromClient, grantFromRow, grantFromTokenRow, TOKEN_GRANT_ROW_COLUMNS, type PrincipalGrant } from '../grants/model.ts';import { readClientGrant, rescopeClientGrant } from '../grants/service.ts';import { rescopeLegacyToken } from '../grants/legacy-token.ts';import { compareTrust, storedMinTrust, type TrustTier } from '../trust/tier.ts';@@ -60,6 +60,9 @@ function credential(kind: 'client' | 'token', id: string, name: string, g: PrincminTrust, floorHidesGuests: minTrust !== null && compareTrust(minTrust, 'external_untrusted') > 0 };}+/** An access_tokens row as JSON with only the columns a grant and its read floor need: never the token hash. */+export const tokenGrantJsonSql = (alias: string) => `jsonb_build_object(${[...TOKEN_GRANT_ROW_COLUMNS, 'min_trust'].map(c => `'${c}', ${alias}.${c}`).join(', ')})`;+const json = (v: unknown) => (typeof v === 'string' ? JSON.parse(v) : v) as Record<string, unknown>;/** Every live credential bound to the brain owner, read against guest source guestSourceId; no owner, no credentials. */@@ -67,7 +70,7 @@ export async function ownerCredentials(engine: BrainEngine, guestSourceId: strinconst owner = await ownerMemberId(engine);if (!owner) return { owner, credentials: [] };const rows = await engine.executeRaw<{ kind: 'client' | 'token'; id: string; name: string; row: unknown }>(- "SELECT 'token' AS kind, t.id::text AS id, t.name, to_jsonb(t) AS row FROM access_tokens t WHERE t.member_id = $1 AND t.revoked_at IS NULL "+ "SELECT 'token' AS kind, t.id::text AS id, t.name, " + tokenGrantJsonSql('t') + " AS row FROM access_tokens t WHERE t.member_id = $1 AND t.revoked_at IS NULL "+ "UNION ALL SELECT 'client' AS kind, c.client_id AS id, COALESCE(c.client_name, c.client_id) AS name, to_jsonb(c) - 'client_secret_hash' AS row "+ "FROM oauth_clients c WHERE c.member_id = $1 AND (to_jsonb(c)->>'deleted_at') IS NULL ORDER BY 1, 3, 2", [owner]);return { owner, credentials: rows.map(r => {diff --git a/src/core/guests/promote.ts b/src/core/guests/promote.tsindex d7ebb9aa41..cbbd2f248e 100644--- a/src/core/guests/promote.ts+++ b/src/core/guests/promote.ts@@ -6,7 +6,9 @@* config access.owner_member, speaking for no one else). Everyone else is refused guest_promotion_owner_only before* anything is read. The owner page is a normal put_page through the caller's own write path (git first where the target* source has a repository, database-only where it has none), carrying the guest note's type, title, body and readers- * plus 'promoted_from: <guest source>:<slug>' for people reading it. The link itself lives in guest_promotions, which+ * plus 'promoted_from: <guest source>:<slug>' for people reading it. The link itself lives in guest_promotions (one row+ * per guest page and target; a link whose target page was purged no longer counts as kept, and promoting again rewrites+ * the page and that one link), which* guest rows read as guest.promoted (guests/marker.ts), and which refuses the broker's delete of the note* (guests/admission.ts refuseRemoteGuestDelete). The guest page and its mark are never changed.*/@@ -72,8 +74,8 @@ export async function promoteGuestNote(ctx: OperationContext, p: Record<string,}const target = (text(p.to, 'to') ?? slug).toLowerCase();const result = { guest: { source_id: note.source_id, slug }, page: { source_id: targetSource, slug: target } };- const [kept] = await ctx.engine.executeRaw('SELECT 1 FROM guest_promotions WHERE guest_page_id = $1 AND target_source_id = $2 AND target_slug = $3',- [note.id, targetSource, target]);+ const [kept] = await ctx.engine.executeRaw(`SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = $1 AND g.target_source_id = $2 AND g.target_slug = $3+ AND EXISTS (SELECT 1 FROM pages t WHERE t.source_id = g.target_source_id AND t.slug = g.target_slug)`, [note.id, targetSource, target]);if (kept) return { status: 'already_promoted', ...result };const page = await ctx.engine.getPage(slug, { sourceId: note.source_id });if (!page) throw new OperationError('page_not_found', 'Guest note ' + slug + ' was deleted while it was promoted; nothing was written.', 'Ask the brain owner to restore it, then promote it again.');@@ -84,8 +86,10 @@ export async function promoteGuestNote(ctx: OperationContext, p: Record<string,if (ctx.dryRun) return { dry_run: true, status: 'would_promote', ...result };const link = async (requestId: unknown) => {const by = await requestPrincipalForContext(ctx);- await ctx.engine.executeRaw(- 'INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id, request_id) VALUES ($1, $2, $3, $4, $5, $6)',+ await ctx.engine.executeRaw(`WITH relinked AS (UPDATE guest_promotions SET promoted_by_kind = $4, promoted_by_id = $5, promoted_at = now(), request_id = $6+ WHERE guest_page_id = $1 AND target_source_id = $2 AND target_slug = $3 RETURNING id)+ INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id, request_id)+ SELECT $1, $2, $3, $4, $5, $6 WHERE NOT EXISTS (SELECT 1 FROM relinked)`,[note.id, targetSource, target, by.kind, by.id, typeof requestId === 'string' ? requestId : null]);};const written = await ctx.engine.getPage(target, { sourceId: targetSource });diff --git a/src/core/guests/schema.ts b/src/core/guests/schema.tsindex 7ab310469c..64ae324a48 100644--- a/src/core/guests/schema.ts+++ b/src/core/guests/schema.ts@@ -14,16 +14,24 @@* A guest source is database-only: gbrain_guard_guest_records refuses a* local_path on it, and refuses listing a source that has one.*/+import { requireMaintainerPoliciesSql } from '../derived-state-maintainers.ts';import { TRUST_TIERS } from '../trust/tier.ts';export const GUEST_RECORD_TABLES = ['guest_sources', 'guest_marks', 'guest_promotions'] as const;-const GUARD_FUNCTION = `CREATE OR REPLACE FUNCTION gbrain_guard_guest_records() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$+/**+ * `failClosed` (follow-up 3 of #9354; the guest-notes migration installed the body without it) refuses a path change on+ * a source by a role that row-level security keeps from reading guest_sources, instead of reading it empty.+ */+const guardFunction = (failClosed: boolean) => `CREATE OR REPLACE FUNCTION gbrain_guard_guest_records() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$BEGINIF TG_TABLE_NAME = 'guest_marks' THENRAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='guest_mark_immutable: a guest mark is never changed; it leaves only with its page',TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='guest_source_guard';- ELSIF TG_TABLE_NAME = 'sources' THEN+ ELSIF TG_TABLE_NAME = 'sources' THEN${failClosed ? `+ IF NEW.local_path IS NOT NULL THEN+ ${requireMaintainerPoliciesSql('guest_sources', ['SELECT'], ' ')}+ END IF;` : ''}IF NEW.local_path IS NOT NULL AND EXISTS (SELECT 1 FROM guest_sources g WHERE g.source_id = NEW.id) THENRAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='guest_source_database_only: a guest source is database-only and takes no local path or repository',TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='guest_source_guard', DETAIL=jsonb_build_object('source',NEW.id)::text;@@ -35,6 +43,9 @@ BEGINRETURN NEW;END $fn$`;+/** The guest-record guard as it stands now, for migrations after the guest-notes one. */+export const GUEST_RECORDS_GUARD_FUNCTION = guardFunction(true);+export const GUEST_NOTES_SCHEMA_SQL = `CREATE TABLE IF NOT EXISTS guest_sources (source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,@@ -67,7 +78,7 @@ CREATE TABLE IF NOT EXISTS guest_promotions (request_id TEXT);CREATE INDEX IF NOT EXISTS guest_promotions_guest_page_idx ON guest_promotions (guest_page_id);-${GUARD_FUNCTION};+${guardFunction(false)};DROP TRIGGER IF EXISTS guest_marks_immutable ON guest_marks;CREATE TRIGGER guest_marks_immutable BEFORE UPDATE ON guest_marks FOR EACH ROW EXECUTE FUNCTION gbrain_guard_guest_records();DROP TRIGGER IF EXISTS guest_source_database_only ON sources;diff --git a/src/core/guests/sources.ts b/src/core/guests/sources.tsindex 9813383759..326aed176c 100644--- a/src/core/guests/sources.ts+++ b/src/core/guests/sources.ts@@ -10,6 +10,7 @@ import type { Principal } from '../persistence/model.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { addSource } from '../sources-ops.ts';import type { TrustTier } from '../trust/tier.ts';+import { lookupGuestSource } from './admission.ts';export const GUEST_TRUST_CEILING: TrustTier = 'external_untrusted';const PRINCIPAL_KINDS: readonly Principal['kind'][] = ['oauth_client', 'legacy_token', 'local_cli', 'local_stdio', 'application'];@@ -24,18 +25,30 @@ export function isGuestWriter(value: string): boolean {export interface GuestSource { source_id: string; writers: string[]; trust_ceiling: string }-export async function readGuestSource(engine: BrainEngine, sourceId: string): Promise<GuestSource | null> {- const [row] = await engine.executeRaw<GuestSource>('SELECT source_id, writers, trust_ceiling FROM guest_sources WHERE source_id = $1', [sourceId]);- return row ?? null;-}+export const readGuestSource = (engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<GuestSource | null> => lookupGuestSource(engine, sourceId);-export interface GuestSourcePlan { sourceId: string; exists: boolean; localPath: string | null; guest: GuestSource | null; writers: string[] }+export interface GuestSourcePlan { sourceId: string; exists: boolean; localPath: string | null; guest: GuestSource | null; writers: string[];+ /** Its config already says guest: true, so its pages read as guest notes and init repairs it whatever it holds. */+ configGuest: boolean;+ /** Pages in an existing source neither guest record marks yet (deleted ones not yet purged included); 0 otherwise. */+ pages: number }/** What `guests init` would do, read without writing. `writers` is the list after the run (existing ones kept). */export async function planGuestSource(engine: BrainEngine, sourceId: string, writers: readonly string[]): Promise<GuestSourcePlan> {- const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id = $1', [sourceId]);+ const [source] = await engine.executeRaw<{ local_path: string | null; config_guest: boolean }>(+ "SELECT local_path, COALESCE(config->>'guest' = 'true', false) AS config_guest FROM sources WHERE id = $1", [sourceId]);const guest = source ? await readGuestSource(engine, sourceId) : null;- return { sourceId, exists: !!source, localPath: source?.local_path ?? null, guest, writers: [...new Set([...(guest?.writers ?? []), ...writers])].sort() };+ const unmarked = !!source && !guest && !source.config_guest;+ const [held] = unmarked ? await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1', [sourceId]) : [];+ return { sourceId, exists: !!source, localPath: source?.local_path ?? null, guest, writers: [...new Set([...(guest?.writers ?? []), ...writers])].sort(),+ configGuest: source?.config_guest === true, pages: Number(held?.n ?? 0) };+}++/** initGuestSource refused: the source is not yet a guest source and already holds pages (deleted ones not yet purged included). */+export class GuestSourceHoldsPages extends Error {+ constructor(readonly sourceId: string, readonly pages: number) {+ super(`Source "${sourceId}" already holds ${pages} page(s), counting deleted pages not yet purged (a restore would bring them back). Every page in a guest source reads as an outside guest's words and only listed writers can change it, so gbrain will not make this one a guest source. Pick another name with --source.`);+ }}/**@@ -43,14 +56,22 @@ export async function planGuestSource(engine: BrainEngine, sourceId: string, wri* missing, sets its guest config and writes its guest_sources row, in one* transaction (a managed brain creates the source through its lifecycle first).* Reads find guest sources from these two records (guests/marker.ts guestSourceSql).- * The database refuses a source with a local_path (guest_source_database_only).+ * The database refuses a source with a local_path (guest_source_database_only). An existing source that neither guest+ * record marks yet must hold no page: counted under the source row's lock, which a page insert's key check waits on, so+ * no page lands between the count and the commit (GuestSourceHoldsPages). A source one record already marks (its config+ * says guest, or guest_sources lists it) is repaired whatever it holds: its pages already read as guest notes.*/export async function initGuestSource(engine: BrainEngine, sourceId: string, writers: readonly string[]): Promise<GuestSource> {const managed = await managedPersistenceEnabled(engine);if (managed && !(await planGuestSource(engine, sourceId, [])).exists) await addSource(engine, { id: sourceId, federated: true });return engine.transaction(async tx => {- const [source] = await tx.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1 FOR UPDATE', [sourceId]);+ const [source] = await tx.executeRaw<{ id: string; guest: boolean }>(`SELECT s.id, (COALESCE(s.config->>'guest' = 'true', false)+ OR EXISTS (SELECT 1 FROM guest_sources g WHERE g.source_id = s.id)) AS guest FROM sources s WHERE s.id = $1 FOR UPDATE OF s`, [sourceId]);if (!source) await addSource(tx, { id: sourceId, federated: true });+ else if (!source.guest) {+ const [held] = await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1', [sourceId]);+ if (Number(held?.n ?? 0) > 0) throw new GuestSourceHoldsPages(sourceId, Number(held!.n));+ }await tx.executeRaw(`UPDATE sources SET config = config || jsonb_build_object('federated', true, 'guest', true, 'trust_ceiling', $2::text) WHERE id = $1`,[sourceId, GUEST_TRUST_CEILING]);const [row] = await tx.executeRaw<GuestSource>(`INSERT INTO guest_sources (source_id, writers, trust_ceiling) VALUES ($1, $2::text[], $3)diff --git a/src/core/guests/stamp.ts b/src/core/guests/stamp.tsindex 892ac444fa..62fb31065e 100644--- a/src/core/guests/stamp.ts+++ b/src/core/guests/stamp.ts@@ -25,9 +25,12 @@ export function guestViewerIsOwner(ctx: Pick<OperationContext, 'remote'>): boolereturn access.owner && !access.audience?.length;}+/** A copy of `value` the stamp may mark; refuses the read when it cannot copy, so a handler's own (possibly cached) object is never marked. */function detachedCopy<T>(value: T): T {let copy: T;- try { copy = structuredClone(value); } catch { return value; }+ try { copy = structuredClone(value); } catch (e) {+ throw new Error(`The guest-note stamp could not copy this result (${e instanceof Error ? e.message : String(e)}), so the read was refused rather than mark the handler's own object or return a guest note unmarked.`);+ }if (value && typeof value === 'object' && copy && typeof copy === 'object') {for (const key of Object.getOwnPropertySymbols(value)) (copy as Record<symbol, unknown>)[key] = (value as Record<symbol, unknown>)[key];}diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 6fad4962e3..3dfaa988ef 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -556,7 +556,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"expected_revision": {"type": "string",- "description": "Revision read; omit to create."+ "description": "Revision read; required unless force."},"force": {"type": "boolean",diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 13af547807..4b5869bf46 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -434,7 +434,7 @@ const delete_page: Operation = {outputRedaction: 'no_stored_text',description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. A page whose file another live page of the source records is hidden without touching that file (receipt write_through.skipped: shared_origin): the file and the surviving page remain, nothing is erased, and the warning names gbrain repair file-drift --prefer file, which imports the file\'s current content into the surviving page (sync holds that page file_drift rather than overwrite it). purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A purge of a page whose file is shared refuses and names the soft delete. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials. Before the row is removed, pages that are private only through this page get their own visibility: private; a purge that cannot label them soft-deletes the page instead and returns purge_held (doctor derived_origin_parked).',params: {- ...PAGE_MUTATION_PARAMS,+ ...PAGE_MUTATION_PARAMS, expected_revision: { type: 'string', description: 'Revision read; required unless force.' },slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },source_id: { type: 'string', description: "#4329: source holding the row to soft-delete (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer delete access." },purge: { type: 'boolean', description: 'Hard-delete after coordinated artifact removal (no 72h recovery; status purged). Honored only for the trusted local CLI; remote/MCP callers get permission_denied (a non-boolean value is invalid_params) and keep the soft-delete path.' },diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex ee8a6df07e..56e04c9047 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -53,7 +53,7 @@ import { readStoredBody } from '../facts/file-body-guard.ts';import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { perCallWriteSource } from '../access/attest-sources.ts';import type { GuestSource } from '../guests/sources.ts';-import { admitGuestOperation, assertGuestFrontmatter, assertGuestReaders, GUEST_NOTE_INTENT_KEY, guestPageImmutable, refuseRemoteGuestDelete } from '../guests/admission.ts';+import { admitGuestOperation, assertGuestFrontmatter, assertGuestReaders, GUEST_NOTE_INTENT_KEY, guestPageImmutable, guestSourcesUnreadable, refuseRemoteGuestDelete, schemaBehindGuests } from '../guests/admission.ts';import { currentCallerAccess } from '../search/private-visibility.ts';import { assertStorageSourceWriter } from '../storage-manifest/door.ts';@@ -79,7 +79,7 @@ const flatSql = (sql: string) => sql.replace(/\s+/g, ' ').trim();* import's source-root and company-profile checks. All of them are rechecked* under lock by the admission transaction or by publication.*/-type AdmissionSource = { incarnation: string; archived: boolean; local_path: string | null; kind: string | null; role: string | null; guest_writers: string[] | null; guest_trust_ceiling: string | null };+type AdmissionSource = { incarnation: string; archived: boolean; local_path: string | null; kind: string | null; role: string | null; guest_writers: string[] | null; guest_trust_ceiling: string | null; guest_sources_hidden: boolean };const BATCH_SHARED_READS = new Set([ADMISSION_SOURCE_SQL,'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1',@@ -413,8 +413,9 @@ export async function preparePageAdmission(ctx: OperationContext,const [, prior, [source]] = await pipelined(ctx.engine, [() => assertPageRequestIdentity(ctx.engine, principal, requestId),() => getWriteRequest(ctx.engine, principal, requestId),- () => ctx.engine.executeRaw<AdmissionSource>(ADMISSION_SOURCE_SQL, [sourceId]),+ () => ctx.engine.executeRaw<AdmissionSource>(ADMISSION_SOURCE_SQL, [sourceId]).catch(e => schemaBehindGuests(ctx.engine, e)),]) as [unknown, WriteRequest | null, AdmissionSource[]];+ if (source?.guest_sources_hidden) throw guestSourcesUnreadable(sourceId);const guest: GuestSource | null = source?.guest_writers ? { source_id: sourceId, writers: source.guest_writers, trust_ceiling: source.guest_trust_ceiling! } : null;// GBRA-504: a guest source admits only its listed writers' plain put_page, carrying the guest attribution, which joins// the intent (and so the replay identity) here; every other write to it is refused before anything is journaled.diff --git a/src/core/persistence/preadmit-cache.ts b/src/core/persistence/preadmit-cache.tsindex b7d3b6a723..6746823e2c 100644--- a/src/core/persistence/preadmit-cache.ts+++ b/src/core/persistence/preadmit-cache.ts@@ -20,14 +20,16 @@import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { registerEngineView, writeSwitchOn } from './switches.ts';+import { GUEST_SOURCES_HIDDEN_SQL } from '../guests/note.ts';export const PREADMIT_TTL_MS = 30_000;const BRAIN_SQL = 'SELECT brain_id FROM persistence_brain WHERE singleton=1';/*** Page admission's source row and, in the same statement, its guest_sources row (GBRA-504). A row worth caching has a* local path, and a source with one is never a guest source (the database refuses it: guest_source_database_only).+ * guest_sources_hidden: row-level security keeps this role from reading guest_sources, so admission refuses.*/-export const ADMISSION_SOURCE_SQL = "SELECT s.incarnation,s.archived,s.local_path,s.config->>'kind' AS kind,s.config->>'role' AS role,g.writers AS guest_writers,g.trust_ceiling AS guest_trust_ceiling FROM sources s LEFT JOIN guest_sources g ON g.source_id=s.id WHERE s.id=$1";+export const ADMISSION_SOURCE_SQL = `SELECT s.incarnation,s.archived,s.local_path,s.config->>'kind' AS kind,s.config->>'role' AS role,g.writers AS guest_writers,g.trust_ceiling AS guest_trust_ceiling,${GUEST_SOURCES_HIDDEN_SQL} AS guest_sources_hidden FROM sources s LEFT JOIN guest_sources g ON g.source_id=s.id WHERE s.id=$1`;const BINDING_SQL = 'SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1';const WRITER_SQL = new Set(['SELECT revoked_at,credential_hash,lane FROM persistence_local_writers WHERE id=$1::uuid',diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 6afd0b96ca..bf555ddfdb 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -136,7 +136,7 @@ const RELATIONSHIP_TEXT: Record<string, string> = {unreadable_state: 'writer state this database role cannot fully read (row-level security hides it or applies to the role, or a singleton row is missing)',};/** #7780: the tables an unreadable_state raise names in its DETAIL `state` (writer-guard-schema.ts, git-canonical-schema.ts). */-const UNREADABLE_STATES: ReadonlySet<unknown> = new Set(['persistence_brain', 'git_canonical_brain', 'sources', 'pages']);+const UNREADABLE_STATES: ReadonlySet<unknown> = new Set(['persistence_brain', 'git_canonical_brain', 'sources', 'pages', 'guest_sources']);/*** #7777: the persistence protocol guards (shared-skills/persistence-schema.ts) raise SQLSTATE 42501, which is alsodiff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 35a66286e7..670b8af60b 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 313;+export const LATEST_SCHEMA_VERSION = 314;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex d76800130c..a201902ed6 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -314,6 +314,7 @@ import { v310 } from './v310-mcp-request-log-rollup.ts';import { v311 } from './v311-concept-inputs-private.ts';import { v312 } from './v312-guest-notes.ts';import { v313 } from './v313-wake-events.ts';+import { v314 } from './v314-guest-notes-fail-closed.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -626,4 +627,5 @@ export const MIGRATIONS: Migration[] = [v311,v312,v313,+ v314,];diff --git a/src/core/schema-migrations/v314-guest-notes-fail-closed.ts b/src/core/schema-migrations/v314-guest-notes-fail-closed.tsnew file mode 100644index 0000000000..bdd8caf76b--- /dev/null+++ b/src/core/schema-migrations/v314-guest-notes-fail-closed.ts@@ -0,0 +1,37 @@+import type { Migration } from './types.ts';+import { GUEST_RECORDS_GUARD_FUNCTION } from '../guests/schema.ts';+import { GUEST_FAIL_CLOSED_STAMP_TIER_FUNCTION } from '../trust/schema.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.+//+// Follow-ups 3 and 5 of #9354 (guest notes):+// - The trust trigger's guest guard and the guest-record guard read+// guest_sources as the writing role. A role that row-level security keeps+// from reading it (no permissive SELECT policy, not the owner, no BYPASSRLS)+// read it empty, so a write into a guest source passed as if the source were+// ordinary. Both functions now refuse such a role with+// writer_coordinator_required (unreadable_state, state guest_sources), the+// v281 maintainer refusal. Function replacement only: their triggers already+// call them. The owner, a role that bypasses RLS and PGLite never reach the+// policy lookup, so they behave as before.+// - A unique index on the promotion link (guest page, target source, target+// slug). A brain that already holds duplicate links keeps them and gets no+// index (a warning names the table); nothing is rewritten on upgrade, and+// promotion still writes at most one link per target.+// No schema.sql mirror, like v312.+export const v314: Migration = {+ version: 314,+ name: 'guest_notes_fail_closed',+ idempotent: true,+ sql: `${GUEST_RECORDS_GUARD_FUNCTION};+${GUEST_FAIL_CLOSED_STAMP_TIER_FUNCTION};+DO $idx$ BEGIN+ IF EXISTS (SELECT 1 FROM guest_promotions GROUP BY guest_page_id, target_source_id, target_slug HAVING count(*) > 1) THEN+ RAISE WARNING 'guest_promotions holds duplicate promotion links; the unique index guest_promotions_link_key was not created';+ ELSE+ CREATE UNIQUE INDEX IF NOT EXISTS guest_promotions_link_key ON guest_promotions (guest_page_id, target_source_id, target_slug);+ END IF;+END $idx$;+`,+};diff --git a/src/core/trust/schema.ts b/src/core/trust/schema.tsindex a4254e32ad..79b5cf1a02 100644--- a/src/core/trust/schema.ts+++ b/src/core/trust/schema.ts@@ -130,13 +130,16 @@ const CHANGED_CHAIN = `${TRUST_TABLES.map((table, index) => `${index === 0 ? 'IF* is refused here (guest_attribution_missing) without a read of its own. A* fact, take or timeline row in a guest source is refused on INSERT and on a* content change; lifecycle updates and deletes pass. Other tables skip the- * probe while guest_sources is empty.+ * probe while guest_sources is empty. `failClosed` (follow-up 3 of #9354) first refuses, with+ * writer_coordinator_required (unreadable_state, state guest_sources), a role that row-level security keeps from+ * reading guest_sources, which would otherwise read it empty and pass every write as if no source were a guest source.*/-const GUEST_GUARD = `+const guestGuard = (failClosed: boolean) => `IF TG_OP = 'UPDATE' THEN${CHANGED_CHAIN.replace(/\n/g, '\n ')}END IF;- IF TG_TABLE_NAME = 'pages' THEN+ IF TG_TABLE_NAME = 'pages' THEN${failClosed ? `+ ${requireMaintainerPoliciesSql('guest_sources', ['SELECT'], ' ')}` : ''}SELECT g.trust_ceiling, g.writers INTO guest_ceiling, guest_writers FROM guest_sources g WHERE g.source_id = NEW.source_id;guest := FOUND;IF NOT guest AND TG_OP = 'UPDATE' AND OLD.source_id IS DISTINCT FROM NEW.source_id THEN@@ -154,7 +157,10 @@ const GUEST_GUARD = `NULLIF(current_setting('gbrain.guest_note', true), '') = current_setting('gbrain.write_request', true), false) THEN${guestRefuse('guest_attribution_missing', 'a listed writer creates or changes a guest page only as a guest note')};END IF;- ELSIF (TG_OP = 'INSERT' OR changed) AND EXISTS (SELECT 1 FROM guest_sources) THEN+ ELSIF (TG_OP = 'INSERT' OR changed)${failClosed ? ` THEN+ ${requireMaintainerPoliciesSql('guest_sources', ['SELECT'], ' ')}+ END IF;+ IF TG_TABLE_NAME <> 'pages' AND (TG_OP = 'INSERT' OR changed)` : ''} AND EXISTS (SELECT 1 FROM guest_sources) THENIF TG_TABLE_NAME = 'facts' THENguest := EXISTS (SELECT 1 FROM guest_sources g WHERE g.source_id = NEW.source_id);ELSE@@ -168,17 +174,19 @@ const GUEST_GUARD = `const GUEST_CEILING_RETURN = `IF guest_ceiling IS NOT NULL AND ${rank('NEW.trust_tier')} > ${rank('guest_ceiling')} THEN NEW.trust_tier := guest_ceiling; END IF; RETURN NEW;`;/**- * The tier trigger function. `guestSources: false` is the v226 body, kept+ * The tier trigger function. `'none'` is the v226 body, kept* byte-identical (the migration golden pins it, and migrations between v226 and- * the guest-notes migration run before guest_sources exists). `true` adds the guest-source rules- * (GUEST_GUARD) and the per-source ceiling on every RETURN NEW; the guest-notes migration installs- * it, and any later migration that re-creates this function uses it.+ * the guest-notes migration run before guest_sources exists). `'guest'` adds the guest-source rules+ * (guestGuard) and the per-source ceiling on every RETURN NEW, as the guest-notes migration installed it (byte-identical+ * too); `'guest_fail_closed'` adds the unreadable guest_sources refusal, and any later migration that re-creates this+ * function uses it.*/-const stampTierFunction = (guestSources: boolean) => {+const stampTierFunction = (mode: 'none' | 'guest' | 'guest_fail_closed') => {+ const guestSources = mode !== 'none';const ret = guestSources ? GUEST_CEILING_RETURN : 'RETURN NEW;';return `CREATE OR REPLACE FUNCTION gbrain_stamp_trust_tier() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$DECLARE writer text; origin_text text; promo text; backfill boolean; keep boolean; changed boolean; effective text;${guestSources ? ' guest boolean := false; guest_ceiling text; guest_writers text[];' : ''}-BEGIN${SETTINGS}${guestSources ? GUEST_GUARD : ''}+BEGIN${SETTINGS}${guestSources ? guestGuard(mode === 'guest_fail_closed') : ''}IF ${rank('writer')} > ${rank(`'${OWNER_TIER_FLOOR}'`)} AND (promo IS NULL OR ${rank('writer')} > ${rank('promo')}) THEN${refuse('a write declared a tier above operator_curated without owner confirmation', `jsonb_build_object('op',TG_OP,'writer',writer)::text`)};END IF;@@ -214,9 +222,11 @@ BEGIN${SETTINGS}${guestSources ? GUEST_GUARD : ''}${ret}END $fn$`;};-const STAMP_TIER_FUNCTION = stampTierFunction(false);-/** The current tier trigger function, guest-source rules included (the guest-notes migration). */-export const GUEST_AWARE_STAMP_TIER_FUNCTION = stampTierFunction(true);+const STAMP_TIER_FUNCTION = stampTierFunction('none');+/** The tier trigger function as the guest-notes migration installed it (its body is pinned there). */+export const GUEST_AWARE_STAMP_TIER_FUNCTION = stampTierFunction('guest');+/** The current tier trigger function: guest-source rules that refuse a role unable to read guest_sources. */+export const GUEST_FAIL_CLOSED_STAMP_TIER_FUNCTION = stampTierFunction('guest_fail_closed');/*** A version row snapshots the page before the archiving write changes it, indiff --git a/test/auth-rescope-unified.test.ts b/test/auth-rescope-unified.test.tsindex b6ed9c5fce..1f64e09f9d 100644--- a/test/auth-rescope-unified.test.ts+++ b/test/auth-rescope-unified.test.ts@@ -192,6 +192,17 @@ describe('9. OAuth clients', () => {expect((await tokenRow('tok-all')).allowed_operations).toBeNull();}, 180_000);+ test('rescope --client with no grant flag prints the operation snapshot and the slug prefixes', async () => {+ const client = await withBrain(async engine => {+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ return provider.registerClientManual('client-ops-example', ['client_credentials'], 'read write');+ });+ expect((await cli('auth', 'rescope', '--client', client.clientId, '--operations', 'get_page,put_page')).exitCode).toBe(0);+ const human = await cli('auth', 'rescope', '--client', client.clientId);+ expect(human.stdout).toMatch(/Operations: get_page, put_page\n/);+ expect(human.stdout).toContain('Slug prefixes: <none>');+ }, 180_000);+test('#6993 rescope --client with no grant flag prints the stored grants and writes nothing; an unknown id is client_not_found', async () => {const client = await withBrain(async engine => {const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });diff --git a/test/derived-state-maintainers-7637.test.ts b/test/derived-state-maintainers-7637.test.tsindex 7fb9cb7631..6b5a029440 100644--- a/test/derived-state-maintainers-7637.test.ts+++ b/test/derived-state-maintainers-7637.test.ts@@ -34,7 +34,7 @@ const BYPASS = `gbrain_maint_bypass_7637_${suffix}`;const UNREADABLE = /writer_coordinator_required: writer state is unreadable to this database role/;const ROLLBACK = 'maintainer-probe-rollback';/** The tables the maintainers read or write besides the one being written. */-const MAINTAINER_TABLES = ['page_retrievals', 'extract_atoms_page_state', 'page_projection_jobs', 'trust_policy_state', 'timeline_entries', 'pages', 'sources'];+const MAINTAINER_TABLES = ['page_retrievals', 'extract_atoms_page_state', 'page_projection_jobs', 'trust_policy_state', 'timeline_entries', 'pages', 'sources', 'guest_sources'];beforeAll(async () => {configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 5ed5a6f0f5..ae2d4c7204 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -648,7 +648,7 @@"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",- "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0618c22ca97887e3333e0543478e7e97ecba3ba3c678f6d803a1e6df0900b163",+ "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597","gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",@@ -666,7 +666,7 @@"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=97d9a8ab7fde70e547ae7bbc87fa3dd749de18e81ffc013f78af3976ee6bd7e3","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",@@ -1373,6 +1373,7 @@"guest_marks_audience_saved_idx": "CREATE INDEX guest_marks_audience_saved_idx ON public.guest_marks USING btree (audience_member, saved_at)","guest_marks_pkey": "CREATE UNIQUE INDEX guest_marks_pkey ON public.guest_marks USING btree (page_id)","guest_promotions_guest_page_idx": "CREATE INDEX guest_promotions_guest_page_idx ON public.guest_promotions USING btree (guest_page_id)",+ "guest_promotions_link_key": "CREATE UNIQUE INDEX guest_promotions_link_key ON public.guest_promotions USING btree (guest_page_id, target_source_id, target_slug)","guest_promotions_pkey": "CREATE UNIQUE INDEX guest_promotions_pkey ON public.guest_promotions USING btree (id)","guest_sources_pkey": "CREATE UNIQUE INDEX guest_sources_pkey ON public.guest_sources USING btree (source_id)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex b725fb65e4..c3ef6c421a 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -648,7 +648,7 @@"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",- "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0618c22ca97887e3333e0543478e7e97ecba3ba3c678f6d803a1e6df0900b163",+ "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597","gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",@@ -666,7 +666,7 @@"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=97d9a8ab7fde70e547ae7bbc87fa3dd749de18e81ffc013f78af3976ee6bd7e3","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",@@ -1373,6 +1373,7 @@"guest_marks_audience_saved_idx": "CREATE INDEX guest_marks_audience_saved_idx ON public.guest_marks USING btree (audience_member, saved_at)","guest_marks_pkey": "CREATE UNIQUE INDEX guest_marks_pkey ON public.guest_marks USING btree (page_id)","guest_promotions_guest_page_idx": "CREATE INDEX guest_promotions_guest_page_idx ON public.guest_promotions USING btree (guest_page_id)",+ "guest_promotions_link_key": "CREATE UNIQUE INDEX guest_promotions_link_key ON public.guest_promotions USING btree (guest_page_id, target_source_id, target_slug)","guest_promotions_pkey": "CREATE UNIQUE INDEX guest_promotions_pkey ON public.guest_promotions USING btree (id)","guest_sources_pkey": "CREATE UNIQUE INDEX guest_sources_pkey ON public.guest_sources USING btree (source_id)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex f0f3e1007f..a37e50c4e5 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -648,7 +648,7 @@"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",- "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0618c22ca97887e3333e0543478e7e97ecba3ba3c678f6d803a1e6df0900b163",+ "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597","gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",@@ -666,7 +666,7 @@"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=97d9a8ab7fde70e547ae7bbc87fa3dd749de18e81ffc013f78af3976ee6bd7e3","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",@@ -1373,6 +1373,7 @@"guest_marks_audience_saved_idx": "CREATE INDEX guest_marks_audience_saved_idx ON public.guest_marks USING btree (audience_member, saved_at)","guest_marks_pkey": "CREATE UNIQUE INDEX guest_marks_pkey ON public.guest_marks USING btree (page_id)","guest_promotions_guest_page_idx": "CREATE INDEX guest_promotions_guest_page_idx ON public.guest_promotions USING btree (guest_page_id)",+ "guest_promotions_link_key": "CREATE UNIQUE INDEX guest_promotions_link_key ON public.guest_promotions USING btree (guest_page_id, target_source_id, target_slug)","guest_promotions_pkey": "CREATE UNIQUE INDEX guest_promotions_pkey ON public.guest_promotions USING btree (id)","guest_sources_pkey": "CREATE UNIQUE INDEX guest_sources_pkey ON public.guest_sources USING btree (source_id)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex ab7e09a410..790de74ac5 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -651,7 +651,7 @@"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",- "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0618c22ca97887e3333e0543478e7e97ecba3ba3c678f6d803a1e6df0900b163",+ "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597","gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",@@ -669,7 +669,7 @@"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=97d9a8ab7fde70e547ae7bbc87fa3dd749de18e81ffc013f78af3976ee6bd7e3","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",@@ -1375,6 +1375,7 @@"guest_marks_audience_saved_idx": "CREATE INDEX guest_marks_audience_saved_idx ON public.guest_marks USING btree (audience_member, saved_at)","guest_marks_pkey": "CREATE UNIQUE INDEX guest_marks_pkey ON public.guest_marks USING btree (page_id)","guest_promotions_guest_page_idx": "CREATE INDEX guest_promotions_guest_page_idx ON public.guest_promotions USING btree (guest_page_id)",+ "guest_promotions_link_key": "CREATE UNIQUE INDEX guest_promotions_link_key ON public.guest_promotions USING btree (guest_page_id, target_source_id, target_slug)","guest_promotions_pkey": "CREATE UNIQUE INDEX guest_promotions_pkey ON public.guest_promotions USING btree (id)","guest_sources_pkey": "CREATE UNIQUE INDEX guest_sources_pkey ON public.guest_sources USING btree (source_id)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 6c88b21b46..a0177d37e2 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -651,7 +651,7 @@"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",- "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0618c22ca97887e3333e0543478e7e97ecba3ba3c678f6d803a1e6df0900b163",+ "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597","gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",@@ -669,7 +669,7 @@"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=97d9a8ab7fde70e547ae7bbc87fa3dd749de18e81ffc013f78af3976ee6bd7e3","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",@@ -1375,6 +1375,7 @@"guest_marks_audience_saved_idx": "CREATE INDEX guest_marks_audience_saved_idx ON public.guest_marks USING btree (audience_member, saved_at)","guest_marks_pkey": "CREATE UNIQUE INDEX guest_marks_pkey ON public.guest_marks USING btree (page_id)","guest_promotions_guest_page_idx": "CREATE INDEX guest_promotions_guest_page_idx ON public.guest_promotions USING btree (guest_page_id)",+ "guest_promotions_link_key": "CREATE UNIQUE INDEX guest_promotions_link_key ON public.guest_promotions USING btree (guest_page_id, target_source_id, target_slug)","guest_promotions_pkey": "CREATE UNIQUE INDEX guest_promotions_pkey ON public.guest_promotions USING btree (id)","guest_sources_pkey": "CREATE UNIQUE INDEX guest_sources_pkey ON public.guest_sources USING btree (source_id)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 998cbcc70c..d6715c056e 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -651,7 +651,7 @@"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",- "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0618c22ca97887e3333e0543478e7e97ecba3ba3c678f6d803a1e6df0900b163",+ "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597","gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",@@ -669,7 +669,7 @@"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=97d9a8ab7fde70e547ae7bbc87fa3dd749de18e81ffc013f78af3976ee6bd7e3","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",@@ -1375,6 +1375,7 @@"guest_marks_audience_saved_idx": "CREATE INDEX guest_marks_audience_saved_idx ON public.guest_marks USING btree (audience_member, saved_at)","guest_marks_pkey": "CREATE UNIQUE INDEX guest_marks_pkey ON public.guest_marks USING btree (page_id)","guest_promotions_guest_page_idx": "CREATE INDEX guest_promotions_guest_page_idx ON public.guest_promotions USING btree (guest_page_id)",+ "guest_promotions_link_key": "CREATE UNIQUE INDEX guest_promotions_link_key ON public.guest_promotions USING btree (guest_page_id, target_source_id, target_slug)","guest_promotions_pkey": "CREATE UNIQUE INDEX guest_promotions_pkey ON public.guest_promotions USING btree (id)","guest_sources_pkey": "CREATE UNIQUE INDEX guest_sources_pkey ON public.guest_sources USING btree (source_id)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 1911e49712..ff7ead0da9 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 300728,- "stdoutSha256": "0e10a7c8d316e108fa63dfd27366d9609bcce6bcf8e7d019d5d63453d2d577d1",+ "stdoutBytes": 300735,+ "stdoutSha256": "33eac5e04d5362ecb7175edec8781ab33558a5dbad8061e781550f43cbc415ac","toolNames": ["remember","entity",@@ -767,7 +767,7 @@"schema": {"properties": {"expected_revision": {- "description": "Revision read; omit to create.",+ "description": "Revision read; required unless force.","type": "string"},"force": {diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 45d4952b2c..a7a4fb18f6 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 308,+ "count": 309,"gaps": [17,18,@@ -100,7 +100,7 @@"widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 313,+ "latest": 314,"records": [{"handler": {@@ -5070,6 +5070,19 @@"transaction": "absent","verify": "absent","version": 313+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "guest_notes_fail_closed",+ "sql": {+ "length": 19508,+ "sha256": "17627b13248a21b59cf335f5caee8e29e5103188e107c6a7714b9e202a8bb4f1"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 314}],"versions": [@@ -5380,7 +5393,8 @@310,311,312,- 313+ 313,+ 314]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 72a156b38e..c30ebd2d70 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -648,7 +648,7 @@"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803","gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",- "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0618c22ca97887e3333e0543478e7e97ecba3ba3c678f6d803a1e6df0900b163",+ "gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597","gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=78fe53917ec54c7627df4961a7669e0d65f8adfa7e249da1beeb58dc37978a66","gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e","gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",@@ -666,7 +666,7 @@"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",- "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3034ff087fc72989b8d7a1cbd8895a26ef6433d0fa830fc6ace23d5a79ff33e2",+ "gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=97d9a8ab7fde70e547ae7bbc87fa3dd749de18e81ffc013f78af3976ee6bd7e3","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=1f8fcf3492a9276c52541f6d353d6c709a123b6db4c84bb9a60d77a82fa1672f","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",@@ -1373,6 +1373,7 @@"guest_marks_audience_saved_idx": "CREATE INDEX guest_marks_audience_saved_idx ON public.guest_marks USING btree (audience_member, saved_at)","guest_marks_pkey": "CREATE UNIQUE INDEX guest_marks_pkey ON public.guest_marks USING btree (page_id)","guest_promotions_guest_page_idx": "CREATE INDEX guest_promotions_guest_page_idx ON public.guest_promotions USING btree (guest_page_id)",+ "guest_promotions_link_key": "CREATE UNIQUE INDEX guest_promotions_link_key ON public.guest_promotions USING btree (guest_page_id, target_source_id, target_slug)","guest_promotions_pkey": "CREATE UNIQUE INDEX guest_promotions_pkey ON public.guest_promotions USING btree (id)","guest_sources_pkey": "CREATE UNIQUE INDEX guest_sources_pkey ON public.guest_sources USING btree (source_id)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)",diff --git a/test/guest-derived-predicate.test.ts b/test/guest-derived-predicate.test.tsindex b74119c1e0..95b6b7d9c9 100644--- a/test/guest-derived-predicate.test.ts+++ b/test/guest-derived-predicate.test.ts@@ -19,6 +19,8 @@ import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';import { runPhaseProposeTakes } from '../src/core/cycle/propose-takes.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';const FLAGGED = 'source-a';const GUEST_PAGE = 'notes/flagged-a';@@ -121,4 +123,25 @@ describe('a brain whose schema is behind the guest-notes migration (v' + GUEST_Nexpect(scanned.filter(slug => slug === GUEST_PAGE || slug === 'people/erin-example')).toEqual([]);expect(await flaggedRows(engine)).toEqual({ links: 0, timeline: 0, facts: 0, proposals: 0 });}, 180_000);++ test('a skip caused by the failed guest lookup says the lookup failed', async () => {+ const atoms = await runPhaseExtractAtoms(engine, { sourceId: FLAGGED });+ expect(atoms.details).toMatchObject({ reason: 'guest_source_lookup_failed', source_id: FLAGGED });+ expect(String((atoms.details as { error?: string }).error)).toContain('guest_sources');+ const report = await runCycle(engine, { sourceId: FLAGGED, phases: ['extract_facts'], brainDir: null } as never);+ expect(report.phases.find(p => p.phase === 'extract_facts')?.details).toMatchObject({ reason: 'guest_source_lookup_failed', source_id: FLAGGED });+ }, 120_000);++ test('a page write is refused migrations_pending, not with the missing-table error', async () => {+ const [version] = await engine.executeRaw<{ value: string }>("SELECT value FROM config WHERE key = 'version'");+ await engine.executeRaw("UPDATE config SET value = $1 WHERE key = 'version'", [String(GUEST_NOTES_MIGRATION - 1)]);+ try {+ const out = await dispatchToolCall(engine, 'put_page', { slug: 'notes/behind-a', content: '---\ntype: note\ntitle: Behind\n---\n# Behind\n' }, { remote: false, sourceId: 'default' });+ const text = out.content.map(c => c.text).join('\n');+ expect({ isError: out.isError, migrationsPending: text.includes('migrations_pending'), raw: text.includes('does not exist') })+ .toEqual({ isError: true, migrationsPending: true, raw: false });+ } finally {+ await engine.executeRaw("UPDATE config SET value = $1 WHERE key = 'version'", [version!.value]);+ }+ }, 120_000);});diff --git a/test/guest-derived-registry.test.ts b/test/guest-derived-registry.test.tsindex f68ee25182..90bbd17a42 100644--- a/test/guest-derived-registry.test.ts+++ b/test/guest-derived-registry.test.ts@@ -24,7 +24,7 @@ import { runPhaseProposeTakes } from '../src/core/cycle/propose-takes.ts';import { withWriteAttribution } from '../src/core/persistence/context.ts';const ROOT = join(import.meta.dir, '..');-const HELPERS = ['skipsGuestSource', 'skipsGuestNote', 'withoutGuestSources', 'guestSourceExclusionSql'];+const HELPERS = ['skipsGuestSource', 'guestSourceSkip', 'skipsGuestNote', 'withoutGuestSources', 'guestSourceExclusionSql'];describe('guest derived-producer registry', () => {test('every cycle phase is classified, and every none entry says why', () => {diff --git a/test/guest-notes-admission.test.ts b/test/guest-notes-admission.test.tsindex 9314e2dceb..2a67f1772b 100644--- a/test/guest-notes-admission.test.ts+++ b/test/guest-notes-admission.test.ts@@ -28,7 +28,7 @@ import { parseAudience } from '../src/core/access/audience.ts';import { remoteCallerAccess } from '../src/core/access/caller.ts';import { withCallerAccess } from '../src/core/search/private-visibility.ts';import { changeGuestWriters, initGuestSource } from '../src/core/guests/sources.ts';-import { GUEST_HEADER, parseGuestAttribution } from '../src/core/guests/admission.ts';+import { GUEST_HEADER, insertGuestMark, parseGuestAttribution } from '../src/core/guests/admission.ts';import { preparePageAdmission } from '../src/core/persistence/page-mutations.ts';import { admitWrite } from '../src/core/persistence/journal.ts';import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';@@ -123,6 +123,11 @@ beforeAll(async () => {afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);describe('guest attribution channel', () => {+ test('a guest mark that writes no row fails instead of passing silently', async () => {+ const row = { source_id: SRC, slug: 'guests/no-such-page', principal_kind: 'oauth_client', principal_id: 'client-a', request_id: randomUUID() };+ expect(await insertGuestMark(engine, row, META, 'member:bob-example').then(() => 'no error', (e: Error) => e.message)).toContain('guest mark');+ });+test('header form is URL-encoded sender_label and group; meta form is _meta.guest', () => {expect(GUEST_HEADER).toBe('X-Gbrain-Guest');expect(parseGuestAttribution({ header: 'sender_label=Bob%20Example&group=team-a' })).toEqual(META);diff --git a/test/guest-notes-promotion.test.ts b/test/guest-notes-promotion.test.tsindex 30cf43667d..f8eeaefeec 100644--- a/test/guest-notes-promotion.test.ts+++ b/test/guest-notes-promotion.test.ts@@ -134,6 +134,28 @@ describe('promote_guest_note (pglite, repo-less)', () => {expect((await promotions(slug)).length).toBe(1);}, 120_000);+ test('a link whose target page was purged is not already_promoted: promoting again writes the page and keeps one link', async () => {+ const slug = slugOf();+ await saveGuest(slug);+ const to = 'notes/purged-' + slug.slice(-8);+ expect((await local('promote_guest_note', { slug, to })).json.status).toBe('promoted');+ await engine.executeRaw('DELETE FROM pages WHERE source_id = $1 AND slug = $2', [PLAIN, to]);+ const again = await local('promote_guest_note', { slug, to });+ expect({ isError: again.isError, status: again.json.status }).toEqual({ isError: false, status: 'promoted' });+ expect((await engine.getPage(to, { sourceId: PLAIN }))?.frontmatter?.promoted_from).toBe(SRC + ':' + slug);+ expect(await promotions(slug)).toEqual([{ target_source_id: PLAIN, target_slug: to, promoted_by_kind: 'local_cli' }]);+ }, 120_000);++ test('the promotion link is unique per guest page and target', async () => {+ const slug = slugOf();+ await saveGuest(slug);+ expect((await local('promote_guest_note', { slug })).json.status).toBe('promoted');+ const [link] = await engine.executeRaw<{ guest_page_id: number }>(+ 'SELECT g.guest_page_id FROM guest_promotions g JOIN pages p ON p.id = g.guest_page_id WHERE p.source_id = $1 AND p.slug = $2', [SRC, slug]);+ expect(await engine.executeRaw(`INSERT INTO guest_promotions (guest_page_id, target_source_id, target_slug, promoted_by_kind, promoted_by_id)+ VALUES ($1, $2, $3, 'local_cli', 'probe')`, [link!.guest_page_id, PLAIN, slug]).then(() => 'inserted', (e: Error) => e.message)).toMatch(/unique|duplicate/i);+ }, 120_000);+test('a credential bound to the owner promotes into its write source, and so do one speaking only for the owner and an owner-bound stdio server', async () => {const slug = slugOf();await saveGuest(slug);diff --git a/test/guest-notes-scoped-role.test.ts b/test/guest-notes-scoped-role.test.tsnew file mode 100644index 0000000000..6c94f93611--- /dev/null+++ b/test/guest-notes-scoped-role.test.ts@@ -0,0 +1,130 @@+/**+ * Guest notes under a scoped database role (follow-up 3 of #9354). The guest guard in the trust trigger and guest+ * admission read guest_sources as the role doing the write. A role that neither owns guest_sources nor bypasses RLS,+ * with no policy on it, read it empty, so a write into a guest source passed as if the source were ordinary.+ * Contract: guest_sources hidden by row-level security is never read as "no guest source". The trigger refuses the+ * write (writer_coordinator_required, unreadable_state, state guest_sources) and the admission reads refuse with the+ * same code. A role holding the docs/ENGINES.md maintainer recipe (guest_sources included) tells guest sources apart+ * as before. Postgres only (PGLite has no roles): it runs in the unit-lane PostgreSQL arms (test/postgres-unit-arms.txt).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { readGuestSource } from '../src/core/guests/sources.ts';+import { refuseGuestSourceWrite, refuseRemoteGuestDelete } from '../src/core/guests/admission.ts';+import { ADMISSION_SOURCE_SQL } from '../src/core/persistence/preadmit-cache.ts';+import type { Principal } from '../src/core/persistence/model.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const SCOPED = `gbrain_guest_scoped_${randomUUID().replaceAll('-', '').slice(0, 12)}`;+const UNREADABLE = /writer_coordinator_required: writer state is unreadable to this database role/;+const BROKER: Principal = { kind: 'oauth_client', id: 'client-a' };+const OTHER: Principal = { kind: 'oauth_client', id: 'client-b' };+const GUESTS = 'guests-scoped';++(testBackends().includes('postgres') ? describe : describe.skip)('guest notes under a scoped database role (Postgres)', () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ let tables: string[] = [];+ let guestPage = { id: 0, slug: '' };++ /** Open policies for the scoped role on every table except `hidden`. */+ async function policies(hidden: string[]) {+ for (const table of tables) {+ await engine.executeRaw(`DROP POLICY IF EXISTS ${SCOPED}_open ON ${table}`);+ if (!hidden.includes(table)) await engine.executeRaw(`CREATE POLICY ${SCOPED}_open ON ${table} FOR ALL TO ${SCOPED} USING (true) WITH CHECK (true)`);+ }+ }+ /** Runs `fn` as the scoped role writing as `principal`, in a transaction that rolls back. */+ async function asScoped<T>(principal: Principal, fn: (tx: BrainEngine) => Promise<T>): Promise<{ value?: T; error?: string; code?: string; state?: string }> {+ const marker = new Error('scoped-probe-rollback');+ let value: T | undefined;+ try {+ await engine.transaction(async tx => {+ await tx.executeRaw(`SET LOCAL ROLE ${SCOPED}`);+ await tx.executeRaw('SELECT set_config(\'gbrain.write_principal_kind\',$1,true), set_config(\'gbrain.write_principal_id\',$2,true)', [principal.kind, principal.id]);+ value = await fn(tx);+ throw marker;+ });+ } catch (e) {+ if (e !== marker) {+ const detail = (e as { detail?: string }).detail;+ return { error: (e as Error).message, ...((e as { code?: string }).code ? { code: (e as { code?: string }).code } : {}),+ ...(detail?.startsWith('{') ? { state: JSON.parse(detail).state } : {}) };+ }+ }+ return { value };+ }+ const insertPage = (tx: BrainEngine, sourceId: string) => tx.executeRaw(+ `INSERT INTO pages(source_id,slug,type,title,compiled_truth,content_hash) VALUES($1,$2,'note','T','b',repeat('a',64)) RETURNING id, slug`,+ [sourceId, `guests/${randomUUID().slice(0, 8)}`]);++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine; close = pg.close;+ await engine.executeRaw(`CREATE ROLE ${SCOPED} NOLOGIN NOSUPERUSER NOBYPASSRLS`);+ await engine.executeRaw(`GRANT USAGE ON SCHEMA public TO ${SCOPED}`);+ await engine.executeRaw(`GRANT ALL ON ALL TABLES IN SCHEMA public TO ${SCOPED}`);+ await engine.executeRaw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ${SCOPED}`);+ tables = (await engine.executeRaw<{ t: string }>(`SELECT tablename AS t FROM pg_tables WHERE schemaname = 'public' ORDER BY 1`)).map(r => r.t);+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES($1,$1,'{"federated":true,"guest":true}'::jsonb)`, [GUESTS]);+ await engine.executeRaw(`INSERT INTO guest_sources(source_id,writers) VALUES($1,ARRAY['oauth_client:client-a'])`, [GUESTS]);+ const request = randomUUID();+ const [page] = await engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('gbrain.write_principal_kind','oauth_client',true), set_config('gbrain.write_principal_id','client-a',true),+ set_config('gbrain.write_request',$1,true), set_config('gbrain.guest_note',$1,true)`, [request]);+ return insertPage(tx, GUESTS) as Promise<Array<{ id: number; slug: string }>>;+ });+ guestPage = page!;+ }, 180_000);+ afterAll(async () => {+ if (engine) {+ await engine.executeRaw(`DROP OWNED BY ${SCOPED}`).catch(() => undefined);+ await engine.executeRaw(`DROP ROLE IF EXISTS ${SCOPED}`);+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ }+ await close?.();+ resetGateway();+ });++ test('the trigger refuses an unlisted page write into a guest source it cannot see as one', async () => {+ await policies(['guest_sources']);+ expect(await asScoped(OTHER, tx => insertPage(tx, GUESTS))).toEqual({ error: expect.stringMatching(UNREADABLE), code: 'P0001', state: 'guest_sources' });+ });++ test('the trigger refuses an ordinary page write too, since the role cannot tell the sources apart', async () => {+ await policies(['guest_sources']);+ expect(await asScoped(OTHER, tx => insertPage(tx, 'default'))).toEqual({ error: expect.stringMatching(UNREADABLE), code: 'P0001', state: 'guest_sources' });+ });++ test('the trigger refuses a fact, take or timeline row it cannot place outside a guest source', async () => {+ await policies(['guest_sources']);+ expect((await asScoped(OTHER, tx => tx.executeRaw(`INSERT INTO facts(source_id,entity_slug,fact,kind,source) VALUES($1,'e','claim','fact','test')`, [GUESTS]))).state)+ .toBe('guest_sources');+ expect((await asScoped(OTHER, tx => tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,summary,detail,source) VALUES($1,'2026-01-01','s','d','x')`, [guestPage.id]))).state)+ .toBe('guest_sources');+ });++ test('admission reads refuse instead of reading the guest source as ordinary', async () => {+ await policies(['guest_sources']);+ expect((await asScoped(OTHER, tx => readGuestSource(tx, GUESTS))).error).toMatch(/writer_coordinator_required|guest_sources/);+ expect((await asScoped(OTHER, tx => refuseGuestSourceWrite(tx, GUESTS, async () => OTHER, 'remember'))).error).toMatch(/guest_sources/);+ expect((await asScoped(OTHER, tx => refuseRemoteGuestDelete(tx, GUESTS, guestPage.slug, OTHER))).error).toMatch(/guest_sources/);+ const admission = await asScoped(OTHER, tx => tx.executeRaw<Record<string, unknown>>(ADMISSION_SOURCE_SQL, [GUESTS]));+ expect(admission.value?.[0]?.guest_sources_hidden).toBe(true);+ });++ test('with a guest_sources policy the role tells guest sources apart as before', async () => {+ await policies([]);+ expect((await asScoped(OTHER, tx => insertPage(tx, GUESTS))).error).toMatch(/source_writer_restricted/);+ expect((await asScoped(OTHER, tx => insertPage(tx, 'default'))).error).toBeUndefined();+ expect((await asScoped(BROKER, tx => readGuestSource(tx, GUESTS))).value).toMatchObject({ source_id: GUESTS, writers: ['oauth_client:client-a'] });+ const admission = await asScoped(OTHER, tx => tx.executeRaw<Record<string, unknown>>(ADMISSION_SOURCE_SQL, [GUESTS]));+ expect(admission.value?.[0]).toMatchObject({ guest_writers: ['oauth_client:client-a'], guest_sources_hidden: false });+ });+});diff --git a/test/guest-notes-stamp-access.test.ts b/test/guest-notes-stamp-access.test.tsindex 5fe4213373..c6756efcbb 100644--- a/test/guest-notes-stamp-access.test.ts+++ b/test/guest-notes-stamp-access.test.ts@@ -26,6 +26,7 @@ import { withCallerAccess } from '../src/core/search/private-visibility.ts';import { exemptGuestWriter, withOutputRedaction } from '../src/core/search/output-redaction.ts';import type { AuthInfo } from '../src/core/ops/contract.ts';import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';+import { stampGuestNotes } from '../src/core/guests/stamp.ts';const SRC = 'guests';const PLAIN = 'source-a';@@ -172,6 +173,13 @@ describe('guest marks reach only callers who can read the note', () => {expect(stamps((await preview('bob-example', 'get_raw_data', { slug: HOST })).text).map(s => s.at).sort()).toEqual([GONE, GUEST, String(ids[GUEST])].sort());});+ test("(g) a result the stamp cannot copy refuses the read and leaves the handler's own object unmarked", async () => {+ const own = { source_id: SRC, slug: GUEST, title: 'held by the handler', render: () => 'not cloneable' };+ const outcome = await stampGuestNotes({ engine, remote: false, sourceId: SRC } as never, own).then(() => 'stamped', (e: Error) => e.message);+ expect({ refused: outcome.includes('could not copy'), origin: (own as Record<string, unknown>).origin, guest: (own as Record<string, unknown>).guest })+ .toEqual({ refused: true, origin: undefined, guest: undefined });+ });+test('(e) output redaction runs after the stamp, so a key-like sender label is redacted for a remote reader', async () => {const listed = await call('bob', 'list_pages', {}, SRC);const keyed = stamps(listed.text).filter(s => s.at === KEYED);diff --git a/test/guest-notes-warning.test.ts b/test/guest-notes-warning.test.tsindex 1ccc038109..4ce6095de0 100644--- a/test/guest-notes-warning.test.ts+++ b/test/guest-notes-warning.test.ts@@ -174,7 +174,9 @@ describe('guest warning on reads', () => {test('a source made a guest source while the process runs is stamped on its next read, with no restart', async () => {const before = await dispatchToolCall(engine, 'get_page', { slug: 'notes/late-page' }, { remote: false, sourceId: LATE });expect(parse(before.content[0]!.text).origin).not.toBe('guest');- await initGuestSource(engine, LATE, []);+ // initGuestSource refuses a source that already holds pages, so the fixture writes the two guest records itself.+ await engine.executeRaw(`UPDATE sources SET config = config || '{"federated": true, "guest": true}'::jsonb WHERE id = $1`, [LATE]);+ await engine.executeRaw('INSERT INTO guest_sources (source_id, writers) VALUES ($1, ARRAY[]::text[])', [LATE]);const after = parse((await dispatchToolCall(engine, 'get_page', { slug: 'notes/late-page' }, { remote: false, sourceId: LATE })).content[0]!.text);expect({ origin: after.origin, unattributed: after.guest?.unattributed }).toEqual({ origin: 'guest', unattributed: true });}, 60_000);diff --git a/test/guests-cli.test.ts b/test/guests-cli.test.tsindex 6b1c189d4d..976ebc5ba6 100644--- a/test/guests-cli.test.ts+++ b/test/guests-cli.test.ts@@ -15,6 +15,7 @@ import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { runGuests } from '../src/commands/guests.ts';+import { initGuestSource } from '../src/core/guests/sources.ts';import { runSources } from '../src/commands/sources.ts';let engine: PGLiteEngine;@@ -84,6 +85,22 @@ describe('gbrain guests init', () => {expect(await guestRow('source-a')).toBeUndefined();});+ test('initGuestSource itself counts under the source lock and refuses a source that holds pages', async () => {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', ['source-a']);+ await engine.putPage('notes/owner-a', { title: 'Owner', type: 'note' as never, compiled_truth: 'Mine.', frontmatter: {}, timeline: '' }, { sourceId: 'source-a' } as never);+ expect(await initGuestSource(engine, 'source-a', []).then(() => 'made a guest source', (e: Error) => e.message)).toContain('already holds 1 page');+ expect(await guestRow('source-a')).toBeUndefined();+ });++ test("doctor's repair works on a source whose config says guest but which has no guest_sources row and holds pages", async () => {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', ['source-a']);+ await engine.putPage('notes/owner-a', { title: 'Owner', type: 'note' as never, compiled_truth: 'Mine.', frontmatter: {}, timeline: '' }, { sourceId: 'source-a' } as never);+ await engine.executeRaw(`UPDATE sources SET config = config || '{"guest": true}'::jsonb WHERE id = 'source-a'`);+ await run(() => runGuests(engine, ['init', '--source', 'source-a', '--yes']));+ expect({ exitCode: exitCode as number | null, err: err.join('\n') }).toEqual({ exitCode: null, err: '' });+ expect(await guestRow('source-a')).toEqual({ writers: [], trust_ceiling: 'external_untrusted' });+ });+test('previews by default and writes nothing', async () => {await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a']));expect(exitCode).toBeNull();diff --git a/test/guests-grant-owner-clients.test.ts b/test/guests-grant-owner-clients.test.tsindex cc6dab1146..1c2d25f0e5 100644--- a/test/guests-grant-owner-clients.test.ts+++ b/test/guests-grant-owner-clients.test.ts@@ -72,6 +72,22 @@ describe('gbrain guests grant-owner-clients', () => {expect(await grantOf(member)).toEqual(before.member);}, 60_000);+ test('the owner credential read loads no token hash, only the columns the grant needs', async () => {+ const { token } = await brain();+ const loaded: unknown[] = [];+ const read = engine.executeRaw.bind(engine);+ const spy = spyOn(engine, 'executeRaw').mockImplementation((async (sql: string, params?: unknown[]) => {+ const rows = await read(sql, params);+ loaded.push(...rows);+ return rows;+ }) as never);+ try {+ const { credentials } = await ownerCredentials(engine, SRC);+ expect(credentials.map(c => c.id)).toContain(token);+ } finally { spy.mockRestore(); }+ expect(JSON.stringify(loaded)).not.toContain('token_hash');+ }, 60_000);+test('the preview lists owner credentials that cannot read the guest source and writes nothing', async () => {const { narrow, reading, member, token } = await brain();const before = await grantOf(narrow);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex a4716d57ef..5e7c03d275 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -182,6 +182,7 @@ test/graduation-target.test.tstest/graduation-verify-sync-freshness.test.tstest/graduation-verify.test.tstest/grandfather-managed.test.ts+test/guest-notes-scoped-role.test.tstest/harness-skills-epoch.test.tstest/harness-verify-member-credential.test.tstest/held-bare-name-move-gst2492.test.ts