Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Guest sources accept new notes from listed writers only

garrytanc250b1e21545
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 58d57d19e9..4d5db2ecc0 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2542,6 +2542,86 @@ More: [docs/guides/write-refusals.md#drain-grant-scope](../../docs/guides/write-
|---|---|---|---|---|---|---|
| Source relationship reconciliation is incomplete. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+### guest_attribution_missing
+
+<a id="guest_attribution_missing"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A write to a guest source carried no valid guest attribution (the X-Gbrain-Guest header or request-level _meta.guest with sender_label and group); nothing was written. | The request itself was wrong or no longer matches the brain; nothing was changed. | Send sender_label and group in _meta.guest or the X-Gbrain-Guest header, then save with a new request_id. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_attribution_missing](../../docs/guides/write-refusals.md#guest_attribution_missing)
+
+### guest_frontmatter_refused
+
+<a id="guest_frontmatter_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A guest page's frontmatter held a key outside the allowlist, or a guest_sender or guest_group that differs from its attribution; nothing was written. | The request itself was wrong or no longer matches the brain; nothing was changed. | Send only type, title, readable_by, guest_group, guest_sender and saved_at, matching the attribution. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_frontmatter_refused](../../docs/guides/write-refusals.md#guest_frontmatter_refused)
+
+### guest_mark_immutable
+
+<a id="guest_mark_immutable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A guest mark is never changed; it leaves only with its page. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_mark_immutable](../../docs/guides/write-refusals.md#guest_mark_immutable)
+
+### guest_page_immutable
+
+<a id="guest_page_immutable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A guest page is saved once, as a new page, and never changed, and a guest source holds no facts, takes or timeline entries; nothing was written. | The request itself was wrong or no longer matches the brain; nothing was changed. | Save the note again under a new slug, or ask the brain owner to promote it and edit the owner page. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_page_immutable](../../docs/guides/write-refusals.md#guest_page_immutable)
+
+### guest_page_promoted
+
+<a id="guest_page_promoted"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Reserved: the guest page was already kept as an owner page. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_page_promoted](../../docs/guides/write-refusals.md#guest_page_promoted)
+
+### guest_promotion_owner_only
+
+<a id="guest_promotion_owner_only"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Reserved: only the brain owner may keep a guest note as an owner page. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_promotion_owner_only](../../docs/guides/write-refusals.md#guest_promotion_owner_only)
+
+### guest_readers_invalid
+
+<a id="guest_readers_invalid"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A guest page's readable_by is not exactly the brain owner plus the one member or group the call speaks for; nothing was written. | The request itself was wrong or no longer matches the brain; nothing was changed. | Speak for one member or group and set readable_by to the owner and that principal. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_readers_invalid](../../docs/guides/write-refusals.md#guest_readers_invalid)
+
+### guest_source_database_only
+
+<a id="guest_source_database_only"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A guest source is database-only: it takes no local path or repository, and a source with one cannot become a guest source. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#guest_source_database_only](../../docs/guides/write-refusals.md#guest_source_database_only)
+
### harness_hook_duplicates
<a id="harness_hook_duplicates"></a>
@@ -5318,6 +5398,16 @@ Reasons: `missing`, `not_directory`, `permission_denied`, `symlink_loop`, `unrea
|---|---|---|---|---|---|---|
| Canonical preparation requires a source-content correction; this profile never writes repository files. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+### source_writer_restricted
+
+<a id="source_writer_restricted"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A write to a guest source came from a credential that is not on its writer list (the local CLI, an enforced member, or a removed writer included); nothing was written. | A guest source holds notes saved for people outside the brain; only the writers the brain owner listed create pages there, so nothing else can make a guest's words look like the owner's or change them. | Do not retry. Write to another source; who may write a guest source is the brain owner's decision. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#source_writer_restricted](../../docs/guides/write-refusals.md#source_writer_restricted)
+
### sources_not_readable
<a id="sources_not_readable"></a>
diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.md
index 13c70fb263..b58f4fb97e 100644
--- a/docs/guides/guest-notes.md
+++ b/docs/guides/guest-notes.md
@@ -5,10 +5,10 @@ offsite moved to Friday"). Those people are outside guests: they aren't you, and
their words shouldn't read as yours. A **guest source** is where gbrain keeps
their notes, apart from your own pages, with a record of who said what.
-This page is the operator view: what a guest source is and how to set one up.
-Saving notes into it, the warning every read shows on a guest note, and keeping a
-guest note as your own page arrive in later releases. Until then a guest source
-holds nothing unless a listed writer puts pages there.
+This page covers what a guest source is, how to set one up, and how a listed
+writer (the broker your agent's host runs) saves notes into it. The warning every
+read shows on a guest note, and keeping a guest note as your own page, arrive in
+later releases.
## What a guest source is
@@ -19,9 +19,10 @@ enforces, whatever program writes to it:
frontmatter, slug or source, needs a writer on the source's writer list. A
writer is named the way gbrain records who made a write: `oauth_client:<client
id>` for an OAuth client, `legacy_token:<token id>` for a legacy token. Your own
- CLI is not on the list, so `gbrain put --source guests` is refused with
- `source_writer_restricted`. Soft delete, restore, purge and maintenance that
- touches no page text still work for you.
+ CLI is not on the list, so `gbrain put --source guests`, `gbrain import`,
+ `remember` and `add_link` there are refused with `source_writer_restricted`.
+ Deleting and restoring a guest page from your own CLI still work, and so do
+ purge and maintenance that touches no page text.
- **Never above external, untrusted.** Every page there is stored at the
`external_untrusted` trust tier or lower ([memory trust](memory-trust.md)), even
when a write path would normally raise it (an owner rewrite, a backfill, a
@@ -77,12 +78,60 @@ A source that isn't a guest source has no writer list, so the command refuses
it. Changing the list is your decision on the brain host; nothing in gbrain
widens it on its own.
+## Save a guest note (for the writer)
+
+A listed writer saves a note with one `put_page` call to the guest source. The
+call says who it speaks for and who the guest is, beside the tool arguments:
+
+- **Audience:** the `X-Gbrain-On-Behalf-Of` header (or request-level
+ `_meta.on_behalf_of`) names exactly one member or group, for example
+ `group:team-a`. The credential's `may_act_for` must allow it.
+- **Guest attribution:** the `X-Gbrain-Guest` header in URL-encoded form,
+ `sender_label=Bob%20Example&group=team-a`, or request-level `_meta.guest`,
+ `{"sender_label": "Bob Example", "group": "team-a"}`. A label is 1 to 64
+ characters with no control or format characters and none of `·`, `[`, `]`,
+ `<`, `>` or `"`; the group is a slug of `a-z`, `0-9` and `-`. Without it
+ the write is refused `guest_attribution_missing`. Attribution sent with a write
+ to any other source is ignored and stored nowhere.
+
+The page content keeps to a short frontmatter: only `type`, `title`,
+`readable_by`, `guest_group`, `guest_sender` and `saved_at`, with
+`guest_sender` and `guest_group` equal to the attribution
+(`guest_frontmatter_refused` otherwise). `readable_by` is exactly you (the
+brain owner) and the audience, for example `[alice-example, group:team-a]`
+(`guest_readers_invalid` otherwise):
+
+```markdown
+---
+type: note
+title: Offsite moved to Friday
+readable_by: [alice-example, group:team-a]
+guest_group: team-a
+guest_sender: Bob Example
+saved_at: 2026-11-13T10:00:00Z
+---
+The offsite moved to Friday.
+```
+
+A guest note is saved once, as a new page. Saving to a slug that exists is
+refused `revision_required`, and `force`, `expected_revision`, `edit_page`,
+`append_page`, `add_timeline_entry`, `add_link`, `remember`, `put_pages` and
+uploads are refused `guest_page_immutable`; a writer may delete its notes.
+gbrain checks the writer list again when the note publishes, so a writer you
+remove in between is refused `source_writer_restricted`. Every refusal is in
+[write refusals](write-refusals.md#guest-source-refusals).
+
+Guest notes feed nothing else in your brain: no facts, takes, timeline entries,
+atoms or link edges are made from them, and the dream cycle and extraction skip
+the guest source. Search, query and get still find them.
+
## What is stored
Three database tables back a guest source. `guest_sources` names each guest
-source, its writer list and its trust ceiling. `guest_marks` will hold, for each
-guest note, who it was saved for, from which group (for example `group:team-a`),
-the sender's label (for example `bob-example`), when and by which writer; a mark
-can never be edited and is removed only when its page is purged.
-`guest_promotions` will record guest notes you keep as your own pages. In this
-release nothing writes the last two yet.
+source, its writer list and its trust ceiling. `guest_marks` holds, for each
+guest note, who it was saved for (`member:bob-example` or `group:team-a`),
+from which group, the sender's label (for example `Bob Example`), when, by which
+writer and in which request; the mark is written in the same transaction as the
+page, can never be edited and is removed only when its page is purged.
+`guest_promotions` will record guest notes you keep as your own pages; nothing
+writes it yet.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index c44666a8f2..72610082e5 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -1074,6 +1074,24 @@ live in the database, so they are the same on a repo-less brain.
| <a id="on_behalf_of_not_permitted"></a>`on_behalf_of_not_permitted` | The credential's `may_act_for` (for a stdio server, config `mcp.stdio_may_act_for`) does not list every audience entry. The message names the credential and the entries it may not act for. Nothing was read. | The brain operator decides: `fix` carries `gbrain auth rescope --token <name> --may-act-for <list>` (or `--client <id>`, or `gbrain config set mcp.stdio_may_act_for <list>`) with the full list to approve. The agent never runs it; until then, call without the audience. |
| <a id="on_behalf_of_in_arguments"></a>`on_behalf_of_in_arguments` | A tool call carried `on_behalf_of` in its arguments (top level or an arguments-level `_meta`), where conversation text could set it. Nothing was read. | Remove it from the arguments. Harness code sends the audience as the header or request-level `_meta.on_behalf_of`; a stdio client that cannot set request-level `_meta` uses a credential bound to one member or config `mcp.stdio_member`. |
+## Guest source refusals
+
+A guest source (`gbrain guests init`, [guest notes](guest-notes.md)) holds notes saved for people outside the brain.
+Its pages are written only by the credentials on its writer list, once each, as new pages; everything else is refused
+before anything is written. The rules live in the database, so they are the same on a repo-less brain.
+
+| Code | What happened | What to do |
+|---|---|---|
+| <a id="source_writer_restricted"></a>`source_writer_restricted` | A write to a guest source came from a credential that is not on the source's writer list: a remote token or client that was never listed, the local CLI (`gbrain put`, `gbrain import`, `remember`, `add_link`), an enforced member, or a listed writer that was removed between admission and publication (the receipt ends `failed` with this code). Only the brain owner on the brain host may delete or restore a guest page. Nothing was written. | Do not retry. Write the content to another source. Who may write a guest source is the brain owner's decision; an agent never changes the writer list. |
+| <a id="guest_page_immutable"></a>`guest_page_immutable` | A listed writer tried something other than saving a new page: a write with `force` or `expected_revision`, `edit_page`, `append_page`, `add_timeline_entry`, `add_link`, `remember`, `put_pages`, an upload, or a `put_page` over a deleted guest page. The database refuses facts, takes and timeline rows in a guest source with the same code. A plain `put_page` to a slug that already exists is refused `revision_required`. Nothing was written. | Save the note again under a new slug. To change a guest note, the brain owner promotes it to an owner page and edits that. |
+| <a id="guest_page_promoted"></a>`guest_page_promoted` | Reserved for guest-note promotion (a later release): the guest page was already kept as an owner page. | Read the owner page the message names. |
+| <a id="guest_attribution_missing"></a>`guest_attribution_missing` | A listed writer's `put_page` carried no guest attribution, or a malformed one. Attribution is the `X-Gbrain-Guest` header (`sender_label=<URL-encoded label>&group=<group-slug>`) or request-level `_meta.guest` (`{"sender_label": "...", "group": "..."}`). A label is 1 to 64 characters with no control, format or line-separator characters and none of `·`, `[`, `]`, `<`, `>` or `"`; a group slug is 1 to 64 of `a-z`, `0-9` and `-`. Sending both with different values is refused too. Nothing was written. | Fix the harness code that sets it, then save the note with a new `request_id`. Attribution sent with a write to any other source is ignored. |
+| <a id="guest_frontmatter_refused"></a>`guest_frontmatter_refused` | A guest page's frontmatter held a key outside `type`, `title`, `readable_by`, `guest_group`, `guest_sender` and `saved_at` (for example `visibility`, `trust_tier`, `tags` or `always_load`), or its `guest_sender` or `guest_group` differs from the attribution. Nothing was written. | Send only the allowed keys, with `guest_sender` and `guest_group` equal to the attribution's `sender_label` and `group`. |
+| <a id="guest_readers_invalid"></a>`guest_readers_invalid` | A guest page's `readable_by` is not exactly the brain owner plus the one member or group the call speaks for (`X-Gbrain-On-Behalf-Of`), the call speaks for several principals or for `guest`, or the brain has no owner set. A missing `readable_by` under an audience is refused `readable_by_invalid` first. Nothing was written. | Speak for one member or group and set `readable_by` to the owner and that principal, for example `[alice-example, group:team-a]`. The owner is set on the brain host with `gbrain access owner set`. |
+| <a id="guest_promotion_owner_only"></a>`guest_promotion_owner_only` | Reserved for guest-note promotion (a later release): only the brain owner may keep a guest note as an owner page. | Ask the brain owner. |
+| <a id="guest_mark_immutable"></a>`guest_mark_immutable` | Something tried to change a guest mark (who a guest page was saved for, from which group, when and by which writer). A mark is never changed; it leaves only with its page. Nothing was written. | Do not retry. |
+| <a id="guest_source_database_only"></a>`guest_source_database_only` | A guest source was given a local path or repository, or a source that has one was made a guest source. A guest source is database-only. Nothing was written. | Use a new source id for the guest source (`gbrain guests init --source <id>`). |
+
## Unscoped reads on a brain that serves several people
A brain serves several people when two or more members are enabled, or when config `access.serves` is `several`
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 9986ee4056..ff52aa34a2 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -209,6 +209,8 @@ test/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-
test/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, include_deleted, fuzzy precedence, grant precedence 5 source-surface-helper
test/git-env-guard.test.ts (file-level) 5 readFileSync
test/grant-execution-prerequisites.test.ts execution prerequisite table 1 readFileSync
+test/guest-derived-registry.test.ts guest derived-producer registry 2 readFileSync
+test/guest-derived-registry.test.ts guest pages feed no derived rows (pglite, repo-less) 3 readFileSync
test/harness-onboarding.test.ts harness identity and private handoff 6 readFileSync
test/hook-command.serial.test.ts user-prompt 18 source-surface-helper
test/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSync
diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.ts
index be9eb3eb2d..e35ba633a7 100644
--- a/src/commands/extract-timeline-db.ts
+++ b/src/commands/extract-timeline-db.ts
@@ -97,9 +97,9 @@ function anchorFor(page: Page, slug: string) {
}
async function walkRefs(engine: BrainEngine, opts: TimelineDbOptions) {
- const all = opts.sourceIdFilter
+ const all = await (await import('../core/guests/derived.ts')).withoutGuestSources(engine, 'extract', opts.sourceIdFilter
? (await engine.listAllPageRefs()).filter(r => r.source_id === opts.sourceIdFilter)
- : await engine.listAllPageRefs();
+ : await engine.listAllPageRefs(), ref => ref.source_id);
const wanted = opts.slugs ? new Set(opts.slugs) : null;
return filterRefsSince(wanted ? all.filter(r => wanted.has(r.slug)) : all, opts.since);
}
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 070e918ea5..b713adea88 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -109,6 +109,7 @@ import { isSegmentedPage, withoutBody } from '../core/page-body/page-shape.ts';
import { extractSegmentedPageLinks } from '../core/page-body/segment-links.ts';
import { STALE_TIME_BUDGET_MS, formatStaleCounts, staleExtractionCounts } from '../core/extraction-lag.ts';
import { assertStaleSourceModeUnambiguous } from './extract-stale-options.ts';
+import { withoutGuestSources } from '../core/guests/derived.ts';
// Batch size for addLinksBatch / addTimelineEntriesBatch.
// Postgres bind-parameter limit is 65535. Links use 4 cols/row → 16K hard ceiling;
@@ -1896,12 +1897,9 @@ async function extractLinksFromDB(
// resolve — the filter is on WHICH pages we extract FROM, not what
// we can resolve TO.
const readAt = await wantedReadAt(engine);
- const allRefs = sourceIdFilter
- ? (await engine.listAllPageRefs()).filter(r => r.source_id === sourceIdFilter)
- : await engine.listAllPageRefs();
- const fullRefsForResolver = sourceIdFilter
- ? await engine.listAllPageRefs()
- : allRefs;
+ const listedRefs = await engine.listAllPageRefs();
+ const allRefs = await withoutGuestSources(engine, 'extract', sourceIdFilter ? listedRefs.filter(r => r.source_id === sourceIdFilter) : listedRefs, ref => ref.source_id);
+ const fullRefsForResolver = listedRefs;
// For backward-compat checks (`allSlugs.has(...)` calls below), we still
// need a flat slug set. ALSO a per-slug → [sources] map for F10 resolution.
//
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 8cd5daca33..3c92345a33 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -51,6 +51,7 @@ import { getEmbeddingModel } from '../core/ai/gateway.ts';
import { managedRootMarkerFor } from '../core/persistence/root-registry.ts';
import { readManagedMode } from '../core/persistence/ownership.ts';
import { readPageBodyPolicy } from '../core/page-body/limits.ts';
+import { readGuestSource } from '../core/guests/sources.ts';
/** Return a refusal when an import target lies outside every admitted root. */
export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {
@@ -467,6 +468,10 @@ export async function runImport(
}
}
}
+ if (await readGuestSource(engine, sourceId ?? 'default')) {
+ console.error(`source_writer_restricted: source ${sourceId ?? 'default'} is a guest source; only its listed writers save pages there, through put_page. Import into another source.`);
+ throw new ImportAbortError('source_writer_restricted: guest sources take no import');
+ }
if (!currentCompanyBrainSync(sourceId) && await getCompanyBrainProfile(engine, sourceId ?? 'default')) {
console.error('This source accepts only its approved committed company-brain manifest. Use sources resume or sync; ordinary import cannot write back to this read-only repository.');
throw new ImportAbortError('company-brain sources require approved committed ingestion');
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index e618c75a41..69c5c6cf2b 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -47,6 +47,7 @@ import {
import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';
import { ROOM_HEADER } from '../core/access/room.ts';
+import { GUEST_HEADER } from '../core/guests/admission.ts';
import { ACTOR_HEADER, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER } from '../core/access/actor-model.ts';
import { parseAgentLabel, AGENT_LABEL_HEADER } from '../core/persistence/attribution.ts';
import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';
@@ -79,6 +80,8 @@ interface McpRequestState {
onBehalfOfHeader: string | undefined;
/** GBRA-498: the X-Gbrain-Room header (the room an answer goes into); it only marks results, never narrows or widens them. */
roomHeader: string | undefined;
+ /** GBRA-504: the X-Gbrain-Guest header (guest attribution); read only for a write to a guest source. */
+ guestHeader: string | undefined;
/** GST-359 C1: the x-qm-actor header (a trusted system names the person); honoured in dispatch only for an attest credential. */
actorHeader: string | undefined;
/** GST-359 D: the x-qm-audience header (QM's channel audience, wave 2); any request carrying it is refused before any work. */
@@ -207,7 +210,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {
surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));
const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));
const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient,
- onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), roomHeader: req.get(ROOM_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER),
+ onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), roomHeader: req.get(ROOM_HEADER), guestHeader: req.get(GUEST_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER),
userAgent: req.get('user-agent'), agentLabel: parseAgentLabel(req.get(AGENT_LABEL_HEADER)) };
const server = createMcpRequestServer(ctx, state, writeback, writeback?.enabled ? await engine.getConfig(OWNER_MEMBER_KEY).catch(() => null) : null);
await serveMcpRequest(server, req, res);
@@ -463,6 +466,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques
...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),
onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },
room: { header: state.roomHeader, requestMeta: (request.params as { _meta?: unknown })._meta },
+ guest: { header: state.guestHeader, requestMeta: (request.params as { _meta?: unknown })._meta },
mcpCaller: { client: authInfo.clientName, userAgent: state.userAgent, meta: (request.params as { _meta?: Record<string, unknown> })._meta },
actor: { header: state.actorHeader, audience: state.audienceHeader },
...(state.agentLabel ? { agentLabel: state.agentLabel } : {}),
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index d92fdb7e16..73e7f6d72a 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1942,6 +1942,13 @@ async function runCycleUnscoped(
phase_scope: PHASE_SCOPE[phase],
},
}));
+ // GBRA-504: a cycle scoped to a guest source skips every phase that would derive rows from guest pages (guests/derived.ts).
+ if (engine && opts.sourceId && await (await import('./guests/note.ts')).isGuestSource(engine, opts.sourceId)) {
+ 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: opts.sourceId } });
+ phases = phases.filter(p => !guestSkipped.has(p));
+ }
// Capture as a const so it narrows to `string` inside the `else` branches of
// the per-phase `if (brainDir === null)` guards, even within async closures
diff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.ts
index 00d3167b86..7bbbac4b4e 100644
--- a/src/core/cycle/chronicle.ts
+++ b/src/core/cycle/chronicle.ts
@@ -153,7 +153,9 @@ export async function runPhaseChronicle(engine: BrainEngine, opts: ChroniclePhas
WHERE c.state IN ('pending','failed') AND NOT EXISTS (SELECT 1 FROM pages p
WHERE p.id=c.page_id AND p.content_hash=c.content_hash AND p.deleted_at IS NULL)`);
}
- const sources = (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map((s) => s.id);
+ const { withoutGuestSources } = await import('../guests/derived.ts');
+ const sources = await withoutGuestSources(engine, 'chronicle',
+ (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map((s) => s.id), id => id);
details.sources = sources.length;
for (const sourceId of sources) {
await discover(engine, sourceId, { managed, enabled, activatedAt, settings, now: now(), dryRun });
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index 91b13b1bdc..e228bc0dbe 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -207,7 +207,8 @@ export async function runPhaseConversationFactsBackfill(
const maxTotalWalltimeMs = cfg.maxTotalWalltimeMin * 60_000;
const maxWalltimeMs = cfg.maxWalltimeMin * 60_000;
- const listed = await listSources(engine);
+ const { withoutGuestSources } = await import('../guests/derived.ts');
+ const listed = await withoutGuestSources(engine, 'conversation_facts_backfill', await listSources(engine), src => src.id);
const excluded = listed.filter(src => cfg.excludeSources.includes(src.id)).map(src => src.id);
const sources = listed.filter(src => !excluded.includes(src.id));
if (sources.length === 0) {
diff --git a/src/core/cycle/enrich-thin.ts b/src/core/cycle/enrich-thin.ts
index df7c2856ca..42cab3723b 100644
--- a/src/core/cycle/enrich-thin.ts
+++ b/src/core/cycle/enrich-thin.ts
@@ -189,7 +189,8 @@ export async function runPhaseEnrichThin(
}
const maxTotalWalltimeMs = cfg.maxTotalWalltimeMin * 60_000;
- const sources = await listSources(engine);
+ const { withoutGuestSources } = await import('../guests/derived.ts');
+ const sources = await withoutGuestSources(engine, 'enrich_thin', await listSources(engine), src => src.id);
if (sources.length === 0) {
return {
phase: 'enrich_thin',
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index bef8781f62..792230e5ae 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -709,6 +709,9 @@ 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 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/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 73f6873560..8cb4559ee3 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -842,6 +842,7 @@ export async function runExtractFacts(
phantomsLockBusy: false,
phantomsMorePending: false,
};
+ if (await (await import('../guests/derived.ts')).skipsGuestSource(engine, 'extract_facts', sourceId)) return result;
// ── Fence unfenced rows (#5299) ─────────────────────────────────
// The inline writer's DB-only fallback keeps producing `row_num IS NULL`
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index fb6d0ef84a..a2deaf52a7 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -44,6 +44,7 @@ import { scrubPurgedSlugs } from '../feedback/store.ts';
import { scrubPurgedNameStores } from '../persistence/purge-name-stores.ts';
import { scrubPurgedSlugHolds, scrubPurgedSlugStores } from '../persistence/purge-slug-stores.ts';
import { expireGonePageFacts } from '../facts/gone-page-facts.ts';
+import { guestSourceExclusionSql } from '../guests/derived.ts';
/**
* PGLite can return zero rows from `INSERT ... ON CONFLICT DO UPDATE ...
@@ -804,7 +805,7 @@ function linkExtractionHeld(versionTs?: string) {
return sqlFragment`COALESCE(links_extract_failure->>'state' = 'held' AND links_extract_failure->>'revision' = knowledge_revision::text${generation}, false)`;
}
-type StaleOpts = { sourceId?: string; versionTs?: string; attendance?: 'exclude' | 'blocked'; held?: 'exclude' | 'only'; wantedProducers?: readonly string[] };
+type StaleOpts = { sourceId?: string; versionTs?: string; attendance?: 'exclude' | 'blocked'; held?: 'exclude' | 'only'; wantedProducers?: readonly string[]; guests?: boolean };
/**
* Shared stale-for-extraction predicate. `attendance` narrows it by the #5761
@@ -824,8 +825,10 @@ function stalePagesWhere(opts?: StaleOpts) {
: opts?.attendance === 'blocked' ? sqlFragment` AND links_attendance_blocked_revision = knowledge_revision` : sqlFragment``;
const held = opts?.held === 'exclude' ? sqlFragment` AND NOT ${linkExtractionHeld(opts.versionTs)}`
: opts?.held === 'only' ? sqlFragment` AND ${linkExtractionHeld(opts.versionTs)}` : sqlFragment``;
+ // GBRA-504: a guest page is never extracted (guests/derived.ts), so it is never stale; `guests: false` is the pre-v312 shape.
+ const guests = opts?.guests === false ? sqlFragment`` : sqlFragment` AND ${trustedSql(guestSourceExclusionSql('extract', 'pages'))}`;
// A quarantined page is hidden from search; it is neither re-extracted nor counted as stale.
- return sqlFragment`deleted_at IS NULL AND ${trustedSql(quarantineFilterFragment('pages'))} AND ${version}${source}${attendance}${held}`;
+ return sqlFragment`deleted_at IS NULL AND ${trustedSql(quarantineFilterFragment('pages'))} AND ${version}${source}${attendance}${held}${guests}`;
}
/** The pages (unaliased `pages` rows) link extraction still owes work: stale, not attendance-blocked, not held (rank_entities' remote coverage). */
@@ -839,9 +842,9 @@ export function staleForExtractionSql(versionTs: string): SqlFragment {
* `attendance: false` is the pre-v180 shape (no marker column: nothing is attendance-blocked). `held` (GBRA-130 A-1) also
* excludes held pages from the stale count and counts them (`held: false` is the pre-v258 shape: nothing is held).
*/
-export function extractionLagStatement(opts: { sourceId?: string; versionTs: string; attendance: boolean; held?: boolean; wantedProducers?: readonly string[] }): { text: string; params: unknown[] } {
+export function extractionLagStatement(opts: { sourceId?: string; versionTs: string; attendance: boolean; held?: boolean; guests?: boolean; wantedProducers?: readonly string[] }): { text: string; params: unknown[] } {
const source = opts.sourceId ? sqlFragment` AND source_id = ${opts.sourceId}` : sqlFragment``;
- const base = { versionTs: opts.versionTs, wantedProducers: opts.wantedProducers };
+ const base = { versionTs: opts.versionTs, wantedProducers: opts.wantedProducers, guests: opts.guests };
const stale = stalePagesWhere({ ...base, ...(opts.attendance ? { attendance: 'exclude' as const } : {}), ...(opts.held ? { held: 'exclude' as const } : {}) });
const blocked = opts.attendance ? sqlFragment`count(*) FILTER (WHERE ${stalePagesWhere({ ...base, attendance: 'blocked' })})::int` : sqlFragment`0`;
const held = opts.held ? sqlFragment`count(*) FILTER (WHERE ${stalePagesWhere({ ...base, held: 'only' })})::int` : sqlFragment`0`;
@@ -852,7 +855,7 @@ export function extractionLagStatement(opts: { sourceId?: string; versionTs: str
/** GBRA-130 A-1: up to `limit` held pages with their failure code, oldest page first, for doctor's message. */
export function heldLinkExtractionStatement(opts: { sourceId?: string; versionTs: string; limit: number }): { text: string; params: unknown[] } {
return renderFragment(sqlFragment`SELECT slug, source_id, links_extract_failure->>'code' AS code FROM pages
- WHERE ${stalePagesWhere({ sourceId: opts.sourceId, versionTs: opts.versionTs, held: 'only' })} ORDER BY id LIMIT ${opts.limit}`);
+ WHERE ${stalePagesWhere({ sourceId: opts.sourceId, versionTs: opts.versionTs, held: 'only', guests: false })} ORDER BY id LIMIT ${opts.limit}`);
}
export async function countStalePagesForExtraction(exec: ScopedRead, opts?: StaleOpts): Promise<number> {
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index 5c7679f6d9..0c2016cd7a 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -42,6 +42,16 @@ export const ERROR_CATALOGUE = {
on_behalf_of_unknown_member: { code: 'on_behalf_of_unknown_member', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member' },
on_behalf_of_not_permitted: { code: 'on_behalf_of_not_permitted', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted' },
on_behalf_of_in_arguments: { code: 'on_behalf_of_in_arguments', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments' },
+ // GBRA-504 guest sources: writer list, create-only guest pages, attribution, frontmatter and readers.
+ source_writer_restricted: { code: 'source_writer_restricted', docs: 'docs/guides/write-refusals.md#source_writer_restricted' },
+ guest_page_immutable: { code: 'guest_page_immutable', docs: 'docs/guides/write-refusals.md#guest_page_immutable' },
+ guest_page_promoted: { code: 'guest_page_promoted', docs: 'docs/guides/write-refusals.md#guest_page_promoted' },
+ guest_attribution_missing: { code: 'guest_attribution_missing', docs: 'docs/guides/write-refusals.md#guest_attribution_missing' },
+ guest_frontmatter_refused: { code: 'guest_frontmatter_refused', docs: 'docs/guides/write-refusals.md#guest_frontmatter_refused' },
+ guest_readers_invalid: { code: 'guest_readers_invalid', docs: 'docs/guides/write-refusals.md#guest_readers_invalid' },
+ guest_promotion_owner_only: { code: 'guest_promotion_owner_only', docs: 'docs/guides/write-refusals.md#guest_promotion_owner_only' },
+ guest_mark_immutable: { code: 'guest_mark_immutable', docs: 'docs/guides/write-refusals.md#guest_mark_immutable' },
+ guest_source_database_only: { code: 'guest_source_database_only', docs: 'docs/guides/write-refusals.md#guest_source_database_only' },
// GST-363: a brain that serves several people knows who is asking (remote reads, credential creation).
requester_scope_required: { code: 'requester_scope_required', docs: 'docs/guides/write-refusals.md#requester_scope_required' },
credential_scope_required: { code: 'credential_scope_required', docs: 'docs/guides/write-refusals.md#credential_scope_required' },
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 4f000150ed..08afef3097 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -899,6 +899,15 @@ export const CODES = {
take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },
target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
timeline_comment_markup: { class: 'caller', summary: "A stored timeline row carries HTML comment markup, so gbrain keeps it database-side and never writes it back into the page; clean it with gbrain repair timeline-comments.", docs: 'docs/guides/repair.md#timeline-comments' },
+ source_writer_restricted: { class: 'caller', summary: "A write to a guest source came from a credential that is not on its writer list (the local CLI, an enforced member, or a removed writer included); nothing was written.", why: "A guest source holds notes saved for people outside the brain; only the writers the brain owner listed create pages there, so nothing else can make a guest's words look like the owner's or change them.", docs: 'docs/guides/write-refusals.md#source_writer_restricted', suggestion: "Do not retry. Write to another source; who may write a guest source is the brain owner's decision." },
+ guest_page_immutable: { class: 'caller', summary: 'A guest page is saved once, as a new page, and never changed, and a guest source holds no facts, takes or timeline entries; nothing was written.', docs: 'docs/guides/write-refusals.md#guest_page_immutable', suggestion: 'Save the note again under a new slug, or ask the brain owner to promote it and edit the owner page.' },
+ guest_page_promoted: { class: 'caller', summary: 'Reserved: the guest page was already kept as an owner page.', docs: 'docs/guides/write-refusals.md#guest_page_promoted' },
+ guest_attribution_missing: { class: 'caller', summary: 'A write to a guest source carried no valid guest attribution (the X-Gbrain-Guest header or request-level _meta.guest with sender_label and group); nothing was written.', docs: 'docs/guides/write-refusals.md#guest_attribution_missing', suggestion: 'Send sender_label and group in _meta.guest or the X-Gbrain-Guest header, then save with a new request_id.' },
+ guest_frontmatter_refused: { class: 'caller', summary: "A guest page's frontmatter held a key outside the allowlist, or a guest_sender or guest_group that differs from its attribution; nothing was written.", docs: 'docs/guides/write-refusals.md#guest_frontmatter_refused', suggestion: 'Send only type, title, readable_by, guest_group, guest_sender and saved_at, matching the attribution.' },
+ guest_readers_invalid: { class: 'caller', summary: "A guest page's readable_by is not exactly the brain owner plus the one member or group the call speaks for; nothing was written.", docs: 'docs/guides/write-refusals.md#guest_readers_invalid', suggestion: 'Speak for one member or group and set readable_by to the owner and that principal.' },
+ guest_promotion_owner_only: { class: 'caller', summary: 'Reserved: only the brain owner may keep a guest note as an owner page.', docs: 'docs/guides/write-refusals.md#guest_promotion_owner_only' },
+ guest_mark_immutable: { class: 'caller', summary: 'A guest mark is never changed; it leaves only with its page.', docs: 'docs/guides/write-refusals.md#guest_mark_immutable' },
+ guest_source_database_only: { class: 'caller', summary: 'A guest source is database-only: it takes no local path or repository, and a source with one cannot become a guest source.', docs: 'docs/guides/write-refusals.md#guest_source_database_only' },
readable_by_invalid: { class: 'caller', summary: 'A remote write\'s readable_by is malformed, removes the field from a page that names readers, or would leave the page unreadable by the writer; nothing was written.', docs: 'docs/guides/write-refusals.md#readable_by_invalid' },
timeline_rows_would_be_removed: { class: 'caller', summary: "A remote put_page or put_pages entry has no Timeline section and would delete the page's dated entries; resend it with the section or with drop_timeline: true.", docs: 'docs/guides/write-refusals.md#timeline_rows_would_be_removed' },
timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },
diff --git a/src/core/extraction-lag.ts b/src/core/extraction-lag.ts
index 7245d3d162..479516c10a 100644
--- a/src/core/extraction-lag.ts
+++ b/src/core/extraction-lag.ts
@@ -62,20 +62,25 @@ async function readLagRow(engine: BrainEngine, opts: { sourceId?: string; timeou
const versionTs = await effectiveLinkExtractorWatermark(engine);
// #9295: count the wanted rows the configured sweep re-resolves (a managed or frontmatter sweep: every producer).
const wantedProducers = await managedPersistenceEnabled(engine) || await resolveIncludeFrontmatter(engine) ? undefined : ['body'];
- const read = async (attendance: boolean, held: boolean) => {
- const { text, params } = extractionLagStatement({ sourceId: opts.sourceId, versionTs, attendance, held, wantedProducers });
+ const read = async (attendance: boolean, held: boolean, guests: boolean) => {
+ const { text, params } = extractionLagStatement({ sourceId: opts.sourceId, versionTs, attendance, held, guests, wantedProducers });
return (await engine.executeRaw<{ total: number; stale: number; attendance_blocked: number; held: number }>(text, params, { timeoutMs: opts.timeoutMs ?? 10_000 }))[0];
};
- let row;
- try { row = await read(true, true); } catch (e) {
- if (isMissingSchemaObject(e, 'column', 'links_extract_failure')) row = await read(true, false).catch(async inner => {
- if (!isMissingSchemaObject(inner, 'column', 'links_attendance_blocked_revision')) throw inner;
- return read(false, false);
- });
- else if (isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) row = await read(false, false);
- else throw e;
+ const readShape = async (guests: boolean) => {
+ try { return await read(true, true, guests); } catch (e) {
+ if (isMissingSchemaObject(e, 'column', 'links_extract_failure')) return read(true, false, guests).catch(async inner => {
+ if (!isMissingSchemaObject(inner, 'column', 'links_attendance_blocked_revision')) throw inner;
+ return read(false, false, guests);
+ });
+ if (isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) return read(false, false, guests);
+ throw e;
+ }
+ };
+ // GBRA-504: guest pages are never extracted, so they are not lag; a brain before v312 has no guest_sources table.
+ try { return await readShape(true); } catch (e) {
+ if (!isMissingSchemaObject(e, 'table', 'guest_sources')) throw e;
+ return readShape(false);
}
- return row;
}
/**
diff --git a/src/core/guests/admission.ts b/src/core/guests/admission.ts
new file mode 100644
index 0000000000..2c8abd0f7e
--- /dev/null
+++ b/src/core/guests/admission.ts
@@ -0,0 +1,158 @@
+/**
+ * Guest notes, slice 2 (GBRA-504): write admission for a guest source.
+ *
+ * A guest source (guests/sources.ts) takes page writes only from a principal on its writer list, only as a new page
+ * through put_page, and only with the guest attribution the broker sends beside the call: the X-Gbrain-Guest header
+ * (URL-encoded form, `sender_label=<label>&group=<group-slug>`) or request-level `_meta.guest`
+ * (`{ sender_label, group }`). The attribution joins the stored write intent as `guest_note`, so a
+ * replay with different attribution is idempotency_conflict, and publication turns it into the page's guest_marks row.
+ * The page's frontmatter keeps to an allowlist, names the sender and group the attribution names, and is readable
+ * by exactly the brain owner plus the call's one audience principal. Every refusal here writes nothing; the database
+ * trigger (trust/schema.ts GUEST_GUARD) is the backstop for any path that bypasses this module.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { parseMarkdownHead } from '../markdown.ts';
+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';
+
+export { GUEST_NOTE_INTENT_KEY, type GuestAttribution } from './note.ts';
+
+export const GUEST_HEADER = 'X-Gbrain-Guest';
+/** The only frontmatter keys a guest page may carry. */
+export const GUEST_FRONTMATTER_KEYS: readonly string[] = ['type', 'title', 'readable_by', 'guest_group', 'guest_sender', 'saved_at'];
+const DOCS = (code: string) => `docs/guides/write-refusals.md#${code}`;
+
+/** The attribution channels a transport saw: the header and request-level _meta (its `guest` key). */
+export interface GuestChannels { header?: string | null; requestMeta?: unknown }
+
+const LABEL_FORBIDDEN = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}·[\]<>"]/u;
+const GROUP_RE = /^[a-z0-9-]{1,64}$/;
+const isObj = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);
+
+export function guestAttributionMissing(why: string): OperationError {
+ return new OperationError('guest_attribution_missing', `A write to a guest source needs guest attribution: ${why}. Nothing was written.`,
+ 'Send the sender label and group slug beside the call, as request-level _meta.guest {"sender_label": "...", "group": "..."} or the X-Gbrain-Guest header (sender_label=<url-encoded label>&group=<group-slug>). A label is 1 to 64 characters with no control or format characters and none of · [ ] < > ".',
+ DOCS('guest_attribution_missing'));
+}
+
+function checked(value: unknown, channel: string): GuestAttribution {
+ if (!isObj(value)) throw guestAttributionMissing(`${channel} is not an object with sender_label and group`);
+ const { sender_label: label, group } = value;
+ if (typeof label !== 'string' || [...label].length < 1 || [...label].length > 64 || LABEL_FORBIDDEN.test(label) || label.trim() !== label) {
+ throw guestAttributionMissing(`${channel} sender_label is missing or not an allowed label`);
+ }
+ if (typeof group !== 'string' || !GROUP_RE.test(group)) throw guestAttributionMissing(`${channel} group is missing or not a group slug`);
+ return { sender_label: label, group };
+}
+
+/** The attribution a call carries, or null when it carries none; malformed or disagreeing channels refuse. */
+export function parseGuestAttribution(channels: GuestChannels | undefined): GuestAttribution | null {
+ const header = typeof channels?.header === 'string' && channels.header.trim() !== '' ? channels.header : null;
+ const meta = isObj(channels?.requestMeta) && Object.hasOwn(channels.requestMeta, 'guest') ? channels.requestMeta.guest : undefined;
+ let fromHeader: GuestAttribution | null = null;
+ if (header !== null) {
+ const form = new URLSearchParams(header);
+ fromHeader = checked({ sender_label: form.get('sender_label'), group: form.get('group') }, 'the ' + GUEST_HEADER + ' header');
+ }
+ const fromMeta = meta === undefined ? null : checked(meta, '_meta.guest');
+ if (fromHeader && fromMeta && (fromHeader.sender_label !== fromMeta.sender_label || fromHeader.group !== fromMeta.group)) {
+ throw guestAttributionMissing('the ' + GUEST_HEADER + ' header and _meta.guest name different senders or groups');
+ }
+ return fromMeta ?? fromHeader;
+}
+
+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.",
+ DOCS('source_writer_restricted'));
+}
+
+export function guestPageImmutable(what: string): OperationError {
+ return new OperationError('guest_page_immutable', `${what}: a guest page is saved once, as a new page, and never changed. Nothing was written.`,
+ 'Save the note again under a new slug with put_page, or ask the brain owner to promote the page (gbrain guests promote) and edit the owner page.',
+ DOCS('guest_page_immutable'));
+}
+
+const principalKey = (principal: Principal) => `${principal.kind}:${principal.id}`;
+export const isListedWriter = (guest: Pick<GuestSource, 'writers'>, principal: Principal) => guest.writers.includes(principalKey(principal));
+
+/**
+ * The first gate on a guest source, before any page is read: who may submit which operation. A principal not on the
+ * writer list may only delete or restore, and only from the trusted local CLI (the owner); a listed writer may delete,
+ * or create through a plain single put_page. Returns the attribution a listed writer's put_page carries.
+ */
+export function admitGuestOperation(guest: GuestSource, input: { principal: Principal; operation: string; remote: boolean;
+ plainPut: boolean; params: Record<string, unknown>; channels: GuestChannels | undefined }): GuestAttribution | null {
+ const { principal, operation } = input;
+ if (!isListedWriter(guest, principal)) {
+ if (!input.remote && (operation === 'delete_page' || operation === 'restore_page')) return null;
+ throw sourceWriterRestricted(guest.source_id);
+ }
+ if (operation === 'delete_page') return null;
+ if (operation !== 'put_page') throw guestPageImmutable(`${operation} on a guest source`);
+ if (!input.plainPut) throw guestPageImmutable('A batch, staged-upload or imported page write on a guest source');
+ if (input.params.force === true || input.params.expected_revision !== undefined) throw guestPageImmutable('force or expected_revision on a guest page');
+ const note = parseGuestAttribution(input.channels);
+ if (!note) throw guestAttributionMissing('the call carries neither _meta.guest nor the ' + GUEST_HEADER + ' header');
+ return note;
+}
+
+/** 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]);
+ if (!guest) return;
+ if (isListedWriter(guest, await principalOf())) throw guestPageImmutable(`${operation} on a guest source`);
+ throw sourceWriterRestricted(sourceId);
+}
+
+export function guestFrontmatterRefused(why: string): OperationError {
+ return new OperationError('guest_frontmatter_refused', `A guest page's frontmatter ${why}. Nothing was written.`,
+ `Send only ${GUEST_FRONTMATTER_KEYS.join(', ')} in the frontmatter, with guest_sender and guest_group equal to the attribution's sender_label and group.`,
+ DOCS('guest_frontmatter_refused'));
+}
+
+export function guestReadersInvalid(why: string): OperationError {
+ return new OperationError('guest_readers_invalid', `A guest page's readable_by ${why}. Nothing was written.`,
+ 'Set readable_by to exactly the brain owner and the one member or group the call speaks for (X-Gbrain-On-Behalf-Of), for example [alice-example, group:team-a].',
+ DOCS('guest_readers_invalid'));
+}
+
+/** The frontmatter allowlist and the sender and group match, read from the raw frontmatter keys. */
+export function assertGuestFrontmatter(content: unknown, note: GuestAttribution): Record<string, unknown> {
+ if (typeof content !== 'string') throw guestFrontmatterRefused('is missing (send the page as content)');
+ const frontmatter = parseMarkdownHead(content).frontmatter;
+ const extra = Object.keys(frontmatter).filter(key => !GUEST_FRONTMATTER_KEYS.includes(key));
+ if (extra.length) throw guestFrontmatterRefused(`carries keys outside the allowlist (${extra.slice(0, 5).join(', ')})`);
+ if (frontmatter.guest_sender !== note.sender_label) throw guestFrontmatterRefused("has a guest_sender that is not the attribution's sender_label");
+ if (frontmatter.guest_group !== note.group) throw guestFrontmatterRefused("has a guest_group that is not the attribution's group");
+ return frontmatter;
+}
+
+/** Readers are exactly {owner, the single audience principal}; checked at submission and again at preparation. */
+export async function assertGuestReaders(engine: Pick<BrainEngine, 'getConfig'>, frontmatter: Record<string, unknown>, audience: readonly string[] | null | undefined): Promise<string> {
+ if (!audience || audience.length !== 1 || audience[0] === 'guest') throw guestReadersInvalid('needs a call that speaks for exactly one member or group');
+ const owner = await ownerMemberId(engine);
+ if (!owner) throw guestReadersInvalid('cannot be checked: this brain has no owner set (gbrain access owner set)');
+ const readers = normalizeReaders(frontmatter);
+ const want = new Set([`member:${owner}`, audience[0]!]);
+ if (!readers || readers.length !== want.size || !readers.every(r => want.has(r))) throw guestReadersInvalid('is not exactly the brain owner and the audience the call speaks for');
+ return audience[0]!;
+}
+
+/** Publication's recheck: the source is still a guest source and the request's principal is still a listed writer. */
+export async function assertGuestWriterAtPublication(tx: Pick<BrainEngine, 'executeRaw'>, row: { source_id: string; principal_kind: string; principal_id: string }): Promise<void> {
+ const [guest] = await tx.executeRaw<{ writers: string[] }>('SELECT writers FROM guest_sources WHERE source_id = $1 FOR SHARE', [row.source_id]);
+ if (!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. */
+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`,
+ [row.source_id, row.slug, audience, note.group, note.sender_label, row.principal_kind, row.principal_id, row.request_id]);
+}
diff --git a/src/core/guests/derived.ts b/src/core/guests/derived.ts
new file mode 100644
index 0000000000..265afd178c
--- /dev/null
+++ b/src/core/guests/derived.ts
@@ -0,0 +1,91 @@
+/**
+ * Guest notes (GBRA-504, decision I1): no derived row carries guest text. Every producer that derives rows from pages is
+ * listed here with what it does on a guest source: `skip` names the code sites that skip guest pages (each calls a
+ * helper below with its own key, so this table drives the behavior), and `none` says why the producer never takes
+ * guest input. test/guest-derived-registry.test.ts fails for a cycle phase missing here and for a skip site that does
+ * not call the helper with its key. A guest source is database-only and holds no facts, takes or timeline rows (the
+ * trust trigger refuses them), so producers of those rows fail closed even without a skip.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { CyclePhase } from '../cycle.ts';
+import { isGuestSource, 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 };
+
+const CYCLE = 'src/core/cycle.ts';
+const FILESYSTEM = 'Reads canonical files on disk; a guest source is database-only and has none.';
+const NO_ROWS = 'Reads takes, facts or typed links, which a guest source never holds (the trust trigger refuses them).';
+
+export const GUEST_DERIVED_PRODUCERS = {
+ lint: { guest: 'none', reason: FILESYSTEM },
+ backlinks: { guest: 'none', reason: FILESYSTEM },
+ sync: { guest: 'none', reason: FILESYSTEM },
+ unindexed_files: { guest: 'none', reason: FILESYSTEM },
+ fence_repair: { guest: 'none', reason: 'Its repairs publish as the local owner, which a guest source refuses (source_writer_restricted), so a guest page is never rewritten.' },
+ content_repair: { guest: 'none', reason: 'Its repairs publish as the local owner, which a guest source refuses (source_writer_restricted), so a guest page is never rewritten.' },
+ synthesize: { guest: 'none', reason: 'Dream synthesis reads session transcripts, not pages.' },
+ extract: { guest: 'skip', sites: [CYCLE, 'src/core/engine-sql/pages.ts', 'src/commands/extract.ts', 'src/commands/extract-timeline-db.ts'] },
+ extract_facts: { guest: 'skip', sites: [CYCLE, 'src/core/cycle/extract-facts.ts'] },
+ extract_atoms: { guest: 'skip', sites: [CYCLE, 'src/core/cycle/extract-atoms.ts'] },
+ resolve_symbol_edges: { guest: 'none', reason: "Writes code-edge metadata on a page's own chunks; no row outside the page." },
+ patterns: { guest: 'none', reason: 'A mixed phase: it runs only in the default lane and reads reflections in its own source.' },
+ synthesize_concepts: { guest: 'none', reason: 'Aggregates atom pages, which extract_atoms never derives from a guest page.' },
+ recompute_emotional_weight: { guest: 'none', reason: "Scores a page from its own takes and tags into that page's emotional_weight column; a guest page has no takes." },
+ consolidate: { guest: 'none', reason: NO_ROWS },
+ propose_takes: { guest: 'skip', sites: [CYCLE] },
+ grade_takes: { guest: 'none', reason: NO_ROWS },
+ calibration_profile: { guest: 'none', reason: NO_ROWS },
+ edge_contradictions: { guest: 'none', reason: NO_ROWS },
+ claim_conflicts: { guest: 'none', reason: NO_ROWS },
+ drift: { guest: 'none', reason: NO_ROWS },
+ standing_questions: { guest: 'none', reason: 'Answers through search like any reader; its evidence pointers name pages and copy no text.' },
+ chronicle: { guest: 'skip', sites: ['src/core/cycle/chronicle.ts'] },
+ facts_drain: { guest: 'none', reason: 'Runs queued facts-absorb jobs; facts_backstop never queues one for a guest page.' },
+ conversation_facts_backfill: { guest: 'skip', sites: [CYCLE, 'src/core/cycle/conversation-facts-backfill.ts'] },
+ enrich_thin: { guest: 'skip', sites: [CYCLE, 'src/core/cycle/enrich-thin.ts'] },
+ skillopt: { guest: 'none', reason: 'Writes skill files and proposals outside the brain database.' },
+ embed: { guest: 'none', reason: "Embeds a page's own chunks, which search needs to find the note; no text reaches another row." },
+ orphans: { guest: 'none', reason: 'A read-only report; it writes no row.' },
+ 'schema-suggest': { guest: 'none', reason: 'Writes schema suggestions outside the canonical tables; a guest page carries only allowlisted keys.' },
+ purge: { guest: 'none', reason: 'Purges tombstones; the owner may delete guest pages.' },
+ bookkeeping_gc: { guest: 'none', reason: 'Never touches a page.' },
+ publication_projections: { guest: 'skip', sites: ['src/core/persistence/page-prepare.ts'] },
+ auto_links: { guest: 'skip', sites: ['src/core/persistence/page-prepare.ts'] },
+ remote_links_effect: { guest: 'skip', sites: ['src/core/persistence/effect-links.ts'] },
+ facts_backstop: { guest: 'skip', sites: ['src/core/persistence/effect-facts.ts'] },
+ think_writeback: { guest: 'none', reason: 'A persisted synthesis takes the lowest tier of its inputs (deriveTrust over taint_refs), so one built on a guest note lands at external_untrusted.' },
+} as const satisfies Record<GuestDerivedProducer, GuestDerivedEntry>;
+
+type Producers = typeof GUEST_DERIVED_PRODUCERS;
+export type GuestSkipProducer = { [K in keyof Producers]: Producers[K]['guest'] extends 'skip' ? K : never }[keyof Producers];
+
+const skips = (producer: GuestSkipProducer) => GUEST_DERIVED_PRODUCERS[producer].guest === 'skip';
+
+/** The cycle phases a cycle scoped to a guest source skips. */
+export function guestSkippedPhases(): CyclePhase[] {
+ return (Object.keys(GUEST_DERIVED_PRODUCERS) as GuestDerivedProducer[])
+ .filter((key): key is CyclePhase & GuestSkipProducer => GUEST_DERIVED_PRODUCERS[key].guest === 'skip' && (GUEST_DERIVED_PRODUCERS[key] as { sites: readonly string[] }).sites.includes(CYCLE));
+}
+
+/** True when `producer` skips `sourceId` because it is a guest source. */
+export async function skipsGuestSource(engine: Pick<BrainEngine, 'executeRaw'>, producer: GuestSkipProducer, sourceId: string): Promise<boolean> {
+ return skips(producer) && isGuestSource(engine, sourceId);
+}
+
+/** True when `producer` skips a write whose stored intent carries a guest note (publication-time producers; no read). */
+export function skipsGuestNote(producer: GuestSkipProducer, intent: Record<string, unknown> | null | undefined): boolean {
+ return skips(producer) && storedGuestNote(intent) !== null;
+}
+
+/** `items` without those in a guest source, for a producer that walks several sources. */
+export async function withoutGuestSources<T>(engine: Pick<BrainEngine, 'executeRaw'>, producer: GuestSkipProducer, items: readonly T[], sourceOf: (item: T) => string): Promise<T[]> {
+ if (!skips(producer) || items.length === 0) return [...items];
+ const guests = new Set((await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM guest_sources')).map(row => row.source_id));
+ return guests.size ? items.filter(item => !guests.has(sourceOf(item))) : [...items];
+}
+
+/** A SQL predicate keeping rows of `alias` (a pages alias or table name) outside guest sources. */
+export function guestSourceExclusionSql(producer: GuestSkipProducer, alias: string): string {
+ return skips(producer) ? `NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = ${alias}.source_id)` : 'TRUE';
+}
diff --git a/src/core/guests/note.ts b/src/core/guests/note.ts
new file mode 100644
index 0000000000..e215fada45
--- /dev/null
+++ b/src/core/guests/note.ts
@@ -0,0 +1,20 @@
+/**
+ * Guest notes (GBRA-504): the stored form of a guest write's attribution and the guest-source check, kept free of
+ * runtime imports so the engine SQL layer and the persistence pipeline can read them without import cycles.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export interface GuestAttribution { sender_label: string; group: string }
+/** The intent key publication reads; a caller can never set it (preparePageAdmission strips it). */
+export const GUEST_NOTE_INTENT_KEY = 'guest_note';
+
+/** The guest note a stored write intent carries, or null (publication and preparation read only this). */
+export function storedGuestNote(intent: Record<string, unknown> | null | undefined): GuestAttribution | null {
+ const note = intent?.[GUEST_NOTE_INTENT_KEY] as Record<string, unknown> | null | undefined;
+ return note && typeof note === 'object' && typeof note.sender_label === 'string' && typeof note.group === 'string'
+ ? { sender_label: note.sender_label, group: note.group } : null;
+}
+
+export async function isGuestSource(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<boolean> {
+ return (await engine.executeRaw('SELECT 1 FROM guest_sources WHERE source_id = $1', [sourceId])).length > 0;
+}
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index a147673405..e74f666e0a 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -20,6 +20,7 @@ import type { RegistryCode } from '../error-registry.ts';
import type { WriteAuthority } from '../persistence/model.ts';
import type { TrustTier } from '../trust/tier.ts';
import type { StdioSurfaceState } from '../../mcp/surface.ts';
+import type { GuestChannels } from '../guests/admission.ts';
/** Agent contract v1: the wire renderer for `fix`/`notices` in toJSON(), registered by agent-output.ts on load. */
interface OperationErrorWireRenderer { fix(a: Action): unknown; notice(n: Notice): unknown }
@@ -572,6 +573,12 @@ export interface OperationContext {
* config mcp.stdio_member, and a named member that is not enabled reads as nobody.
*/
stdioMember?: string;
+ /**
+ * GBRA-504: the guest attribution channels a remote call carried (the X-Gbrain-Guest header, request-level
+ * _meta.guest), set by dispatch from the transport; never from tool arguments. Read only for a write to a guest
+ * source (guests/admission.ts), and stored nowhere for any other write.
+ */
+ guestChannels?: GuestChannels;
/**
* Set by transports that can widen a session's listed tools (stdio): when
* `request_tools` returns schemas, the named tools join this session's
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 5e1cbf72e9..c6bcb784ed 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -1,5 +1,6 @@
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
-import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { requestPrincipalForContext, submitPageMutation } from '../persistence/page-mutations.ts';
+import { refuseGuestSourceWrite } from '../guests/admission.ts';
import { remoteTargetHidden } from '../persistence/page-visibility.ts';
import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
import { MANAGED_LINK_SOURCES } from '../links-fence.ts';
@@ -146,6 +147,7 @@ const add_link: Operation = {
const linkOpts = ctx.sourceId
? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId, originSourceId: ctx.sourceId }
: undefined;
+ await refuseGuestSourceWrite(ctx.engine, ctx.sourceId || 'default', () => requestPrincipalForContext(ctx), 'add_link');
// #4109: per-endpoint source-boundary diagnostics before the mutation.
await requireWritablePage(ctx, p.from as string, 'add_link', 'from');
await requireWritablePage(ctx, p.to as string, 'add_link', 'to');
@@ -202,6 +204,7 @@ const remove_link: Operation = {
enforceClientSlugFence(ctx, p.from as string, 'remove_link');
if (ctx.dryRun) return { dry_run: true, action: 'remove_link', from: p.from, to: p.to };
const writeSource = ctx.sourceId || 'default';
+ await refuseGuestSourceWrite(ctx.engine, writeSource, () => requestPrincipalForContext(ctx), 'remove_link');
if (await remoteTargetHidden(ctx.engine, ctx.remote, writeSource, p.from as string)
|| await remoteTargetHidden(ctx.engine, ctx.remote, writeSource, p.to as string)) return { status: 'ok', removed: 0 };
await primeRelationSemantics(ctx.engine);
diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.ts
index 4c266b8efb..7c79c13e1f 100644
--- a/src/core/persistence/effect-facts.ts
+++ b/src/core/persistence/effect-facts.ts
@@ -14,6 +14,7 @@ import { authorizeStoredRequest, authorizeWrite } from './authority.ts';
import { completeEffect } from './effect-journal.ts';
import { guardEffectSource } from './effect-recovery.ts';
import { derivedExtractionSkip } from './derived-extraction-gate.ts';
+import { skipsGuestNote } from '../guests/derived.ts';
import { bodyUnread, isSegmentedPage } from '../page-body/page-shape.ts';
import type { PersistenceEffect } from './effect-model.ts';
import type { WriteRequest } from './model.ts';
@@ -94,6 +95,7 @@ async function bodyAlreadyOffered(engine: BrainEngine, slug: string, page: Parse
export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequest, page: ParsedPage, before: PageSnapshot | null = null): Promise<FactsBackstopStatus> {
const confined = derivedExtractionSkip(row.authority);
if (confined) return { skipped: confined };
+ if (skipsGuestNote('facts_backstop', row.intent)) return { skipped: 'guest_source' };
if (!(await isFactsExtractionEnabled(engine))) return { skipped: 'extraction_disabled' };
const eligible = isFactsBackstopEligible(row.slug, page);
if (!eligible.ok) return { skipped: eligible.reason };
diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.ts
index 3574d1be7f..8eb40cf477 100644
--- a/src/core/persistence/effect-links.ts
+++ b/src/core/persistence/effect-links.ts
@@ -20,6 +20,7 @@ import { extractSegmentedPageLinks } from '../page-body/segment-links.ts';
import { inlineRegions } from '../page-body/tail-digest.ts';
import { validateSlug } from '../utils.ts';
import { isRemoteWantedPagesEnabled, replaceWantedLinks } from '../wanted-links.ts';
+import { skipsGuestNote } from '../guests/derived.ts';
/** `mcp.remote_auto_links`: unset is on; false/0/no/off (any case) turns the remote `links` effect off. */
export async function isRemoteAutoLinksEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
@@ -108,6 +109,7 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEff
const skip = (tx: SqlEngine, reason: string) => completeEffect(tx, effect, { links: 'skipped', reason });
const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [effect.request_id]);
if (!row || row.state !== 'committed' || !effect.data.slug) return skip(engine, 'invalid_write_request');
+ if (skipsGuestNote('remote_links_effect', row.intent)) return skip(engine, 'guest_source');
if (effect.data.range) return runAppendLinksEffect(engine, effect, row, effect.data.range, hostId);
const sourceId = effect.source_id;
const snapshot = await engine.readPageSnapshot(effect.data.slug, { sourceId });
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index db43aa2904..87fc7c20a1 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -36,6 +36,7 @@ import { entityPageMissingNotice } from '../interop-notices.ts';
import { ownerSpeaksForItself } from '../access/member-facts.ts';
import { isDerivationPrivate } from '../search/private-visibility.ts';
+import { refuseGuestSourceWrite } from '../guests/admission.ts';
export { prepareMemoryMutation } from './memory-prepare.ts';
/** Only semantic appends without an explicit caller revision can be recomputed. */
@@ -234,6 +235,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
const [source] = await ctx.engine.executeRaw<RememberSource>(
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);
if (!source || source.archived) throw sourceInactive(sourceId);
+ await refuseGuestSourceWrite(ctx.engine, sourceId, () => Promise.resolve(principal), 'remember');
const { parseTtlParam } = await import('../ops/facts.ts');
const validUntil = parseTtlParam(p.ttl);
const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 547b8ceb61..fc3b9240b0 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -52,6 +52,9 @@ import { holdsSummarizedToolCalls, isQuotedPageType, quotesTier, unquoteTranscri
import { readStoredBody } from '../facts/file-body-guard.ts';
import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { perCallWriteSource } from '../access/attest-sources.ts';
+import { readGuestSource, type GuestSource } from '../guests/sources.ts';
+import { admitGuestOperation, assertGuestFrontmatter, assertGuestReaders, GUEST_NOTE_INTENT_KEY, guestPageImmutable } from '../guests/admission.ts';
+import { currentCallerAccess } from '../search/private-visibility.ts';
export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {
// #5994: a failed-writes replay is admitted under the original writer.
@@ -79,6 +82,7 @@ const BATCH_SHARED_READS = new Set([
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1",
'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',
'SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid',
+ 'SELECT source_id, writers, trust_ceiling FROM guest_sources WHERE source_id = $1',
'SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',
'SELECT brain_id FROM persistence_brain WHERE singleton=1',
'SELECT value FROM config WHERE key=$1',
@@ -395,7 +399,7 @@ export async function preparePageAdmission(ctx: OperationContext,
throw new OperationError('request_too_large', contentSizeHold(bodyBytes, PAGE_MAX_BYTES)!.message,
`Nothing was admitted or written, and the same content is refused on every retry. Pages up to ${PAGE_MAX_BYTES} bytes are stored and searchable; send a smaller page.`);
}
- const { page_batch: _forged, timeline_section: _section, ...params } = input.params;
+ const { page_batch: _forged, timeline_section: _section, [GUEST_NOTE_INTENT_KEY]: _guestNote, ...params } = input.params;
const p: Record<string, unknown> = { ...params, ...parseMutationPrecondition(params) };
if (p.content_origin !== undefined) contentOriginTier(p.content_origin);
if (input.batch) p.page_batch = { id: input.batch.id, index: input.batch.index, size: input.batch.size, ...(input.batch.repeats?.length ? { repeats: input.batch.repeats } : {}) };
@@ -405,10 +409,16 @@ export async function preparePageAdmission(ctx: OperationContext,
const captureSlug = input.operation === 'capture' ? await resolveCaptureFile(ctx, sourceId, p) : null;
const principal = await requestPrincipalForContext(ctx);
// Independent reads go out together on Postgres; the first refusal in this order is the one reported.
- const [, prior] = await pipelined(ctx.engine, [
+ const [, prior, guest] = await pipelined(ctx.engine, [
() => assertPageRequestIdentity(ctx.engine, principal, requestId),
() => getWriteRequest(ctx.engine, principal, requestId),
- ]) as [unknown, WriteRequest | null];
+ () => readGuestSource(ctx.engine, sourceId),
+ ]) as [unknown, WriteRequest | null, GuestSource | 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.
+ const guestNote = guest ? admitGuestOperation(guest, { principal, operation: input.operation, remote: ctx.remote !== false,
+ plainPut: !input.batch && !staged && !imported && input.managedFileImport !== true, params: p, channels: ctx.guestChannels }) : null;
+ if (guestNote) p[GUEST_NOTE_INTENT_KEY] = guestNote;
// GBRA-217: a reason is refused before anything is journaled; its canonical form joins the replay identity. An
// operation that records no reason never journals one a caller passed anyway.
if (CHANGE_REASON_OPERATIONS.includes(input.operation) && Object.hasOwn(p, 'reason')) {
@@ -496,6 +506,10 @@ export async function preparePageAdmission(ctx: OperationContext,
await assertTimelineNotOmitted(ctx.engine, { intent, remote: ctx.remote !== false, writer: typeof p.expected_revision === 'string' ? 'editing' : 'preserving',
slug, sourceId, content: intent.content, prior: snapshot });
}
+ if (guestNote) {
+ if (snapshot?.page.deleted_at) throw guestPageImmutable(`put_page over the deleted guest page ${slug}`);
+ await assertGuestReaders(ctx.engine, assertGuestFrontmatter(p.content, guestNote), currentCallerAccess().audience);
+ }
const slugAdvisory = (input.operation === 'put_page' || input.operation === 'capture') && input.managedFileImport !== true
? suffixedSlugAdmission(ctx, slug, !!snapshot && !snapshot.page.deleted_at, input.operation) : null;
// #5616: typed edit refusals before admission; publication repeats them on the locked snapshot.
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 7cb7d38d11..df51ca5ee6 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -107,6 +107,9 @@ import { gateField, gateInput } from '../trust/gate-outcomes.ts';
import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';
import { fileContentHash, FileBytes, isStreamedContent, LARGE_FILE_MIN_BYTES, StreamedFileContent } from './large-file.ts';
import { bindOrigin } from './origin-guard.ts';
+import { assertGuestReaders, assertGuestWriterAtPublication, insertGuestMark } from '../guests/admission.ts';
+import { isGuestSource, storedGuestNote } from '../guests/note.ts';
+import { skipsGuestNote } from '../guests/derived.ts';
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,
@@ -875,6 +878,26 @@ async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snap
afterCommit: async target => { if (!complete) await buildSegmentedProjection(target, { sourceId: row.source_id, slug: row.slug }).catch(() => undefined); } };
return prepared;
}
+/**
+ * GBRA-504: `restore_page` of a guest page (only the local owner may submit one). Soft delete only set `deleted_at`, so
+ * the restore clears it without re-importing the body: a re-import would rewrite the page's content columns, which the
+ * guest-source guard refuses from anyone but a listed writer, and would project rows a guest page never has. A guest
+ * source is database-only, so there is no file to write.
+ */
+async function prepareGuestRestore(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot): Promise<PreparedMutation> {
+ const source = { sourceId: row.source_id };
+ const noop = snapshot.page.deleted_at == null;
+ return { observedRevision: snapshot.revision, noop, ...await pageDatabaseOnlyPublication(engine, row, undefined),
+ validate: async () => {},
+ apply: async tx => {
+ if (noop) return { ...pageNoopAdvisories(row), status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, chunks: 0, chunk_skip_reason: 'write_skipped' };
+ await tx.createVersion(row.slug, source);
+ await tx.restorePage(row.slug, source);
+ await sealPageTextProjection(tx, row.slug, row.source_id);
+ return { ...pageNoopAdvisories(row), status: 'restored', slug: row.slug, source_id: row.source_id, chunks: 0, noop: false };
+ } };
+}
+
/**
* serializePageToMarkdown's bytes for a page whose body was not read back, streamed from its segments by export's
* serializer: measured here, produced again into the publication's staging file (large-file.ts), never concatenated.
@@ -1059,6 +1082,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
`Page ${row.slug} does not exist in source ${row.source_id} (it was purged or never written), so nothing was ${row.operation === 'restore_page' ? 'restored' : 'reverted'}. Check the slug and the source.`,
pageFix(row.source_id, row.slug));
if (row.operation === 'restore_page' && bodyUnread(snapshot.page)) return prepareUnreadRestore(engine, row, snapshot, { activePack, clock, allowMissingFile: options.allowMissingFile });
+ if (row.operation === 'restore_page' && await isGuestSource(engine, row.source_id)) return prepareGuestRestore(engine, row, snapshot);
let page = snapshot.page;
let tags = snapshot.tags;
if (row.operation === 'revert_version') {
@@ -1085,7 +1109,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);
}
content = remoteCoreMarkingKept(row, snapshot, content, activePack);
- const projected = !(options.unprojected || row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));
+ const guestNote = storedGuestNote(p);
+ const projected = !skipsGuestNote('publication_projections', p) && !(options.unprojected || row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));
const writer = replacesTombstone || ((row.operation === 'put_page' || row.operation === 'edit_page') && p.kind !== 'managed_maintenance_page'
&& (preparedIntent !== undefined || typeof p.expected_revision === 'string')) ? 'editing' : 'preserving';
// #5969 (D3): only an ordinary put_page intent carries a timeline section; every other writer keeps the shared policy.
@@ -1121,6 +1146,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// #5575: the page's tier, computed once before import so the write gate sees exactly it (ENG-18).
const incoming = typeof content === 'string' && !isFenceEditWrite(row) ? parseMarkdown(content, row.slug, { activePack }).frontmatter : null;
const trust = provenanceWriteTrust(row, incoming, snapshot?.page.frontmatter);
+ const guestAudience = guestNote ? await assertGuestReaders(engine, incoming ?? {}, Array.isArray(row.authority.actingFor) ? row.authority.actingFor : null) : null;
const gateTrust = pageGateTrust(row, trust, storedTier);
// GST-2518: a lower-tier local write keeps the page's privacy labels it would widen (GST-2521: and the owner as a reader); its proposal carries the request.
const labelGuard = await privacyLabelGuard(engine, row, trust, snapshot?.page ?? null, storedTier, incoming);
@@ -1203,7 +1229,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
const [project, advisories, links, target, core] = await pipelined(together, [
async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy) : undefined,
async () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),
- async () => !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
+ async () => !skipsGuestNote('auto_links', p) && !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
? prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id,options.coordinated === true) : undefined,
() => prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote, newPageIgnoredDatabaseOnly: true, clock, labelEdit: row.operation === 'submit_job' && p.kind === 'managed_maintenance_page' ? readLabelEdit(p.label_edit) : undefined }),
// Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).
@@ -1303,6 +1329,15 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// DX-1: a guarded supersession reports contested (the first proposal; every one when the write contested several rows).
...(contested.length ? { contested: { proposal_ref: contested[0], ...(contested.length > 1 ? { proposal_refs: contested } : {}) } } : {}) };
} };
+ if (guestNote && guestAudience) {
+ const { validate, apply } = publication;
+ publication.validate = async tx => { await validate?.(tx); await assertGuestWriterAtPublication(tx, row); };
+ publication.apply = async (tx, preimage) => {
+ const out = await apply(tx, preimage);
+ if (!noop) await insertGuestMark(tx, row, guestNote, guestAudience);
+ return out;
+ };
+ }
return publication;
}
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index fcd7789488..75bfa82921 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -119,6 +119,13 @@ const GIT_PROTOCOL_PREFIX = 'git_protocol_required:';
/** trust/schema.ts: the tier trigger's refusal of a raise without owner confirmation. */
const TRUST_PREFIX = 'trust_raise_refused:';
const PURGED_PREFIX = 'purged_content:';
+/** GBRA-504 (trust/schema.ts GUEST_GUARD, guests/schema.ts): the guest-source guards' codes, each the message prefix of its raise. */
+const GUEST_GUARD_TEXT: Record<string, string> = {
+ source_writer_restricted: 'only the listed writers of a guest source may create or change its pages',
+ guest_page_immutable: 'a guest source holds no facts, takes or timeline entries, and its pages are never changed',
+ guest_mark_immutable: 'a guest mark is never changed',
+ guest_source_database_only: 'a guest source is database-only and takes no local path or repository',
+};
const RELATIONSHIP_TEXT: Record<string, string> = {
different_source: 'a row in a source this publication does not own',
missing_source: 'a row whose source could not be resolved',
@@ -249,6 +256,9 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {
...guardDetail(e.detail) },
message: `The trust-tier guard refused a write${table ? ` on ${table}` : ''}: raising a tier needs the owner's confirmation. Nothing was committed.` };
}
+ const guestCode = constraint === 'guest_source_guard' ? Object.keys(GUEST_GUARD_TEXT).find(code => message.startsWith(`${code}:`)) : undefined;
+ if (guestCode) return { code: guestCode, message: `The guest-source guard refused a write${table ? ` on ${table}` : ''}: ${GUEST_GUARD_TEXT[guestCode]}. Nothing was committed.`,
+ detail: { origin: 'database_trigger', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };
const reason = publicationReason(sqlstate, raiser, message);
return { code: 'storage_error', message: `Publication failed (P0001${raiser ? ` in ${raiser}` : ''}: ${reason}). Inspect owner diagnostics.`,
detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}), reason } };
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 7745d80051..9ec8633ba6 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -307,6 +307,13 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {
Object.assign(strict, { canonical: error.code, reason: error.reason, why: error.why, docs: error.docs, fix: error.fix });
throw strict;
}
+ // GBRA-504: a guest-source refusal keeps its frozen code (scope_denied for a non-writer, invalid_params for a writer's
+ // change); the canonical code and docs ride along.
+ if (error.code === 'source_writer_restricted' || error.code === 'guest_page_immutable') {
+ const guest = verbError(error.code === 'source_writer_restricted' ? 'scope_denied' : 'invalid_params', error.message, error.suggestion ?? 'Do not retry.');
+ Object.assign(guest, { canonical: error.code, docs: error.docs });
+ throw guest;
+ }
const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)
? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)
? 'invalid_params' : 'unavailable';
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index be270429a4..9444ceb731 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -67,7 +67,7 @@ export function pageWriteTrust(row: Pick<WriteRequest, 'id' | 'operation' | 'aut
// A managed derived page (atoms, synthesis, concepts, chronicle) carries its derivation declaration (trust/taint.ts).
const channel = derivationWriteTrust(row.intent) ?? requestChannelTrust(row);
if (!channel || isFenceEditWrite(row)) return channel;
- const caps = frontmatterTrustCaps(frontmatter);
+ const caps: TrustTier[] = [...frontmatterTrustCaps(frontmatter), ...(row.intent?.guest_note !== undefined ? ['external_untrusted' as const] : [])];
return caps.length ? effectiveWriteTrust({ channel: channel.tier, lowerTo: caps, origin: channel.origin ?? { channel: row.operation } }) : channel;
}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index f9bd3014d5..2f7cc4d375 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -18,6 +18,7 @@ import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core
import { currentCallerAccess, withCallerAccess } from '../core/search/private-visibility.ts';
import { appliedAccessSummary, folderAccessFor, identityLookupUnavailable, remoteCallerAccess } from '../core/access/caller.ts';
import { credentialScopeFor, requesterScopeGate, requesterScopeRefuses, requiresRequesterScope, withServesReread, type RequesterScopeNotice } from '../core/access/requester-scope.ts';
+import type { GuestChannels } from '../core/guests/admission.ts';
import { assessRoom, readRoomDeclaration, roomResponseCapNotice, type RoomChannels, type RoomDeclaration } from '../core/access/room.ts';
import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';
import { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';
@@ -194,6 +195,8 @@ export interface DispatchOpts {
* code. A `room` tool argument is read too, and can only add people (access/room.ts).
*/
room?: RoomChannels;
+ /** GBRA-504: the guest attribution channels the transport read (the X-Gbrain-Guest header, request-level _meta.guest). */
+ guest?: GuestChannels;
/** GBRA-498 (internal): the room this call declared, resolved by dispatchToolCall; never set by a transport. */
roomDeclaration?: RoomDeclaration;
/** GBRA-498 (internal): the call named an attested actor, so its answer is never marked for a room. */
@@ -980,6 +983,7 @@ export function buildOperationContext(
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
...(opts.stdioSurface ? { stdioSurface: opts.stdioSurface } : {}),
...(opts.stdioMember !== undefined && opts.transport === 'stdio' && !opts.auth ? { stdioMember: opts.stdioMember } : {}),
+ ...(opts.guest && opts.remote !== false ? { guestChannels: opts.guest } : {}),
...(opts.revealTools ? { revealTools: opts.revealTools } : {}),
...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),
...(opts.admissionOrigin ? { admissionOrigin: opts.admissionOrigin } : {}),
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 9ca29ef2c0..b4ead52f17 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -41,6 +41,7 @@ import { operations, operationsByName, opAllowedForBoundClient } from '../core/o
import { scopeDeniedError } from '../core/ops/op-fix.ts';
import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';
import { ROOM_HEADER } from '../core/access/room.ts';
+import { GUEST_HEADER } from '../core/guests/admission.ts';
import { ACTOR_HEADER, QM_AUDIENCE_HEADER, withAttestRight } from '../core/access/actor-model.ts';
import { parseAgentLabel, AGENT_LABEL_HEADER } from '../core/persistence/attribution.ts';
import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';
@@ -571,7 +572,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
transport: 'http', inboundFrameBytes: bodyCap,
takesHoldersAllowList: auth.takesHoldersAllowList,
sourceId: auth.sourceId, agentLabel: parseAgentLabel(req.headers.get(AGENT_LABEL_HEADER)),
- ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta }, room: { header: req.headers.get(ROOM_HEADER) ?? undefined, requestMeta: params?._meta }, mcpCaller: { client: auth.auth?.clientName, userAgent: req.headers.get('user-agent') ?? undefined, meta: params?._meta },
+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta }, room: { header: req.headers.get(ROOM_HEADER) ?? undefined, requestMeta: params?._meta }, guest: { header: req.headers.get(GUEST_HEADER) ?? undefined, requestMeta: params?._meta }, mcpCaller: { client: auth.auth?.clientName, userAgent: req.headers.get('user-agent') ?? undefined, meta: params?._meta },
actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined, audience: req.headers.get(QM_AUDIENCE_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope
// to the operator-granted sources via sourceScopeOpts.
auth: auth.auth,
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index b2a9dd8efe..f6f1fa4aad 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -511,7 +511,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// stdio stays remote/untrusted.
transport: 'stdio', inboundFrameBytes: MCP_STDIO_MAX_MESSAGE_BYTES,
takesHoldersAllowList: ['world'],
- ...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}), onBehalfOf: { requestMeta: request.params?._meta }, room: { requestMeta: request.params?._meta },
+ ...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}), onBehalfOf: { requestMeta: request.params?._meta }, room: { requestMeta: request.params?._meta }, guest: { requestMeta: request.params?._meta },
mcpCaller: { client: server?.getClientVersion()?.name, meta: request.params?._meta },
sourceId: sourceScope.sourceId,
...(sourceScope.localFederatedSourceIds
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index c831c01283..406c72ff14 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6843,6 +6843,7 @@
"emitToolTail?: ((tail: { text?: string; meta?: Record<string, unknown>; }) => void) | undefined",
"engine: BrainEngine",
"explicitReadBinding?: ExplicitReadBinding | undefined",
+ "guestChannels?: GuestChannels | undefined",
"inboundFrameBytes?: number | undefined",
"isCallable?: ((opName: string) => boolean) | undefined",
"jobId?: number | undefined",
@@ -6871,7 +6872,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index ecb24f71cf..a66e7ca441 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -61,8 +61,8 @@
"string",
"string"
],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2 AND links_attendance_blocked_revision = knowledge_revision",
- "textSha256": "002fabcfde69b77bcdf854b15c11e46e4c797cde1be1973e34ab73df3d327bd7"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2 AND links_attendance_blocked_revision = knowledge_revision AND NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = pages.source_id)",
+ "textSha256": "8892f5fbcb64737dd5dd3d5b24f2c86d935e15f574b5e6d5875d7823d063f764"
}
],
"attendance-exclude": [
@@ -71,16 +71,16 @@
"params": [
"string"
],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND links_attendance_blocked_revision IS DISTINCT FROM knowledge_revision",
- "textSha256": "e568ead5dc5191a909c2e58fea58356a5acde8fcda59cd40b091727b964fb6a3"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND links_attendance_blocked_revision IS DISTINCT FROM knowledge_revision AND NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = pages.source_id)",
+ "textSha256": "d78d41c22ff31f42821a8224184caa7e08d54dd1cf325822db794b79caf242b9"
}
],
"default": [
{
"lane": "pool",
"params": [],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at))",
- "textSha256": "2288e7b188811bbaa877f1d9a13e4148bbee4ed200d7ba438a12737c69ef72e5"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = pages.source_id)",
+ "textSha256": "e108c9f4ec8e75ab4ae25b9d1c7aa0022175ec64599a4ad0e4b3cacc8aa55dbe"
}
],
"versionTs+sourceId": [
@@ -90,8 +90,8 @@
"string",
"string"
],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2",
- "textSha256": "57ff70c7578ba9ff9e97f7d18593cb82a92ede5115e7cbf45e9b6d29a8aa2a3b"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2 AND NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = pages.source_id)",
+ "textSha256": "c247759eaffef0a8f5b5840a1f04a7443302a8522e78a5f811d37905625f90f1"
}
]
},
@@ -756,8 +756,8 @@
"number",
"number"
],
- "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2 AND id > $3 ORDER BY id LIMIT $4",
- "textSha256": "22fb498ad7872c970f05a3905d04bebef7df2790c417bea32d6a214eb0ae4505"
+ "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2 AND NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = pages.source_id) AND id > $3 ORDER BY id LIMIT $4",
+ "textSha256": "c5392d1114a1041dba9a874c501cc31182fab4a30fd133527c80ab597a5827c4"
}
],
"default": [
@@ -766,8 +766,8 @@
"params": [
"number"
],
- "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) ORDER BY id LIMIT $1",
- "textSha256": "27cc368fcbecffffad33b5d8542adbc3d0fcd24e6700ce7b5d351ec5e2103a57"
+ "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND NOT EXISTS (SELECT 1 FROM guest_sources guest_src WHERE guest_src.source_id = pages.source_id) ORDER BY id LIMIT $1",
+ "textSha256": "eb5a092049ba72338135fdbe81657e57c91db6c031266feeac756ea2023cfa00"
}
]
},
diff --git a/test/guest-derived-registry.test.ts b/test/guest-derived-registry.test.ts
new file mode 100644
index 0000000000..942a5583a5
--- /dev/null
+++ b/test/guest-derived-registry.test.ts
@@ -0,0 +1,100 @@
+/**
+ * Guest notes (GBRA-504, decision I1): guest pages feed no derived rows, and a registry says so for every producer.
+ *
+ * Protects: every cycle phase (and every extra producer) is classified in GUEST_DERIVED_PRODUCERS; each producer marked
+ * skip has code at each named site that calls a guest helper with its own key (so the table drives the behavior), and a
+ * cycle scoped to a guest source skips exactly the phases the table says. On a repo-less PGLite brain with a guest page
+ * that links and dates things, stale link extraction, the timeline walk and fact extraction derive nothing from it and
+ * report nothing for it, while an owner page beside it still gets its link.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { ALL_PHASES, runCycle } from '../src/core/cycle.ts';
+import { MANAGED_PHASE_TABLE } from '../src/core/cycle/phase-table.ts';
+import { GUEST_DERIVED_PRODUCERS, guestSkippedPhases } from '../src/core/guests/derived.ts';
+import { initGuestSource } from '../src/core/guests/sources.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { withWriteAttribution } from '../src/core/persistence/context.ts';
+
+const ROOT = join(import.meta.dir, '..');
+const HELPERS = ['skipsGuestSource', 'skipsGuestNote', 'withoutGuestSources', 'guestSourceExclusionSql'];
+
+describe('guest derived-producer registry', () => {
+ test('every cycle phase is classified, and every none entry says why', () => {
+ for (const phase of ALL_PHASES) expect({ phase, listed: Object.hasOwn(GUEST_DERIVED_PRODUCERS, phase) }).toEqual({ phase, listed: true });
+ for (const phase of Object.keys(MANAGED_PHASE_TABLE)) expect({ phase, listed: Object.hasOwn(GUEST_DERIVED_PRODUCERS, phase) }).toEqual({ phase, listed: true });
+ for (const [key, entry] of Object.entries(GUEST_DERIVED_PRODUCERS)) {
+ if (entry.guest === 'none') expect({ key, reason: entry.reason.length > 20 }).toEqual({ key, reason: true });
+ else expect({ key, sites: entry.sites.length > 0 }).toEqual({ key, sites: true });
+ }
+ });
+
+ test('each skip site calls a guest helper with its own key; the cycle gate covers the cycle.ts sites', () => {
+ const cycle = readFileSync(join(ROOT, 'src/core/cycle.ts'), 'utf8');
+ expect(cycle).toContain('guestSkippedPhases()');
+ const viaCycle: string[] = [];
+ for (const [key, entry] of Object.entries(GUEST_DERIVED_PRODUCERS)) {
+ if (entry.guest !== 'skip') continue;
+ for (const site of entry.sites) {
+ if (site === 'src/core/cycle.ts') { viaCycle.push(key); continue; }
+ const text = readFileSync(join(ROOT, site), 'utf8');
+ const called = HELPERS.some(helper => new RegExp(`${helper}\\([^;]*?'${key}'`, 's').test(text));
+ expect({ key, site, called }).toEqual({ key, site, called: true });
+ }
+ }
+ expect([...guestSkippedPhases()].sort()).toEqual(viaCycle.sort() as typeof ALL_PHASES);
+ });
+});
+
+describe('guest pages feed no derived rows (pglite, repo-less)', () => {
+ let engine: PGLiteEngine;
+ const writer = { kind: 'oauth_client' as const, id: 'client-a' };
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await initGuestSource(engine, 'guests', [`${writer.kind}:${writer.id}`]);
+ const asWriter = <T>(fn: (tx: PGLiteEngine) => Promise<T>) => engine.transaction(tx => withWriteAttribution(tx, { requestId: null, principal: writer,
+ trust: { tier: 'external_untrusted', origin: { channel: 'test' } } }, () => fn(tx as PGLiteEngine)));
+ await asWriter(tx => importFromContent(tx, 'people/carol-example', '---\ntype: note\ntitle: Carol\n---\n# Carol\n\nA guest page.', { sourceId: 'guests', noEmbed: true } as never));
+ await asWriter(tx => importFromContent(tx, 'notes/guest-a', '---\ntype: note\ntitle: Guest\n---\n# Guest\n\nMet [[people/carol-example]] about the ledger.\n\n## Facts\n\n| fact | entity |\n|---|---|\n| Carol likes tea | people/carol-example |\n',
+ { sourceId: 'guests', noEmbed: true } as never));
+ await asWriter(tx => tx.executeRaw("UPDATE pages SET timeline = '- **2026-11-01** | Met Carol' WHERE source_id='guests' AND slug='notes/guest-a'"));
+ await importFromContent(engine, 'people/dan-example', '---\ntype: person\ntitle: Dan\n---\n# Dan\n', { noEmbed: true } as never);
+ await importFromContent(engine, 'notes/owner-a', '---\ntype: note\ntitle: Owner\n---\n# Owner\n\nMet [[people/dan-example]].\n', { noEmbed: true } as never);
+ }, 180_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ const guestRows = async () => (await engine.executeRaw<{ links: number; timeline: number; facts: number }>(
+ `SELECT (SELECT count(*)::int FROM links l JOIN pages p ON p.id = l.from_page_id WHERE p.source_id = 'guests') AS links,
+ (SELECT count(*)::int FROM timeline_entries t JOIN pages p ON p.id = t.page_id WHERE p.source_id = 'guests') AS timeline,
+ (SELECT count(*)::int FROM facts f WHERE f.source_id = 'guests') AS facts`))[0]!;
+
+ test('stale extraction never lists a guest page and links only the owner page', async () => {
+ expect(await engine.countStalePagesForExtraction({ sourceId: 'guests' })).toBe(0);
+ await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: false });
+ expect(await guestRows()).toEqual({ links: 0, timeline: 0, facts: 0 });
+ const [owner] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM links l JOIN pages p ON p.id = l.from_page_id WHERE p.slug = 'notes/owner-a'");
+ expect(owner!.n).toBeGreaterThan(0);
+ }, 120_000);
+
+ test('the timeline walk and fact extraction skip the guest source', async () => {
+ const timeline = await extractTimelineFromDB(engine, { dryRun: false, jsonMode: true, quiet: true });
+ expect(timeline.refused).toBe(0);
+ const facts = await runExtractFacts(engine, { sourceId: 'guests' });
+ expect({ scanned: facts.pagesScanned, failed: facts.pagesFailed }).toEqual({ scanned: 0, failed: 0 });
+ expect(await guestRows()).toEqual({ links: 0, timeline: 0, facts: 0 });
+ }, 120_000);
+
+ test('a cycle scoped to the guest source reports the derived phases skipped', async () => {
+ const report = await runCycle(engine, { sourceId: 'guests', phases: ['extract_facts', 'propose_takes', 'orphans'], brainDir: null } as never);
+ const byPhase = Object.fromEntries(report.phases.map(p => [p.phase, (p.details as { reason?: string } | undefined)?.reason]));
+ expect({ extract_facts: byPhase.extract_facts, propose_takes: byPhase.propose_takes }).toEqual({ extract_facts: 'guest_source', propose_takes: 'guest_source' });
+ expect(byPhase.orphans).not.toBe('guest_source');
+ }, 120_000);
+});
diff --git a/test/guest-notes-admission.test.ts b/test/guest-notes-admission.test.ts
new file mode 100644
index 0000000000..c2bb5157db
--- /dev/null
+++ b/test/guest-notes-admission.test.ts
@@ -0,0 +1,317 @@
+/**
+ * Guest notes, slice 2 (GBRA-504): who may write a guest source, and what a guest write may say.
+ *
+ * Protects: a guest source takes page writes only from a credential on its writer list, through put_page, as a new
+ * page (create-only), with the guest attribution channel (X-Gbrain-Guest header or request-level _meta.guest), a
+ * frontmatter allowlist and readers of exactly the brain owner plus the call's one audience principal; the write is
+ * capped at external_untrusted, gets a guest_marks row in the publication transaction, and produces no derived rows
+ * (facts, takes, timeline, links). A writer-list change after admission refuses at publication. Local CLI writes,
+ * an enforced member, remember, links and import refuse on a guest source, while local delete and restore still work.
+ * Pages outside a guest source keep their behavior, and attribution sent to them is stored nowhere.
+ *
+ * Real seams: legacy tokens bound by the member CLI functions, dispatched through MCP dispatch on a repo-less PGLite
+ * brain; the race case drives admission and publication through the persistence service directly.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { buildOperationContext, dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { addGroup, addMember, bindCredential } from '../src/core/access/members.ts';
+import { clearOwner, setOwner } from '../src/core/access/owner.ts';
+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 { 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';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runImport } from '../src/commands/import.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
+
+const SRC = 'guests';
+const PLAIN = 'source-a';
+const OWNER = 'alice-example';
+const META = { sender_label: 'Bob Example', group: 'team-a' };
+
+let engine: PGLiteEngine;
+const tokens: Record<string, { id: string; token: string }> = {};
+const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+const verify = async (who: string) => await provider().verifyAccessToken(tokens[who]!.token) as unknown as AuthInfo;
+
+interface GuestPage { readers?: string | null; sender?: string; group?: string; extra?: string[]; body?: string }
+const guestPage = (o: GuestPage = {}) => ['---', 'type: note', 'title: A note from Bob',
+ ...(o.readers === null ? [] : [`readable_by: ${o.readers ?? `[${OWNER}, bob-example]`}`]),
+ `guest_group: ${o.group ?? 'team-a'}`, `guest_sender: ${o.sender ?? 'Bob Example'}`, 'saved_at: 2026-11-13T10:00:00Z',
+ ...(o.extra ?? []), '---', '# A note from Bob', '',
+ o.body ?? 'Bob met [Carol](people/carol-example) about the harbor ledger. See [[people/carol-example]].\n\n## Timeline\n\n- **2026-11-01** | Met Carol about the ledger'].join('\n');
+
+type Channels = { audience?: string | null; header?: string; meta?: unknown; sourceId?: string };
+const parse = (text: string) => { try { return JSON.parse(text) as Record<string, unknown>; } catch { return {} as Record<string, unknown>; } };
+async function call(who: string, op: string, params: Record<string, unknown>, ch: Channels = {}) {
+ const auth = await verify(who);
+ const out = await dispatchToolCall(engine, op, { ...params }, {
+ remote: true, transport: 'http', auth, sourceId: ch.sourceId ?? SRC, takesHoldersAllowList: ['world'],
+ onBehalfOf: { header: ch.audience === null ? undefined : ch.audience ?? 'bob-example' },
+ guest: { header: ch.header, requestMeta: ch.meta === undefined ? { guest: META } : ch.meta === null ? undefined : { guest: ch.meta } },
+ });
+ const text = out.content.map(c => c.text).join('\n');
+ const json = parse(text);
+ return { isError: out.isError === true, text, json, code: (json.code ?? json.error) as string | undefined };
+}
+async function local(op: string, params: Record<string, unknown>, sourceId = SRC) {
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: false, sourceId });
+ const text = out.content.map(c => c.text).join('\n');
+ const json = parse(text);
+ return { isError: out.isError === true, text, json, code: (json.code ?? json.error) as string | undefined };
+}
+const put = (who: string, slug: string, page: GuestPage = {}, ch: Channels = {}, extra: Record<string, unknown> = {}) =>
+ call(who, 'put_page', { slug, content: guestPage(page), ...extra }, ch);
+const revisionOf = async (slug: string) => (await engine.readPageSnapshot(slug, { sourceId: SRC, includeDeleted: true }))!.revision;
+const codeOf = (fn: () => unknown) => { try { fn(); return null; } catch (e) { return (e as { code?: string }).code ?? String(e); } };
+const slugOf = () => `notes/guest-${randomUUID().slice(0, 8)}`;
+async function pageRow(slug: string, sourceId = SRC) {
+ const [row] = await engine.executeRaw<{ id: number; tier: string; deleted: boolean }>(
+ 'SELECT id, trust_tier AS tier, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ return row ?? null;
+}
+async function markOf(slug: string) {
+ const [row] = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT m.source_id, m.slug_at_write, m.audience_member, m.group_slug, m.sender_label, m.writer_kind, m.writer_id, m.request_id, m.saved_at IS NOT NULL AS saved
+ FROM guest_marks m JOIN pages p ON p.id = m.page_id WHERE p.source_id=$1 AND p.slug=$2`, [SRC, slug]);
+ return row ?? null;
+}
+async function derivedCounts(slug: string) {
+ const [row] = await engine.executeRaw<{ links: number; timeline: number; facts: number; takes: number }>(
+ `SELECT (SELECT count(*)::int FROM links l WHERE l.from_page_id = p.id OR l.to_page_id = p.id) AS links,
+ (SELECT count(*)::int FROM timeline_entries t WHERE t.page_id = p.id) AS timeline,
+ (SELECT count(*)::int FROM facts f WHERE f.source_id = p.source_id) AS facts,
+ (SELECT count(*)::int FROM takes k WHERE k.page_id = p.id) AS takes
+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2`, [SRC, slug]);
+ return row!;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const id of [OWNER, 'bob-example', 'carol-example']) await addMember(engine, id);
+ await addGroup(engine, 'team-a', ['bob-example']);
+ await addGroup(engine, 'team-b', ['carol-example']);
+ await setOwner(engine, OWNER);
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [PLAIN]);
+ await initGuestSource(engine, SRC, []);
+ const mint = async (name: string, grant: string[]) => {
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: grant });
+ tokens[name] = { id: minted.id, token: minted.token };
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { mayActFor: ['member:bob-example', 'member:carol-example', 'group:team-a', 'guest'] });
+ await readsUnscopedOnPurpose(engine, minted.id);
+ };
+ await mint('broker', [SRC]);
+ await mint('other', [SRC]);
+ await mint('plain', [PLAIN]);
+ await changeGuestWriters(engine, SRC, { add: [`legacy_token:${tokens.broker!.id}`] });
+}, 240_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);
+
+describe('guest attribution channel', () => {
+ 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);
+ expect(parseGuestAttribution({ requestMeta: { guest: META } })).toEqual(META);
+ expect(parseGuestAttribution({ header: 'sender_label=Bob%20Example&group=team-a', requestMeta: { guest: META } })).toEqual(META);
+ expect(parseGuestAttribution({})).toBeNull();
+ });
+
+ test('a label or group outside the rules, or header and meta that disagree, is refused', () => {
+ for (const label of ['', 'x'.repeat(65), 'Bob\u202eExample', 'Bob\u200bExample', 'Bob\nExample', 'Bob · Ex', 'Bob [x]', 'Bob <x>', 'Bob "x"'])
+ expect({ label, code: codeOf(() => parseGuestAttribution({ requestMeta: { guest: { sender_label: label, group: 'team-a' } } })) }).toEqual({ label, code: 'guest_attribution_missing' });
+ for (const group of ['Team-A', 'team a', '', 'x'.repeat(65)])
+ expect({ group, code: codeOf(() => parseGuestAttribution({ requestMeta: { guest: { sender_label: 'Bob', group } } })) }).toEqual({ group, code: 'guest_attribution_missing' });
+ expect(codeOf(() => parseGuestAttribution({ header: 'sender_label=Bob&group=team-a', requestMeta: { guest: META } }))).toBe('guest_attribution_missing');
+ expect(codeOf(() => parseGuestAttribution({ requestMeta: { guest: 'Bob' } }))).toBe('guest_attribution_missing');
+ });
+});
+
+describe('guest write admission (pglite, repo-less)', () => {
+ test('a listed writer saves a new guest page: external_untrusted, a guest mark, no derived rows', async () => {
+ const slug = slugOf();
+ const out = await put('broker', slug);
+ expect({ isError: out.isError, code: out.code }).toEqual({ isError: false, code: undefined });
+ const row = await pageRow(slug);
+ expect(row?.tier).toBe('external_untrusted');
+ expect(await markOf(slug)).toEqual({ source_id: SRC, slug_at_write: slug, audience_member: 'member:bob-example', group_slug: 'team-a',
+ sender_label: 'Bob Example', writer_kind: 'legacy_token', writer_id: tokens.broker!.id, request_id: expect.any(String), saved: true });
+ expect(await derivedCounts(slug)).toEqual({ links: 0, timeline: 0, facts: 0, takes: 0 });
+ const [intent] = await engine.executeRaw<{ note: unknown }>("SELECT intent->'guest_note' AS note FROM persistence_requests WHERE source_id=$1 AND slug=$2", [SRC, slug]);
+ expect(intent?.note).toEqual(META);
+ }, 60_000);
+
+ test('the header channel works on its own', async () => {
+ const slug = slugOf();
+ const out = await put('broker', slug, {}, { header: 'sender_label=Bob%20Example&group=team-a', meta: null });
+ expect({ isError: out.isError, code: out.code }).toEqual({ isError: false, code: undefined });
+ expect((await markOf(slug))?.sender_label).toBe('Bob Example');
+ }, 60_000);
+
+ test('a group audience is stored as the group principal', async () => {
+ const slug = slugOf();
+ const out = await put('broker', slug, { readers: `[${OWNER}, group:team-a]` }, { audience: 'group:team-a' });
+ expect({ isError: out.isError, code: out.code }).toEqual({ isError: false, code: undefined });
+ expect((await markOf(slug))?.audience_member).toBe('group:team-a');
+ }, 60_000);
+
+ test('missing or bad attribution is guest_attribution_missing and writes nothing', async () => {
+ for (const ch of [{ meta: null }, { meta: { sender_label: 'Bob\u202eExample', group: 'team-a' } }, { meta: { sender_label: 'Bob\u200b', group: 'team-a' } },
+ { header: 'sender_label=Carol&group=team-a' }] as Channels[]) {
+ const slug = slugOf();
+ const out = await put('broker', slug, {}, ch);
+ expect({ ch, code: out.code }).toEqual({ ch, code: 'guest_attribution_missing' });
+ expect(await pageRow(slug)).toBeNull();
+ }
+ }, 60_000);
+
+ test('a credential not on the writer list is source_writer_restricted', async () => {
+ const slug = slugOf();
+ const out = await put('other', slug);
+ expect(out.code).toBe('source_writer_restricted');
+ expect(out.text).not.toMatch(/writers --add|add (it|the credential) as a writer/i);
+ expect(await pageRow(slug)).toBeNull();
+ }, 60_000);
+
+ test('local CLI writes, an enforced member, remember and import refuse on a guest source', async () => {
+ const slug = slugOf();
+ expect((await local('put_page', { slug, content: guestPage() })).code).toBe('source_writer_restricted');
+ expect((await local('remember', { fact: 'Bob likes tea', provenance: 'test 2026-11-13' })).code).toBe('source_writer_restricted');
+ const member = await dispatchToolCall(engine, 'put_page', { slug, content: guestPage() }, {
+ remote: true, transport: 'stdio', stdioMember: 'bob-example', enforcedMember: true, sourceId: SRC, takesHoldersAllowList: ['world'] });
+ expect(parse(member.content[0]!.text).code).toBe('source_writer_restricted');
+ await expect(importFromContent(engine, slug, guestPage(), { sourceId: SRC })).rejects.toThrow(/source_writer_restricted/);
+ const dir = mkdtempSync(join(tmpdir(), 'gb-guest-import-'));
+ try {
+ mkdirSync(join(dir, 'notes'));
+ writeFileSync(join(dir, 'notes', 'a.md'), guestPage());
+ await expect(runImport(engine, [dir, '--source', SRC, '--no-embed'])).rejects.toThrow(/source_writer_restricted/);
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ expect(await pageRow(slug)).toBeNull();
+ expect(await pageRow('notes/a')).toBeNull();
+ }, 120_000);
+
+ test('the local owner can still delete and restore a guest page; a remote non-writer cannot delete', async () => {
+ const slug = slugOf();
+ expect((await put('broker', slug)).isError).toBe(false);
+ expect((await call('other', 'delete_page', { slug, expected_revision: await revisionOf(slug) })).code).toBe('source_writer_restricted');
+ expect((await pageRow(slug))?.deleted).toBe(false);
+ const del = await local('delete_page', { slug, expected_revision: await revisionOf(slug) });
+ expect({ isError: del.isError, code: del.code }).toEqual({ isError: false, code: undefined });
+ expect((await pageRow(slug))?.deleted).toBe(true);
+ const restored = await local('restore_page', { slug, expected_revision: await revisionOf(slug) });
+ expect({ isError: restored.isError, code: restored.code }).toEqual({ isError: false, code: undefined });
+ const row = await pageRow(slug);
+ expect(row?.deleted).toBe(false);
+ expect((await engine.executeRaw('SELECT 1 FROM content_chunks WHERE page_id=$1', [row!.id])).length).toBeGreaterThan(0);
+ expect(await markOf(slug)).not.toBeNull();
+ }, 60_000);
+
+ test('guest pages are create-only', async () => {
+ const slug = slugOf();
+ expect((await put('broker', slug)).isError).toBe(false);
+ expect((await put('broker', slug, { body: 'Rewritten.' })).code).toBe('revision_required');
+ expect((await put('broker', slug, { body: 'Rewritten.' }, {}, { force: true })).code).toBe('guest_page_immutable');
+ expect((await put('broker', slug, { body: 'Rewritten.' }, {}, { expected_revision: await revisionOf(slug) })).code).toBe('guest_page_immutable');
+ expect((await call('broker', 'edit_page', { slug, edits: [{ old_text: 'Bob met', new_text: 'Bob saw' }], expected_revision: await revisionOf(slug) })).code).toBe('guest_page_immutable');
+ expect((await call('broker', 'add_timeline_entry', { slug, date: '2026-11-02', summary: 'Again' })).code).toBe('guest_page_immutable');
+ expect((await call('broker', 'append_page', { slug, text: 'More.', request_id: randomUUID() })).code).toBe('guest_page_immutable');
+ expect((await call('broker', 'add_link', { from: slug, to: slug })).code).toBe('guest_page_immutable');
+ expect((await call('other', 'add_link', { from: slug, to: slug })).code).toBe('source_writer_restricted');
+ expect((await call('broker', 'remember', { fact: 'Bob likes tea', provenance: 'test 2026-11-13' })).code).toBe('guest_page_immutable');
+ const batch = await call('broker', 'put_pages', { pages: [{ slug: slugOf(), content: guestPage() }], request_id: randomUUID() });
+ expect((batch.json.pages as Array<{ error?: { code?: string } }>)?.map(page => page.error?.code)).toEqual(['guest_page_immutable']);
+ const del = await call('broker', 'delete_page', { slug, expected_revision: await revisionOf(slug) });
+ expect({ isError: del.isError, code: del.code }).toEqual({ isError: false, code: undefined });
+ expect((await put('broker', slug)).code).toBe('guest_page_immutable');
+ }, 120_000);
+
+ test('the frontmatter allowlist and the sender and group match', async () => {
+ for (const [label, page] of [
+ ['extra key', { extra: ['tags: [x]'] }], ['visibility', { extra: ['visibility: private'] }], ['trust key', { extra: ['trust_tier: owner'] }],
+ ['sender mismatch', { sender: 'Carol Example' }], ['group mismatch', { group: 'team-b' }],
+ ] as Array<[string, GuestPage]>) {
+ const slug = slugOf();
+ expect({ label, code: (await put('broker', slug, page)).code }).toEqual({ label, code: 'guest_frontmatter_refused' });
+ expect(await pageRow(slug)).toBeNull();
+ }
+ }, 120_000);
+
+ test('readers must be exactly the owner and the one audience principal', async () => {
+ const refused: Array<[string, GuestPage, Channels]> = [
+ ['owner dropped', { readers: '[bob-example]' }, {}],
+ ['extra group', { readers: `[${OWNER}, bob-example, group:team-b]` }, {}],
+ ['two-entry audience', { readers: `[${OWNER}, bob-example, carol-example]` }, { audience: 'bob-example, carol-example' }],
+ ];
+ for (const [label, page, ch] of refused) {
+ const slug = slugOf();
+ expect({ label, code: (await put('broker', slug, page, ch)).code }).toEqual({ label, code: 'guest_readers_invalid' });
+ expect(await pageRow(slug)).toBeNull();
+ }
+ for (const [label, page, ch] of [['no readers', { readers: null }, {}], ['no audience', {}, { audience: null }]] as Array<[string, GuestPage, Channels]>) {
+ const slug = slugOf();
+ expect({ label, refused: ['guest_readers_invalid', 'readable_by_invalid'].includes(String((await put('broker', slug, page, ch)).code)) }).toEqual({ label, refused: true });
+ expect(await pageRow(slug)).toBeNull();
+ }
+ await clearOwner(engine);
+ try {
+ const slug = slugOf();
+ expect((await put('broker', slug)).code).toBe('guest_readers_invalid');
+ } finally { await setOwner(engine, OWNER); }
+ }, 120_000);
+
+ test('the same request_id with different attribution is idempotency_conflict', async () => {
+ const slug = slugOf();
+ const requestId = randomUUID();
+ expect((await call('broker', 'put_page', { slug, content: guestPage(), request_id: requestId })).isError).toBe(false);
+ const replay = await call('broker', 'put_page', { slug, content: guestPage(), request_id: requestId }, { meta: { sender_label: 'Bob Example', group: 'team-b' } });
+ expect(replay.code).toBe('idempotency_conflict');
+ }, 60_000);
+
+ test('attribution sent with a write outside a guest source is ignored and stored nowhere', async () => {
+ const slug = slugOf();
+ const out = await call('plain', 'put_page', { slug, content: '---\ntype: note\ntitle: Plain\n---\n# Plain\n\nPlain words.' }, { sourceId: PLAIN, audience: null });
+ expect({ isError: out.isError, code: out.code }).toEqual({ isError: false, code: undefined });
+ const [row] = await engine.executeRaw<{ note: unknown; tier: string }>(
+ "SELECT r.intent->'guest_note' AS note, p.trust_tier AS tier FROM persistence_requests r JOIN pages p ON p.source_id=r.source_id AND p.slug=r.slug WHERE r.source_id=$1 AND r.slug=$2", [PLAIN, slug]);
+ expect(row?.note ?? null).toBeNull();
+ expect(row?.tier).not.toBe('external_untrusted');
+ expect((await engine.executeRaw('SELECT 1 FROM guest_marks WHERE source_id=$1', [PLAIN])).length).toBe(0);
+ }, 60_000);
+
+ test('a writer removed between admission and publication refuses at publication', async () => {
+ const slug = slugOf();
+ const auth = await verify('broker');
+ const params = { slug, content: guestPage(), request_id: randomUUID() };
+ const ctx = buildOperationContext(engine, params, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'],
+ guest: { requestMeta: { guest: META } } });
+ const access = await remoteCallerAccess(engine, auth, undefined, 'http', parseAudience({ header: 'bob-example' }), undefined, false);
+ const row = await withCallerAccess(access, async () => {
+ const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params });
+ return admitWrite(engine, prepared.admission!);
+ });
+ const [stored] = await engine.executeRaw<{ note: unknown }>("SELECT intent->'guest_note' AS note FROM persistence_requests WHERE request_id=$1::uuid", [row.request_id]);
+ expect(stored?.note).toEqual(META);
+ const writer = `legacy_token:${tokens.broker!.id}`;
+ await changeGuestWriters(engine, SRC, { remove: [writer] });
+ try {
+ const settled = await waitForWrite(engine, row, ctx.config, 10_000);
+ expect({ state: settled.state, code: settled.error_code }).toEqual({ state: 'failed', code: 'source_writer_restricted' });
+ expect(await pageRow(slug)).toBeNull();
+ } finally { await changeGuestWriters(engine, SRC, { add: [writer] }); }
+ }, 60_000);
+});