Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep the purge carry away from guest notes (GBRA-504)
garrytan26d4850bc506
diff --git a/behavior-changes.d/guest_notes_gbra504.md b/behavior-changes.d/guest_notes_gbra504.mdindex d23a91a516..ff49b2ba85 100644--- a/behavior-changes.d/guest_notes_gbra504.md+++ b/behavior-changes.d/guest_notes_gbra504.md@@ -1 +1 @@-New guest notes (GBRA-504): a brain can keep what people outside it say in a group chat with your agent, in a guest source that only a listed broker credential writes, once per note. Nothing changes until you run gbrain guests init: a brain without a guest source reads, writes and costs exactly as before, and no grant, privacy label or search scope changes on upgrade. With a guest source, every read that returns a guest note marks it as an outside guest's words (origin guest, trust tier external_untrusted, a guest object in JSON and a warning line in text), guest notes feed no facts, takes, timeline entries or links, and your own CLI cannot write there. You keep a note as your own page with gbrain guests promote <slug> (MCP promote_guest_note, owner only; anyone else is refused guest_promotion_owner_only), after which the broker can no longer delete it (guest_page_promoted). Your own tokens and OAuth clients read the guest source only once it is on their read list: gbrain guests grant-owner-clients previews that and --yes applies it, and gbrain doctor --only guest_source checks the whole setup.+New guest notes (GBRA-504): a brain can keep what people outside it say in a group chat with your agent, in a guest source that only a listed broker credential writes, once per note. Nothing changes until you run gbrain guests init: a brain without a guest source reads, writes and costs exactly as before, and no grant, privacy label or search scope changes on upgrade. With a guest source, every read that returns a guest note marks it as an outside guest's words (origin guest, trust tier external_untrusted, a guest object in JSON and a warning line in text), guest notes feed no facts, takes, timeline entries or links, and your own CLI cannot write there. You keep a note as your own page with gbrain guests promote <slug> (MCP promote_guest_note, owner only; anyone else is refused guest_promotion_owner_only), after which the broker can no longer delete it (guest_page_promoted). A guest writer can delete only the guest notes it saved itself. Your own tokens and OAuth clients read the guest source only once it is on their read list: gbrain guests grant-owner-clients previews that and --yes applies it, and gbrain doctor --only guest_source checks the whole setup.diff --git a/changelog.d/gbra504-guest-notes-4-promotion.md b/changelog.d/gbra504-guest-notes-4-promotion.mdindex 14e0a9ddbc..2330b279b7 100644--- a/changelog.d/gbra504-guest-notes-4-promotion.md+++ b/changelog.d/gbra504-guest-notes-4-promotion.md@@ -1,6 +1,6 @@**Guest notes: a group member's note is saved, marked as a guest's, warned about on every read, and becomes your own page only when you say so.** People in a group chat with your agent sometimes say things worth keeping. A guest source keeps those notes apart from your own pages, with a record of who said them. Nothing changes until you run `gbrain guests init`: a brain without a guest source reads, writes and costs exactly as before, and no grant, privacy label or search scope changes on upgrade.-A guest source has four rules the database enforces, whatever program writes. Only writers on the source's list (an OAuth client or legacy token, for example the broker your agent's host runs) may create a page there or change its text, and only as a new page; your own CLI, `gbrain import`, sync, `remember`, `add_link` and `put_raw_data` are refused `source_writer_restricted`, while delete, restore and purge from your CLI still work. No page there is ever stored above the `external_untrusted` trust tier, even after an owner rewrite or a trust confirmation. Guest notes feed no facts, takes, timeline entries or links (`guest_page_immutable`). And a guest source is database-only, so attaching a local path is refused. `gbrain guests init` also refuses an existing source that already holds pages, so your own pages never turn into guest notes.+A guest source has four rules the database enforces, whatever program writes. Only writers on the source's list (an OAuth client or legacy token, for example the broker your agent's host runs) may create a page there or change its text, and only as a new page; your own CLI, `gbrain import`, sync, `remember`, `add_link` and `put_raw_data` are refused `source_writer_restricted`, while delete, restore and purge from your CLI still work. No page there is ever stored above the `external_untrusted` trust tier, even after an owner rewrite or a trust confirmation. Guest notes feed no facts, takes, timeline entries or links (`guest_page_immutable`). And a guest source is database-only, so attaching a local path is refused. `gbrain guests init` also refuses an existing source that already holds pages, deleted pages not yet purged included, so your own pages never turn into guest notes.When the writer saves a note, gbrain records who it was saved for, which group, when and which client sent it, in its own table that no later write can edit and that never comes from the page text. Every read that returns a guest note (search, query, get, list, find, backlinks, timeline, think and the rest) marks it as an outside guest's words: `origin: "guest"` and a `guest` object in JSON, and a warning line plus the external-data envelope in text. A contract test fails if any operation, present or future, returns a guest row without the mark.@@ -18,6 +18,7 @@ You keep a note as your own page with `gbrain guests promote <slug>` (MCP `promo- The guest-notes schema migration (`src/core/schema-migrations/v<NNN>-guest-notes.ts`; `GUEST_NOTES_MIGRATION` in `src/core/guests/migration.ts` names its number): the `guest_sources`, `guest_marks` and `guest_promotions` tables under row-level security, the per-source trust ceiling in the trust trigger, and the writer backstop trigger.- `src/core/guests/`: admission (writer list, new-page-only, allowed frontmatter and readers), the mark and its warning, derived-row refusals, promotion, owner credentials and source setup.- Read paths (`src/cli/page-render.ts`, `src/cli/search-row-format.ts`, `src/cli/guest-lines.ts`, `src/core/access/page-items.ts`, `src/core/think/index.ts`, `src/core/search/transcript-quote.ts`) carry the guest mark and warning.+- A guest writer can delete only the guest notes it saved itself; deleting a note another writer saved is refused `permission_denied`.- Stale extraction, `propose_takes` (scoped or not) and the cycle's fact, atom and enrichment phases leave guest pages out.- Reads on a brain whose schema is still behind that migration keep working, because the guest check falls back to the source config when the `guest_sources` table is missing.- Goldens regenerated: `test/fixtures/goldens/sql-text/pages.json` (stale-extraction query excludes guest pages), `test/fixtures/goldens/exports/types.json` (guest types and error codes), the doctor goldens (the `guest_source` row and the three new tables under row-level security) and `test/fixtures/goldens/cli/tools-json.json` (the new operation).diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.mdindex 3e871a8138..57c3fb25fe 100644--- a/docs/guides/guest-notes.md+++ b/docs/guides/guest-notes.md@@ -65,7 +65,9 @@ The source is called `guests` unless you pass `--source <id>`. Running initagain on a guest source adds the new writers and keeps the old ones. If thesource exists already, it must have no local path and hold no pages; init thenmarks it as a guest source. A source that already holds pages is refused, because-every page in a guest source would then read as a guest's words.+every page in a guest source would then read as a guest's words. Deleted pages+that haven't been purged yet count too, because restoring one would bring it back+into the guest source.## Change who may writediff --git a/src/commands/guests.ts b/src/commands/guests.tsindex 673c68da95..cce301ccad 100644--- a/src/commands/guests.ts+++ b/src/commands/guests.ts@@ -83,9 +83,9 @@ async function runInit(engine: BrainEngine, rest: string[]): Promise<void> {process.exit(2);}if (plan.exists && !plan.guest) {- const [held] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1 AND deleted_at IS NULL', [sourceId]);+ const [held] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1', [sourceId]);if (Number(held?.n ?? 0) > 0) {- console.error(`Source "${sourceId}" already holds ${held!.n} page(s). Every page in a guest source reads as an outside guest's words and only listed writers can change it, so gbrain will not make this one a guest source. Pick another name with --source.`);+ console.error(`Source "${sourceId}" already holds ${held!.n} page(s), counting deleted pages not yet purged (a restore would bring them back). Every page in a guest source reads as an outside guest's words and only listed writers can change it, so gbrain will not make this one a guest source. Pick another name with --source.`);process.exit(2);}}diff --git a/src/core/guests/derived.ts b/src/core/guests/derived.tsindex 197b2e1ee9..46e778d703 100644--- a/src/core/guests/derived.ts+++ b/src/core/guests/derived.ts@@ -48,7 +48,7 @@ export const GUEST_DERIVED_PRODUCERS = {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.' },+ purge: { guest: 'none', reason: 'Purges tombstones; the owner may delete guest pages. Its origin carry (repair/origin-carry.ts) labels only pages tied to an origin by derived_from, source_slug, event or a provenance link: a guest page carries none of those keys and a guest source holds no links and no owner page, so it never labels a guest page.' },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'] },diff --git a/test/guest-notes-origin-carry.test.ts b/test/guest-notes-origin-carry.test.tsnew file mode 100644index 0000000000..a1bae8cf53--- /dev/null+++ b/test/guest-notes-origin-carry.test.ts@@ -0,0 +1,119 @@+/**+ * Guest notes (GBRA-504) against the origin carry (GST-2689): before a deleted page's row goes, the purge labels+ * private every page that page alone kept private, through the label door.+ *+ * 1. Protects: the carry never labels a guest note, and the guest gate never refuses one of its writes, so no origin+ * is parked for good. A guest page's frontmatter allowlist has none of the keys that tie a page to an origin, a+ * guest write naming derived_from is refused, and the owner's purge of a private origin labels its owner-source+ * dependent while every guest note keeps its revision. The owner's explicit and retention purges of a guest note+ * remove it with no hold and no park. The one way a guest source held a page the carry would label was a source made+ * a guest source while it held deleted pages, then restored; test/guests-cli.test.ts pins init refusing that.+ * 2. Fails when: a tie key joins the allowlist, a guest note changes during a carry, or a guest note's purge is held or parked.+ * 3. Real seams: legacy tokens on the guest source's writer list through MCP dispatch, local dispatch for the owner, on+ * a repo-less PGLite brain.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+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 { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { addMember, bindCredential } from '../src/core/access/members.ts';+import { setOwner } from '../src/core/access/owner.ts';+import { changeGuestWriters, initGuestSource } from '../src/core/guests/sources.ts';+import { GUEST_FRONTMATTER_KEYS } from '../src/core/guests/admission.ts';+import { readDerivedOriginParks } from '../src/core/persistence/derived-origin-hold.ts';+import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.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;+let token = '';+const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+const parse = (text: string) => { try { return JSON.parse(text) as Record<string, unknown>; } catch { return {} as Record<string, unknown>; } };+const note = (extra: string[] = [], body = 'Bob says hello.') => ['---', 'type: note', 'title: A note from Bob', 'readable_by: [' + OWNER + ', bob-example]', 'guest_group: team-a',+ 'guest_sender: Bob Example', 'saved_at: 2026-11-13T10:00:00Z', ...extra, '---', '# A note from Bob', '', body].join('\n');++async function guest(op: string, params: Record<string, unknown>) {+ const auth = await provider().verifyAccessToken(token) as unknown as AuthInfo;+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'],+ onBehalfOf: { header: 'bob-example' }, guest: { requestMeta: { guest: META } } });+ const json = parse(out.content.map(c => c.text).join('\n'));+ return { isError: out.isError === true, 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 });+ return { isError: out.isError === true, json: parse(out.content.map(c => c.text).join('\n')) };+}+const snapshot = (slug: string, sourceId = SRC) => engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+const revisionOf = async (slug: string, sourceId = SRC) => (await snapshot(slug, sourceId))!.revision;+const rowCount = async (slug: string, sourceId = SRC) => (await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]))[0]!.n;+const slugOf = () => 'notes/guest-' + randomUUID().slice(0, 8);+async function savedGuestNote(): Promise<string> {+ const slug = slugOf();+ const saved = await guest('put_page', { slug, content: note([], `Bob says hello about ${slug}.`) });+ expect({ isError: saved.isError, code: saved.code }).toEqual({ isError: false, code: undefined });+ return slug;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const id of [OWNER, 'bob-example']) await addMember(engine, id);+ 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 minted = await mintLegacyToken(engine, { name: 'broker-a', scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC] });+ token = minted.token;+ await bindCredential(engine, { kind: 'token', id: minted.id }, { mayActFor: ['member:bob-example', 'guest'] });+ await readsUnscopedOnPurpose(engine, minted.id);+ await changeGuestWriters(engine, SRC, { add: ['legacy_token:' + minted.id] });+}, 240_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); }, 60_000);++describe('the origin carry and guest notes (pglite, repo-less)', () => {+ test('a guest page can carry none of the keys that tie a page to an origin', async () => {+ expect(GUEST_FRONTMATTER_KEYS.filter(key => ['derived_from', 'source_slug', 'event', 'synthesized_by'].includes(key))).toEqual([]);+ const refused = await guest('put_page', { slug: slugOf(), content: note(['derived_from: notes/owner-origin.md']) });+ expect({ isError: refused.isError, code: refused.code }).toEqual({ isError: true, code: 'guest_frontmatter_refused' });+ }, 60_000);++ test("the owner's purge of a private origin labels its derived page and leaves every guest note unchanged", async () => {+ const kept = await savedGuestNote();+ const before = await revisionOf(kept);+ expect((await local('put_page', { slug: 'notes/owner-origin', content: '---\ntype: note\nvisibility: private\n---\n# Origin\n\nPrivate plan.' }, PLAIN)).isError).toBe(false);+ expect((await local('put_page', { slug: 'notes/owner-digest', content: '---\ntype: note\nderived_from: notes/owner-origin.md\n---\n# Digest\n\nA digest.' }, PLAIN)).isError).toBe(false);+ const purge = await local('delete_page', { slug: 'notes/owner-origin', purge: true, expected_revision: await revisionOf('notes/owner-origin', PLAIN) }, PLAIN);+ expect({ isError: purge.isError, status: purge.json.status, held: purge.json.purge_held }).toEqual({ isError: false, status: 'purged', held: undefined });+ expect((await snapshot('notes/owner-digest', PLAIN))!.page.frontmatter.visibility).toBe('private');+ expect(await revisionOf(kept)).toBe(before);+ expect(await readDerivedOriginParks(engine)).toEqual([]);+ }, 120_000);++ test("the owner's explicit purge of a guest note removes it with no hold and no park", async () => {+ const slug = await savedGuestNote();+ const purge = await local('delete_page', { slug, purge: true, expected_revision: await revisionOf(slug) });+ expect({ isError: purge.isError, status: purge.json.status, held: purge.json.purge_held }).toEqual({ isError: false, status: 'purged', held: undefined });+ expect(await rowCount(slug)).toBe(0);+ expect(await readDerivedOriginParks(engine)).toEqual([]);+ }, 120_000);++ test('the retention purge of an expired guest note removes it with no park', async () => {+ const slug = await savedGuestNote();+ expect((await local('delete_page', { slug, expected_revision: await revisionOf(slug) })).isError).toBe(false);+ await engine.executeRaw("UPDATE pages SET deleted_at = now() - interval '200 hours' WHERE source_id = $1 AND slug = $2", [SRC, slug]);+ const run = await purgeDeletedPagesCoordinated(engine, 72);+ expect({ purged: run.slugs.includes(slug), blocked: run.blocked.filter(b => b.slug === slug) }).toEqual({ purged: true, blocked: [] });+ expect(await rowCount(slug)).toBe(0);+ expect(await readDerivedOriginParks(engine)).toEqual([]);+ }, 120_000);+});diff --git a/test/guests-cli.test.ts b/test/guests-cli.test.tsindex dfbf1b588f..6b1c189d4d 100644--- a/test/guests-cli.test.ts+++ b/test/guests-cli.test.ts@@ -75,6 +75,15 @@ describe('gbrain guests init', () => {expect(configOf((await sourceRow('source-a'))!.config).guest).toBeUndefined();});+ test('refuses an existing source whose only page is deleted but not yet purged', async () => {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', ['source-a']);+ await engine.putPage('notes/owner-a', { title: 'Owner', type: 'note' as never, compiled_truth: 'Mine.', frontmatter: {}, timeline: '' }, { sourceId: 'source-a' } as never);+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE source_id = 'source-a'");+ await run(() => runGuests(engine, ['init', '--source', 'source-a', '--yes']));+ expect({ exitCode: exitCode as number | null, said: err.join('\n').includes('already holds 1 page') }).toEqual({ exitCode: 2, said: true });+ expect(await guestRow('source-a')).toBeUndefined();+ });+test('previews by default and writes nothing', async () => {await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a']));expect(exitCode).toBeNull();