Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(access): unrestricted brains test only the derived readers column (GBRA-218)
garrytanf1c39714f067
diff --git a/scripts/bench-member-access.ts b/scripts/bench-member-access.tsindex 168e7d1813..098f55aae6 100644--- a/scripts/bench-member-access.ts+++ b/scripts/bench-member-access.ts@@ -75,11 +75,14 @@ async function runCell(share: number) {if (share > 0 && !hasMembers) { await engine.disconnect(); return null; }await seed(engine, share);- if (hasMembers) await engine.executeRaw("INSERT INTO access_members (id) VALUES ('alice-example') ON CONFLICT DO NOTHING");+ // Share 0 is a brain with no restriction at all (no member, no readers), the case nearly every brain is in; its+ // "member" token is a second unbound token. Restricted shares create the member and bind it.+ const bindMember = hasMembers && share > 0;+ if (bindMember) await engine.executeRaw("INSERT INTO access_members (id) VALUES ('alice-example') ON CONFLICT DO NOTHING");const mint = async (name: string) => mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });const unbound = await mint('bench-unbound');const alice = await mint('bench-alice');- if (hasMembers) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [alice.id, 'alice-example']);+ if (bindMember) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [alice.id, 'alice-example']);const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });async function remote(token: string, params: Record<string, unknown>) {diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex 045bb2c70c..1a62a9e8a1 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -76,6 +76,7 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | uprivateReadableSources: privateSources ?? [],hidePrivate: !relaxed,applyRemoteReadPolicy: false,+ restricted,};}diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 928136fbd2..fd5083ae84 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -69,6 +69,7 @@ function privacyPartSql(pageAlias: string): string {* embedded as literals; anything else empties it (fail closed).*/export function accessAllowedSql(pageAlias: string, identity: readonly string[]): string {+ if (!currentCallerAccess().restricted) return `(${pageAlias}.page_readers IS NULL)`;return `(${readersAllowedSql(pageAlias, identity)} AND ${originAllowedSql(pageAlias)})`;}@@ -137,7 +138,17 @@ export function privatePagesFilterFragmentFast(pageAlias: string): string {* no-grant floor, federation, an OAuth client's bound source or a request's* `source_ids`); empty for writes;* - hidePrivate: false only when an operator relaxed privacy for remote reads- * (GBRAIN_REMOTE_PRIVATE_PAGES=1 or search.remote_private_pages=visible).+ * (GBRAIN_REMOTE_PRIVATE_PAGES=1 or search.remote_private_pages=visible);+ * - restricted: false only inside a remote request on a brain whose config+ * access.restrictions_present was unset when the request began. Then no+ * page named readers at that moment and none predates the migration (v274+ * sets the flag when one does), so every readers value is in the derived+ * column: accessAllowedSql tests only page_readers IS NULL (live, so a page+ * gaining readers mid-request is still hidden, since the trigger fills the+ * column in that write) and skips lineage, member matching and the+ * frontmatter test, whose per-row JSONB read cost keyword search about 3%.+ * The flag is sticky and set in the same transaction as the first page+ * that names readers.* Outside any record (local CLI, jobs, cycles) the identity is empty, no* source is private-readable and hidePrivate follows the process's hatch* state, so caller-aware fragments still fail closed on restricted pages.@@ -147,12 +158,13 @@ export interface CallerAccess {privateReadableSources: readonly string[];hidePrivate: boolean;applyRemoteReadPolicy: boolean;+ restricted: boolean;}const callerAccessStore = new AsyncLocalStorage<CallerAccess>();/** The current read's caller-access record (see CallerAccess). */export function currentCallerAccess(): CallerAccess {- return callerAccessStore.getStore() ?? { identity: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false };+ return callerAccessStore.getStore() ?? { identity: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false, restricted: true };}/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */@@ -165,6 +177,7 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):privateReadableSources: sources.length && sources.every(isValidSourceId) ? Object.freeze([...new Set(sources)]) : Object.freeze([]),hidePrivate: access.hidePrivate ?? base.hidePrivate,applyRemoteReadPolicy: access.applyRemoteReadPolicy ?? base.applyRemoteReadPolicy,+ restricted: access.restricted ?? base.restricted,}), fn);}diff --git a/test/access-unrestricted-fast-path.test.ts b/test/access-unrestricted-fast-path.test.tsnew file mode 100644index 0000000000..da83bf826c--- /dev/null+++ b/test/access-unrestricted-fast-path.test.ts@@ -0,0 +1,63 @@+/**+ * GBRA-218: the unrestricted fast path. On a brain whose config+ * access.restrictions_present is unset, a remote read tests only each row's+ * own derived readers column (accessAllowedSql's short form). This file proves the short form+ * never shows a page that names readers: the trigger flips the flag in the+ * page's own transaction, and even with the flag forced back off the row test+ * alone still hides the page. Repo-less PGLite, keyless.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { accessAllowedSql, withCallerAccess } from '../src/core/search/private-visibility.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';++const SRC = 'fast-src';+let engine: PGLiteEngine;+let token = '';++async function seen(slug: string, canary: string): Promise<boolean> {+ const auth = await new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) })+ .verifyAccessToken(token) as unknown as AuthInfo;+ const read = async (op: string, params: Record<string, unknown>) => (await dispatchToolCall(engine, op, params, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'] }))+ .content.map(c => c.text).join('\n');+ // get_page echoes a missing slug in its not-found error, so only its content counts.+ return (await read('search', { query: canary, match: 'keyword', fields: 'full' })).includes(canary)+ || (await read('get_page', { slug })).includes(canary)+ || (await read('list_pages', { limit: 50 })).includes(slug);+}++describe('unrestricted fast path (pglite, repo-less)', () => {+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [SRC]);+ await importFromContent(engine, 'notes/open-page', '---\ntype: note\ntitle: Open\n---\nCanary fastopenpage.', { sourceId: SRC, noEmbed: true });+ token = (await mintLegacyToken(engine, { name: 'unbound', scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] })).token;+ }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ test('the short form is used only when the request record says unrestricted, and tests the row readers', () => {+ const full = withCallerAccess({ restricted: true }, () => accessAllowedSql('p', []));+ const short = withCallerAccess({ restricted: false }, () => accessAllowedSql('p', ['member:alice-example']));+ expect(full).toContain('gbrain_access_origin_restricted');+ expect(short).not.toContain('gbrain_access_origin_restricted');+ expect(short).toBe('(p.page_readers IS NULL)');+ expect(accessAllowedSql('p', [])).toContain('gbrain_access_origin_restricted');+ });++ test('a page that gains readers is hidden on the next request, and stays hidden with the flag forced off', async () => {+ expect((await engine.executeRaw("SELECT 1 FROM config WHERE key = 'access.restrictions_present' AND value = '1'")).length).toBe(0);+ expect(await seen('notes/open-page', 'fastopenpage')).toBe(true);+ await importFromContent(engine, 'notes/open-page', '---\ntype: note\ntitle: Open\nreadable_by: [alice-example]\n---\nCanary fastopenpage.', { sourceId: SRC, noEmbed: true });+ expect((await engine.executeRaw("SELECT 1 FROM config WHERE key = 'access.restrictions_present' AND value = '1'")).length).toBe(1);+ expect(await seen('notes/open-page', 'fastopenpage')).toBe(false);+ await engine.executeRaw("DELETE FROM config WHERE key = 'access.restrictions_present'");+ expect(await seen('notes/open-page', 'fastopenpage')).toBe(false);+ }, 120_000);+});