Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Guest notes stay marked even when the guest-source shortcut is missing (GBRA-504)
garrytaned6a4a2b3af1
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 3ed4a33bdb..18328578d3 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -34,7 +34,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/trust.ts` — `confirm_memory` (#5575 A4, CEO-9, DX-20): the one MCP-visible owner action. Raises a fact, take or page to `user_confirmed` through `trust/owner-actions.ts` after `requireOwnerConfirmation` (a `memory_confirm` connection, or the local CLI's typed-token TTY prompt); agent tokens get `insufficient_scope` with a `tell_user_to_run` fix naming `gbrain trust confirm <ref>`. Trust proposals and holds are not reachable here; the other owner actions are CLI or resident-owner administration only (`trust/owner-ipc.ts`).- `src/core/guests/{schema,sources}.ts` — GBRA-504 guest sources. `schema.ts` is migration v312's DDL: `guest_sources` (the authority for which sources are guest sources, their writer list of `<kind>:<id>` attribution principals and their tier ceiling), `guest_marks` (immutable: `gbrain_guard_guest_records` refuses UPDATE; rows leave only with their page) and `guest_promotions`, RLS on, and the guard that keeps a guest source database-only (no `local_path`). The trust trigger (`trust/schema.ts` `GUEST_AWARE_STAMP_TIER_FUNCTION`, installed by v312; v226 keeps its own body) clamps a guest page to the ceiling on every exit, refuses a page INSERT or content change (any content column but `deleted_at`) unless `gbrain.write_principal_kind`:`gbrain.write_principal_id` is on the writer list, and refuses facts, takes and timeline rows there. `sources.ts` holds the reads and writes behind `gbrain guests init` and `gbrain sources writers`.-- `src/core/guests/{marker,stamp}.ts`, `src/core/access/page-items.ts`, `src/cli/guest-lines.ts` — GBRA-504 slice 3: the guest warning on every read. `marker.ts` holds the `GuestStamp` object (`sender_label`, `group`, `audience_member`, `saved_at` day, `promoted`, `writer` for owner callers only, `unattributed`), the warning line, the quote-fence label, think's fixed `Uses outside-guest notes:` line, `loadGuestMarks` (one batched `guest_marks` read; a failed read leaves rows unattributed, never bare) and `withGuestMarks`, which `operation-load.ts` `finalizeOperation` wraps around every op whose `outputRedaction` is not `no_stored_text`. It runs only when config `guests.present` (set by `initGuestSource`, sticky) is `true` or unreadable; `stamp.ts` `stampGuestNotes` then finds page items with `page-items.ts` `collectPageItems` (the walker shared with `access/room.ts`; it also reads `fetch` rows by their `gbrain://page/` url), reads guest rows through `eligibility/stamp.ts` `loadPageTrust`, and stamps a copy with `origin: guest`, `external_untrusted` and the `guest` object; a failed load fails the read. `eligibility/labels.ts` prints the warning line before the `origin="guest"` envelope, `eligibility/activation.ts` and `context/turn-context.ts` carry the stamp on `delta`, and the CLI prints it through `search-row-format.ts`, `page-render.ts` and `guest-lines.ts`. Publication refuses a plain write that lands after its source became a guest source (`guests/admission.ts` `assertNoGuestSourceAtPublication`). Servers list capability `guest_marker_v1`. Tests: `test/guest-notes-warning.test.ts`, `test/guest-notes-contract.test.ts` (every op that returns stored text, as owner over HTTP and stdio and as the audience member).+- `src/core/guests/{marker,stamp}.ts`, `src/core/access/page-items.ts`, `src/cli/guest-lines.ts` — GBRA-504 slice 3: the guest warning on every read. `marker.ts` holds the `GuestStamp` object (`sender`, from `guest_marks.sender_label`; `group`, `audience_member`, `saved_at` day, `promoted`, `writer` for owner callers only, `unattributed`), the warning line, the quote-fence label, think's fixed `Uses outside-guest notes:` line, `loadGuestMarks` (one batched `guest_marks` read; a failed read leaves rows unattributed, never bare) and `withGuestMarks`, which `operation-load.ts` `finalizeOperation` wraps around every op whose `outputRedaction` is not `no_stored_text`. `stamp.ts` `stampGuestNotes` finds page items with `page-items.ts` `collectPageItems` (the walker shared with `access/room.ts`; it also reads `fetch` rows by their `gbrain://page/` url), skips the trust load only when `marker.ts` `brainHasGuestSource` (one read of `sources` and `guest_sources`, yes when it fails) finds no guest source, reads guest rows through `eligibility/stamp.ts` `loadPageTrust` (a source is a guest source when its config says so or `guest_sources` lists it, `guestSourceSql`), and stamps a copy with `origin: guest`, `external_untrusted` and the `guest` object; a failed load fails the read. `eligibility/labels.ts` prints the warning line before the `origin="guest"` envelope, `eligibility/activation.ts` and `context/turn-context.ts` carry the stamp on `delta`, and the CLI prints it through `search-row-format.ts`, `page-render.ts` and `guest-lines.ts`. Publication refuses a plain write that lands after its source became a guest source (`guests/admission.ts` `assertNoGuestSourceAtPublication`). Servers list capability `guest_marker_v1`. Tests: `test/guest-notes-warning.test.ts`, `test/guest-notes-contract.test.ts` (every op that returns stored text, as owner over HTTP and stdio and as the audience member), `test/guest-notes-shortcut.test.ts` (a source marked guest without `gbrain guests init` is still marked).- `src/core/health-memo.ts` — in-process memo for the `get_health` op only (O-ENG-13). An entry is reused when engine object, scope key (`all`, `scalar:<id>`, `set:<sorted unique ids>`, `empty` for an empty or no-sources grant; derived from the exact scope handed to `engine.getHealth`, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (`page_generation_clock_seq.last_value` plus the `persistence_brain` id) and TTL all match. TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config `health.cache_ttl_ms`, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch `pages` (links, timeline rows, chunks). A failed clock/config read computes uncached. `engine.getHealth` stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; `gbrain repair --apply` and `gbrain doctor --remediate` call `clearHealthMemo`. Pinned by `test/health-memo.test.ts`.diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.mdindex 5e4438c8c0..4428b9dac3 100644--- a/docs/guides/guest-notes.md+++ b/docs/guides/guest-notes.md@@ -132,7 +132,7 @@ the local CLI alike. JSON results give the row `origin: "guest"`, trust tier`external_untrusted` and a `guest` object:```json-{ "sender_label": "Bob Example", "group": "team-a", "audience_member": "member:bob-example",+{ "sender": "Bob Example", "group": "team-a", "audience_member": "member:bob-example","saved_at": "2026-11-13", "promoted": false, "writer": "legacy_token:<id>" }```diff --git a/src/core/eligibility/activation.ts b/src/core/eligibility/activation.tsindex b6115a6989..800f3b9ab4 100644--- a/src/core/eligibility/activation.ts+++ b/src/core/eligibility/activation.ts@@ -18,7 +18,7 @@import type { BrainEngine } from '../engine.ts';import type { Notice } from '../agent-output.ts';import { admitsTrust, minTrust, storedTrustTier, type TrustTier } from '../trust/tier.ts';-import { guestView, loadGuestMarks, unattributedGuest, type GuestStamp } from '../guests/marker.ts';+import { guestSourceSql, guestView, loadGuestMarks, unattributedGuest, type GuestStamp } from '../guests/marker.ts';import { activationSuppressedSql, type EligibilityTable } from './sql.ts';import type { ReadEligibility } from './policy.ts';@@ -132,7 +132,7 @@ export async function pageActivationVerdicts(engine: Exec, keys: readonly PageKeif (keys.length === 0) return out;const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; trust_tier: string; write_origin: unknown; flagged: boolean; guest: boolean }>(`SELECT a.id, a.source_id, a.slug, a.trust_tier, a.write_origin, ${activationSuppressedSql('pages', 'a')} AS flagged,- COALESCE(s.config->>'guest' = 'true', false) AS guest FROM pages a LEFT JOIN sources s ON s.id = a.source_id+ ${guestSourceSql('s.config', 'a.source_id')} AS guest FROM pages a LEFT JOIN sources s ON s.id = a.source_idWHERE a.deleted_at IS NULL AND (a.source_id, a.slug) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,[keys.map(k => k.source_id), keys.map(k => k.slug)]);// GBRA-504: a page in a guest source carries its guest mark (one batched read), or reads unattributed.diff --git a/src/core/eligibility/stamp.ts b/src/core/eligibility/stamp.tsindex 511d27917c..305fdbe43b 100644--- a/src/core/eligibility/stamp.ts+++ b/src/core/eligibility/stamp.ts@@ -12,7 +12,7 @@ import { admitsTrust, compareTrust, minTrust, storedTrustTier, type TrustTier }import { chunkFenceMarker, FENCE_TRUST_ORIGIN, fenceTrustMarker, lowestFenceTrustMarker } from './fence-overlay.ts';import { needsDataEnvelope, parseContested, renderTrustedText, trustFields, type Contested, type TrustFields } from './labels.ts';import { activationSuppressedSql, contestedRefSql } from './sql.ts';-import { GUEST_ORIGIN, guestView, loadGuestMarks, unattributedGuest, type GuestStamp } from '../guests/marker.ts';+import { GUEST_ORIGIN, guestSourceSql, guestView, loadGuestMarks, unattributedGuest, type GuestStamp } from '../guests/marker.ts';const withFlag = (fields: TrustFields, flagged: unknown): TrustFields => (flagged === true ? { ...fields, unconfirmed: true } : fields);@@ -29,11 +29,11 @@ const key = (source: string | null | undefined, slug: string) => `${source ?? 'dtype TrustRow = { id: number; source_id: string; slug: string; trust_tier: string; write_origin: unknown; flagged: boolean; guest: boolean };const TRUST_COLUMNS = `pages.id, pages.source_id, pages.slug, pages.trust_tier, pages.write_origin, ${activationSuppressedSql('pages', 'pages')} AS flagged,- COALESCE(s.config->>'guest' = 'true', false) AS guest FROM pages LEFT JOIN sources s ON s.id = pages.source_id`;+ ${guestSourceSql('s.config', 'pages.source_id')} AS guest FROM pages LEFT JOIN sources s ON s.id = pages.source_id`;/*** Trust fields per page id and per (source_id, slug). GBRA-504: a row in a guest source is decided here, per row from- * its source, and carries origin `guest`, the external tier and its guest mark (one batched guest_marks read, only+ * its source's config and guest_sources (guests/marker.ts guestSourceSql), and carries origin `guest`, the external tier and its guest mark (one batched guest_marks read, only* when a guest row is among them; a mark that cannot be read leaves the row unattributed, never bare). The writer is* shown only with `guestWriter` (an owner caller); `includeDeleted` also resolves soft-deleted pages by slug.*/diff --git a/src/core/guests/marker.ts b/src/core/guests/marker.tsindex 900ccfb6ff..d4949cfe12 100644--- a/src/core/guests/marker.ts+++ b/src/core/guests/marker.ts@@ -3,7 +3,7 @@** A row is a guest row when its page's source is a guest source (`sources.config.guest`), decided per row inside the* batched trust load (eligibility/stamp.ts loadPageTrust), never from a process cache. Its JSON form is- * `origin: "guest"` plus a `guest` object (sender_label, group, audience_member, saved_at, promoted, and the writer+ * `origin: "guest"` plus a `guest` object (sender, group, audience_member, saved_at, promoted, and the writer* for owner callers only); its text form is one warning line followed by the external-data envelope. A guest row* whose mark cannot be read reads as `unattributed`, never bare. The page text never feeds any of it, and labels are* escaped on render even though admission already refused those characters (guests/admission.ts).@@ -15,14 +15,24 @@ export const GUEST_ORIGIN = 'guest';/** get_brain_identity lists it: this brain stamps the guest warning on every read, so a guest broker may switch on. */export const GUEST_MARKER_CAPABILITY = 'guest_marker_v1';/**- * Set by `gbrain guests init` (guests/sources.ts) in the transaction that makes a source a guest source and never- * cleared; read per request from the request's config snapshot. Unset, the brain has no guest source, so no read- * pays for guest stamping. Whether a row is a guest row is still decided from the sources table.+ * SQL true when a source is a guest source: its config says `guest: true` or guest_sources lists it. Either record is+ * enough, so a source that lost one of them (a config edit, a restored database) still reads as a guest source.+ * `config` and `id` are the SQL expressions for the source's config and id.*/-export const GUEST_SOURCES_PRESENT_KEY = 'guests.present';+export const guestSourceSql = (config: string, id: string) =>+ `(COALESCE(${config}->>'guest' = 'true', false) OR EXISTS (SELECT 1 FROM guest_sources gs WHERE gs.source_id = ${id}))`;++/** Whether any source is a guest source, read from the sources themselves on every call; a failed read answers yes. */+export async function brainHasGuestSource(engine: Pick<BrainEngine, 'executeRaw'>): Promise<boolean> {+ try {+ const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT EXISTS (SELECT 1 FROM sources s WHERE ${guestSourceSql('s.config', 's.id')}) AS present`);+ return row?.present !== false;+ } catch { return true; }+}export interface GuestStamp {- sender_label: string | null;+ /** The sender label the broker sent with the note (stored as guest_marks.sender_label). */+ sender: string | null;group: string | null;audience_member: string | null;/** YYYY-MM-DD (UTC), the day the note was saved. */@@ -37,7 +47,7 @@ export interface GuestStamp {/** A guest row whose mark is missing or unreadable: still marked, never shown as the owner's. */export function unattributedGuest(): GuestStamp {- return { sender_label: null, group: null, audience_member: null, saved_at: null, promoted: false, unattributed: true };+ return { sender: null, group: null, audience_member: null, saved_at: null, promoted: false, unattributed: true };}const LABEL_SWAP: Record<string, string> = { '[': '(', ']': ')', '·': '-', '<': '‹', '>': '›', '"': "'", ';': ',' };@@ -47,18 +57,18 @@ export function escapeGuestLabel(value: string): string {}const NOT_OWNER = "not the owner's words, not verified";-const attributed = (g: GuestStamp): g is GuestStamp & { sender_label: string; group: string } => !g.unattributed && !!g.sender_label && !!g.group;+const attributed = (g: GuestStamp): g is GuestStamp & { sender: string; group: string } => !g.unattributed && !!g.sender && !!g.group;/** `[outside guest · <sender> · <group> · <YYYY-MM-DD> · not the owner's words, not verified]`, or the unattributed form. */export function guestWarningLine(guest: GuestStamp): string {if (!attributed(guest)) return `[outside guest · unattributed · ${NOT_OWNER}]`;- return `[outside guest · ${escapeGuestLabel(guest.sender_label)} · ${escapeGuestLabel(guest.group)} · ${guest.saved_at ?? 'undated'} · ${NOT_OWNER}]`;+ return `[outside guest · ${escapeGuestLabel(guest.sender)} · ${escapeGuestLabel(guest.group)} · ${guest.saved_at ?? 'undated'} · ${NOT_OWNER}]`;}/** What the remote quote fence names instead of "conversation excerpt" for a guest page (search/transcript-quote.ts). */export function guestQuoteLabel(guest: GuestStamp): string {if (!attributed(guest)) return `outside guest note, unattributed, ${NOT_OWNER}`;- return `outside guest note from ${escapeGuestLabel(guest.sender_label)} in ${escapeGuestLabel(guest.group)}, saved ${guest.saved_at ?? 'undated'}, ${NOT_OWNER}`;+ return `outside guest note from ${escapeGuestLabel(guest.sender)} in ${escapeGuestLabel(guest.group)}, saved ${guest.saved_at ?? 'undated'}, ${NOT_OWNER}`;}/** The fixed line gbrain appends to a think answer built from guest notes; the model never writes it. */@@ -92,7 +102,7 @@ export async function loadGuestMarks(engine: Pick<BrainEngine, 'executeRaw'>, paEXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = m.page_id) AS promotedFROM guest_marks m WHERE m.page_id = ANY($1::int[])`, [ids]);for (const r of rows) {- out.set(Number(r.page_id), { sender_label: r.sender_label, group: r.group_slug, audience_member: r.audience_member, saved_at: day(r.saved_at),+ out.set(Number(r.page_id), { sender: r.sender_label, group: r.group_slug, audience_member: r.audience_member, saved_at: day(r.saved_at),promoted: r.promoted === true, writer: `${r.writer_kind}:${r.writer_id}` });}} catch { /* every guest row reads unattributed */ }@@ -101,16 +111,13 @@ export async function loadGuestMarks(engine: Pick<BrainEngine, 'executeRaw'>, pa/*** The registration-time wrapper (operation-load.ts finalizeOperation): every op that may return stored text has its- * result stamped by guests/stamp.ts. A brain that never ran `gbrain guests init` pays one config read, answered by the- * request's config snapshot; an unreadable config is treated as a brain with guest sources, so the stamp still runs.+ * result stamped by guests/stamp.ts, which skips the trust load only when the sources say no source is a guest source.*/export function withGuestMarks(op: Pick<Operation, 'outputRedaction'>, handler: Operation['handler']): Operation['handler'] {if (op.outputRedaction === 'no_stored_text') return handler;return async (ctx, params) => {const result = await handler(ctx, params);- if (!result || typeof result !== 'object' || typeof ctx.engine?.getConfig !== 'function') return result;- const present = await ctx.engine.getConfig(GUEST_SOURCES_PRESENT_KEY).catch(() => 'true');- if (present !== 'true') return result;+ if (!result || typeof result !== 'object' || typeof ctx.engine?.executeRaw !== 'function') return result;const { stampGuestNotes } = await import('./stamp.ts');return stampGuestNotes(ctx, result);};diff --git a/src/core/guests/sources.ts b/src/core/guests/sources.tsindex d36284aff8..9813383759 100644--- a/src/core/guests/sources.ts+++ b/src/core/guests/sources.ts@@ -10,7 +10,6 @@ import type { Principal } from '../persistence/model.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { addSource } from '../sources-ops.ts';import type { TrustTier } from '../trust/tier.ts';-import { GUEST_SOURCES_PRESENT_KEY } from './marker.ts';export const GUEST_TRUST_CEILING: TrustTier = 'external_untrusted';const PRINCIPAL_KINDS: readonly Principal['kind'][] = ['oauth_client', 'legacy_token', 'local_cli', 'local_stdio', 'application'];@@ -41,9 +40,9 @@ export async function planGuestSource(engine: BrainEngine, sourceId: string, wri/*** Makes `sourceId` a guest source: creates it database-only and federated when- * missing, sets its guest config, writes its guest_sources row and sets the- * brain's guest-sources marker (guests/marker.ts GUEST_SOURCES_PRESENT_KEY), in one+ * missing, sets its guest config and writes its guest_sources row, in one* transaction (a managed brain creates the source through its lifecycle first).+ * Reads find guest sources from these two records (guests/marker.ts guestSourceSql).* The database refuses a source with a local_path (guest_source_database_only).*/export async function initGuestSource(engine: BrainEngine, sourceId: string, writers: readonly string[]): Promise<GuestSource> {@@ -57,7 +56,6 @@ export async function initGuestSource(engine: BrainEngine, sourceId: string, wriconst [row] = await tx.executeRaw<GuestSource>(`INSERT INTO guest_sources (source_id, writers, trust_ceiling) VALUES ($1, $2::text[], $3)ON CONFLICT (source_id) DO UPDATE SET writers = ARRAY(SELECT DISTINCT w FROM unnest(guest_sources.writers || EXCLUDED.writers) AS w ORDER BY w)RETURNING source_id, writers, trust_ceiling`, [sourceId, [...new Set(writers)].sort(), GUEST_TRUST_CEILING]);- await tx.executeRaw(`INSERT INTO config (key, value) VALUES ($1, 'true') ON CONFLICT (key) DO UPDATE SET value = 'true'`, [GUEST_SOURCES_PRESENT_KEY]);return row!;});}diff --git a/src/core/guests/stamp.ts b/src/core/guests/stamp.tsindex ebbcb5cc43..45da5cf96a 100644--- a/src/core/guests/stamp.ts+++ b/src/core/guests/stamp.ts@@ -12,7 +12,7 @@ import { currentCallerAccess } from '../search/private-visibility.ts';import { collectPageItems, type Ref } from '../access/page-items.ts';import { loadPageTrust } from '../eligibility/stamp.ts';import { relabelGuestQuote } from '../search/transcript-quote.ts';-import { GUEST_ORIGIN, guestQuoteLabel } from './marker.ts';+import { brainHasGuestSource, GUEST_ORIGIN, guestQuoteLabel } from './marker.ts';/** An owner caller sees the guest note's writer: the trusted local CLI, or a credential bound to the owner speaking for no one else. */export function guestViewerIsOwner(ctx: Pick<OperationContext, 'remote'>): boolean {@@ -34,12 +34,14 @@ const refSlug = (r: Ref) => (r.kind === 'page' ? r.slug : undefined);/*** `result` with every guest item stamped, on a detached copy (handlers may return cached objects), or `result` itself- * when nothing in it is a guest row. A failed trust load fails the read rather than return a guest note unmarked.+ * when nothing in it is a guest row. The trust load is skipped only when no source is a guest source (marker.ts+ * brainHasGuestSource, which answers yes when it cannot tell); a failed trust load fails the read rather than return a+ * guest note unmarked.*/export async function stampGuestNotes(ctx: Pick<OperationContext, 'engine' | 'remote' | 'sourceId'>, result: unknown): Promise<unknown> {if (!result || typeof result !== 'object') return result;const found = collectPageItems(result, ctx.sourceId ?? 'default').filter(s => s.ref !== null && s.ref.kind !== 'fact');- if (!found.length) return result;+ if (!found.length || !(await brainHasGuestSource(ctx.engine))) return result;const refs = found.map(s => s.ref!).map(r => r.kind === 'page' ? { source_id: r.source_id, slug: r.slug } : { page_id: (r as { id: number }).id, slug: '' });const trust = await loadPageTrust(ctx.engine, refs, { guestWriter: guestViewerIsOwner(ctx), includeDeleted: true });const guestOf = (r: Ref) => (r.kind === 'page' ? trust.byKey.get(`${r.source_id}\u0000${r.slug}`) : r.kind === 'page_id' ? trust.byId.get(r.id) : undefined)?.guest;diff --git a/test/guest-notes-contract.test.ts b/test/guest-notes-contract.test.tsindex 84aaba6ad1..1b86dfe97a 100644--- a/test/guest-notes-contract.test.ts+++ b/test/guest-notes-contract.test.ts@@ -119,7 +119,7 @@ const CLASSIFIED: Record<string, Args | { skip: string }> = {questions_status: { id: 'q-1' },};/** Reads whose owner answer must contain the guest page's text, so the contract is exercised, not vacuous. */-const MUST_REACH = ['get_page', 'list_pages', 'find_pages', 'search', 'query', 'search_exact', 'get_chunks', 'fetch'];+const MUST_REACH = ['get_page', 'list_pages', 'find_pages', 'search', 'query', 'search_exact', 'get_chunks', 'fetch', 'get_versions', 'chronicle_day'];let engine: PGLiteEngine;const tokens: Record<string, { id: string; token: string }> = {};@@ -195,8 +195,16 @@ beforeAll(async () => {expect(put.isError).not.toBe(true);const [m] = await engine.executeRaw<{ sender_label: string; group_slug: string; audience_member: string; saved_at: Date | string; writer_kind: string; writer_id: string }>('SELECT m.* FROM guest_marks m JOIN pages p ON p.id = m.page_id WHERE p.source_id = $1 AND p.slug = $2', [SRC, GUEST]);- expected = { sender_label: m!.sender_label, group: m!.group_slug, audience_member: m!.audience_member, saved_at: new Date(m!.saved_at).toISOString().slice(0, 10),+ expected = { sender: m!.sender_label, group: m!.group_slug, audience_member: m!.audience_member, saved_at: new Date(m!.saved_at).toISOString().slice(0, 10),promoted: false, writer: m!.writer_kind + ':' + m!.writer_id };+ // A version and a timeline entry on the guest page, as a page has when its source became a guest source after it was+ // written and edited, so get_versions and chronicle_day return guest text.+ // The trust trigger refuses a timeline row on a guest source today, so the fixture sets the row in with triggers off.+ await engine.transaction(async tx => {+ await tx.executeRaw('SET LOCAL session_replication_role = replica');+ await tx.executeRaw('INSERT INTO page_versions (page_id, compiled_truth, frontmatter) SELECT id, compiled_truth, frontmatter FROM pages WHERE source_id = $1 AND slug = $2', [SRC, GUEST]);+ await tx.executeRaw("INSERT INTO timeline_entries (page_id, date, summary) SELECT id, $3::date, 'Bob says the offsite moved to Friday.' FROM pages WHERE source_id = $1 AND slug = $2", [SRC, GUEST, TODAY]);+ });}, 240_000);afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);@@ -229,7 +237,7 @@ describe('G3: every op that returns stored text carries the guest warning', () =const line = guestWarningLine(expected);const bad: string[] = [];for (const [op, args] of [['get_page', { slug: GUEST }], ['list_pages', { source_id: SRC }], ['find_pages', { pattern: 'notes/*' }], ['search', { query: SENTINEL }],- ['search_exact', { phrase: SENTINEL }], ['get_chunks', { slug: GUEST }], ['get_versions', { slug: GUEST, include_body: true }]] as Array<[string, Args]>) {+ ['search_exact', { phrase: SENTINEL }], ['get_chunks', { slug: GUEST }], ['get_versions', { slug: GUEST, include_body: true }], ['chronicle_day', { date: TODAY }]] as Array<[string, Args]>) {const out = await dispatchToolCall(engine, op, { ...args }, { remote: false, sourceId: SRC });const result = JSON.parse(out.content[0]!.text);const text = withGuestLines(op, result, {}, formatResult(op, result, {}));diff --git a/test/guest-notes-shortcut.test.ts b/test/guest-notes-shortcut.test.tsnew file mode 100644index 0000000000..7df3cc833e--- /dev/null+++ b/test/guest-notes-shortcut.test.ts@@ -0,0 +1,79 @@+/**+ * Guest notes (GBRA-504): no config key can hide a guest source.+ *+ * Protects: whether a read stamps guest notes is decided from the sources themselves, never from a separate marker, so+ * a source marked guest by a config edit alone (no `gbrain guests init`), or listed in guest_sources after its config+ * lost the guest key (a restored database, a config rewrite), still has its pages marked when a remote caller reads+ * them; and a failed guest-source check marks or refuses the read, never returns it bare.+ *+ * Real seams: MCP dispatch of list_pages over stdio as the owner on a repo-less PGLite brain; the source changes are+ * plain SQL.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { addMember } from '../src/core/access/members.ts';+import { setOwner } from '../src/core/access/owner.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';++const OWNER = 'alice-example';+const EDITED = 'source-edited';+const LISTED = 'source-listed';+const FAILED = 'source-failed';+const SLUG = 'notes/visitor';++let engine: PGLiteEngine;++/** list_pages: an op with no trust stamp of its own, so only the read-time guest stamp can mark its rows. */+async function readAsOwner(sourceId: string) {+ const out = await dispatchToolCall(engine, 'list_pages', {}, { remote: true, transport: 'stdio', stdioMember: OWNER, sourceId, takesHoldersAllowList: ['world'] });+ const text = out.content[0]!.text;+ let rows: any[] = [];+ try { const parsed = JSON.parse(text); rows = Array.isArray(parsed) ? parsed : parsed.pages ?? []; } catch { /* an error text */ }+ return { isError: out.isError === true, text, json: rows.find(r => r.slug === SLUG) ?? null };+}+const marked = (out: Awaited<ReturnType<typeof readAsOwner>>) =>+ ({ isError: out.isError, origin: out.json?.origin, tier: out.json?.trust_tier, unattributed: out.json?.guest?.unattributed });+const MARKED = { isError: false, origin: 'guest', tier: 'external_untrusted', unattributed: true };++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await addMember(engine, OWNER);+ await setOwner(engine, OWNER);+ for (const id of [EDITED, LISTED, FAILED]) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ await importFromContent(engine, SLUG, '---\ntype: note\ntitle: Visitor note\n---\n# Visitor note\n\nA visitor wrote this in ' + id + '.\n', { sourceId: id });+ }+}, 240_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);++describe('a guest source the guests command never set up', () => {+ test('a source marked guest by a config edit alone is marked on a remote read', async () => {+ const before = await readAsOwner(EDITED);+ expect({ isError: before.isError, found: before.json !== null, origin: before.json?.origin === 'guest' }).toEqual({ isError: false, found: true, origin: false });+ await engine.executeRaw(`UPDATE sources SET config = config || '{"guest": true}'::jsonb WHERE id = $1`, [EDITED]);+ expect(marked(await readAsOwner(EDITED))).toEqual(MARKED);+ }, 60_000);++ test('a source in guest_sources whose config lost the guest key is marked on a remote read', async () => {+ await engine.executeRaw(`INSERT INTO guest_sources (source_id, writers, trust_ceiling) VALUES ($1, '{}'::text[], 'external_untrusted')`, [LISTED]);+ const [row] = await engine.executeRaw<{ guest: string | null }>(`SELECT config->>'guest' AS guest FROM sources WHERE id = $1`, [LISTED]);+ expect(row!.guest).toBeNull();+ expect(marked(await readAsOwner(LISTED))).toEqual(MARKED);+ }, 60_000);++ test('a failed guest-source check marks or refuses the read, never returns it bare', async () => {+ await engine.executeRaw(`UPDATE sources SET config = config || '{"guest": true}'::jsonb WHERE id = $1`, [FAILED]);+ const real = PGLiteEngine.prototype.executeRaw;+ (engine as any).executeRaw = function (this: PGLiteEngine, sql: string, params?: unknown[]) {+ if (/guest/.test(sql) && !/\bpages\b/.test(sql)) return Promise.reject(new Error('guest-source check unavailable'));+ return real.call(this, sql, params as never);+ };+ let out: Awaited<ReturnType<typeof readAsOwner>>;+ try { out = await readAsOwner(FAILED); } finally { delete (engine as any).executeRaw; }+ expect(out.isError || out.json?.origin === 'guest').toBe(true);+ }, 60_000);+});diff --git a/test/guest-notes-warning.test.ts b/test/guest-notes-warning.test.tsindex b40b4582f6..1ccc038109 100644--- a/test/guest-notes-warning.test.ts+++ b/test/guest-notes-warning.test.ts@@ -1,7 +1,7 @@/*** Guest notes, slice 3 (GBRA-504): every read of a guest page carries the guest warning, built from guest_marks.*- * Protects: a guest row's JSON gains origin "guest", the external tier and a guest object (sender_label, group,+ * Protects: a guest row's JSON gains origin "guest", the external tier and a guest object (sender, group,* audience_member, saved_at, promoted; the writer only for owner callers) matching its guest_marks row; text forms get* the warning line and the external-data envelope with origin="guest"; a remote quote fence names the guest; a guest* row with no readable mark reads "unattributed", never bare; a source made a guest source while a process runs is@@ -72,7 +72,7 @@ async function markRow(slug: string) {}async function expectedGuest(slug: string, owner: boolean) {const m = await markRow(slug);- return { sender_label: m.sender_label, group: m.group_slug, audience_member: m.audience_member, saved_at: new Date(m.saved_at).toISOString().slice(0, 10), promoted: false,+ return { sender: m.sender_label, group: m.group_slug, audience_member: m.audience_member, saved_at: new Date(m.saved_at).toISOString().slice(0, 10), promoted: false,...(owner ? { writer: m.writer_kind + ':' + m.writer_id } : {}) };}@@ -155,7 +155,7 @@ describe('guest warning on reads', () => {test('a guest row with no readable mark reads unattributed, never bare', async () => {const out = await call('owner', 'get_page', { slug: BARE });- expect({ origin: out.json.origin, guest: out.json.guest }).toEqual({ origin: 'guest', guest: { sender_label: null, group: null, audience_member: null, saved_at: null, promoted: false, unattributed: true } });+ expect({ origin: out.json.origin, guest: out.json.guest }).toEqual({ origin: 'guest', guest: { sender: null, group: null, audience_member: null, saved_at: null, promoted: false, unattributed: true } });expect(guestWarningLine(unattributedGuest())).toBe("[outside guest · unattributed · not the owner's words, not verified]");}, 60_000);@@ -184,7 +184,7 @@ describe('guest warning on reads', () => {const [chunk] = await engine.executeRaw<{ chunk_text: string }>('SELECT chunk_text FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index LIMIT 1', [id]);const rows = [{ slug: GUEST, page_id: id, source_id: SRC, title: 'A note from Bob', chunk_text: chunk!.chunk_text, score: 1 } as unknown as SearchResult];await stampPageTrust(engine, rows);- expect(rows[0]!.guest?.sender_label).toBe('Bob Example');+ expect(rows[0]!.guest?.sender).toBe('Bob Example');const seen: string[][] = [];await applyReranker(SENTINEL, rows, { enabled: true, topNIn: 5, timeoutMs: 1000, rerankerFn: async ({ documents }: { documents: string[] }) => { seen.push(documents); return documents.map((_, index) => ({ index, relevanceScore: 1 })); } } as never);expect(seen).toEqual([[chunk!.chunk_text]]);diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.tsindex 49e6aaa21d..c0e2fa015d 100644--- a/test/helpers/config-reader-registry.ts+++ b/test/helpers/config-reader-registry.ts@@ -30,7 +30,6 @@ export const INTERNAL_CONFIG_STATE: readonly InternalConfigState[] = [{ key: 'heal.audit', reason: 'the bounded self-heal audit log (last 200 rows, 30 days) that heal-audit.ts writes for each heal; doctor reads it to count a heal\'s consecutive failures, so a hand edit would hide an escalation' },{ key: 'access.serves_derived', reason: 'whether two or more members are enabled, kept by the v309 trigger on access_members (search/private-visibility.ts servesPolicyFrom); a hand edit would lie about whom the brain serves' },{ key: 'access.serves_since', reason: 'when the brain first served several people, set once by the v309 trigger and never cleared; it starts the unscoped-read grace (access/requester-scope.ts)' },- { key: 'guests.present', reason: 'sticky marker initGuestSource sets in the same transaction as the first guest source (guests/sources.ts); reads stamp guest notes only when it is set, so clearing it would show guest text without its warning' },{ key: 'access.restrictions_present', reason: 'sticky member-access marker a v282 trigger sets once a page names readers or a member exists (search/private-visibility.ts); clearing it would send remote reads down the unrestricted fast path' },{ key: '_internal.link_extraction_generation', reason: 'link-extraction watermark generation (link-extraction-watermark.ts)' },{ key: 'code.cluster_generation', reason: 'code-intel traversal cache generation counter' },