Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep room marks honest under an enforced member, a paged page and output redaction
garrytand0ce05cccede
diff --git a/src/cli/main.ts b/src/cli/main.tsindex f9ef6ab611..4ab2035d49 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -743,7 +743,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C// path's return value so renderers see the same shape they'd see on the// routed path. Date → ISO string; bigint → string (postgres.js shape);// Buffer → object. Microsecond-cost; eliminates a whole drift bug class.- const { result, stderr: noticeText } = cliOpts.room === undefined ? applyCliOpNotices(normalizeLocalResult(rawResult), params.json === true, { op: op.name, retrieval: lastRetrievalMeta }) : await (await import('./room.ts')).directWithRoom(engine, op.name, normalizeLocalResult(rawResult), cliOpts.room, params.json === true, { sourceId: ctx.sourceId, run: asPreview.run, retrieval: lastRetrievalMeta }); // GBRA-498: --room marks it+ const { result, stderr: noticeText } = cliOpts.room === undefined ? applyCliOpNotices(normalizeLocalResult(rawResult), params.json === true, { op: op.name, retrieval: lastRetrievalMeta }) : await (await import('./room.ts')).directWithRoom(engine, op.name, normalizeLocalResult(rawResult), cliOpts.room, params.json === true, { sourceId: ctx.sourceId, run: asPreview.run, retrieval: lastRetrievalMeta, enforced: !!enforcedClass }); // GBRA-498: --room marks itif (enforced && await enforced.namesHiddenPage(engine, command, result)) {process.stderr.write(enforced.WITHHELD_LINE(command));return;@@ -843,7 +843,7 @@ async function runThinClientRouted(await printPagedPage(async p => unpackToolResult(await callRemoteTool(cfg, 'get_page', p, { timeoutMs, signal: sigintController.signal })), params, writeStdoutFinal);return null;}));- if (raw === null) return;+ if (raw === null) { if (cliOpts.room !== undefined) process.stderr.write((await import('./room.ts')).roomNotMarkedLine(op.cliHints?.name ?? op.name)); return; } // GBRA-498: a paged page carries no marks// T15/FOV-1: lift the server's retrieval meta off the envelope before// unpacking (old servers lack _meta — capture is simply skipped).const envelopeMeta = extractResponseMeta(raw);diff --git a/src/cli/room.ts b/src/cli/room.tsindex deb02e432e..8a82c05d95 100644--- a/src/cli/room.ts+++ b/src/cli/room.ts@@ -72,8 +72,10 @@ export function roomSummaryLine(meta: RoomMeta): string {/** The direct path: marks the result, then the notices and stamp as applyCliOpNotices renders them, then the summary. */export async function directWithRoom(engine: BrainEngine, op: string, result: unknown, room: string, json: boolean,- opts: { sourceId: string; run: <T>(fn: () => Promise<T>) => Promise<T>; retrieval: Record<string, unknown> | null }): Promise<{ result: unknown; stderr?: string }> {- const marked = await markCliResult(engine, op, result, room, { sourceId: opts.sourceId, run: opts.run });+ opts: { sourceId: string; run: <T>(fn: () => Promise<T>) => Promise<T>; retrieval: Record<string, unknown> | null; enforced?: boolean }): Promise<{ result: unknown; stderr?: string }> {+ // An enforced member (GBRAIN_ENFORCED_MEMBER) is not the trusted owner: it may not ask what another room reads here.+ const marked = await markCliResult(engine, op, result, room, { sourceId: opts.sourceId, run: opts.run,+ ...(opts.enforced ? { unavailable: { reason: 'not_permitted' as const, detail: 'a CLI under GBRAIN_ENFORCED_MEMBER marks no room; ask through the connection bound to that member' } } : {}) });const out = applyCliOpNotices(cliRoomResult(marked, json), json, { op, retrieval: opts.retrieval });return { result: out.result, stderr: (out.stderr ?? '') + (json ? '' : roomSummaryLine(marked.meta)) };}diff --git a/src/core/access/room.ts b/src/core/access/room.tsindex 94912781c5..0eab3a3429 100644--- a/src/core/access/room.ts+++ b/src/core/access/room.ts@@ -419,7 +419,7 @@ async function assessRoomUnguarded(engine: BrainEngine | null, input: RoomInput)const gates = s.ref ? [s.ref, ...(s.also ?? [])].map(judge) : [];const access: RoomAccess = unavailable ? { readable: 'unknown', reason: unavailable.reason }: !s.ref ? { readable: 'unknown', reason: 'not_identified' }- : gates.find(a => a.readable === false) ?? (s.unknown ? { readable: 'unknown', reason: s.unknown } : undefined) ?? gates.find(a => a.readable === false) ?? gates.find(a => a.readable === 'unknown') ?? { readable: true };+ : gates.find(a => a.readable === false) ?? (s.unknown ? { readable: 'unknown', reason: s.unknown } : undefined) ?? gates.find(a => a.readable === 'unknown') ?? { readable: true };s.holder[ROOM_ACCESS_KEY] = access;meta.counts.items++;if (access.readable === true) { meta.counts.readable++; continue; }diff --git a/src/core/search/output-redaction.ts b/src/core/search/output-redaction.tsindex 01ae1d9069..648d61ca9f 100644--- a/src/core/search/output-redaction.ts+++ b/src/core/search/output-redaction.ts@@ -95,6 +95,11 @@ export function withOutputRedaction(op: Pick<Operation, 'handler' | 'outputRedacconst localVerbatim = policy === 'retrieval' ? [] : policy.retrieval.localVerbatim;return async (ctx, params) => {const result = await handler(ctx, params);- return redactRetrievalOutput([result], {}, { uncapped: true, verbatim: ctx.remote === false ? localVerbatim : [] }).results[0];+ const redacted = redactRetrievalOutput([result], {}, { uncapped: true, verbatim: ctx.remote === false ? localVerbatim : [] }).results[0];+ // In-process side channels (symbol keys, e.g. a think answer's room evidence) survive the redaction copy; no response carries them.+ if (result && typeof result === 'object' && redacted && typeof redacted === 'object') {+ for (const key of Object.getOwnPropertySymbols(result)) (redacted as Record<symbol, unknown>)[key] = (result as Record<symbol, unknown>)[key];+ }+ return redacted;};}diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 79c21e9ec8..a8579abcfb 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -906,6 +906,9 @@ export async function runThink(synthesisOk: false, // #1698: no LLM ran — never persist thissynthesis_status: modelProblem ? 'model_unusable' : 'no_llm',...(stubExtractive ? { extractive: stubExtractive } : {}),+ // GBRA-498: the extractive digest quotes the gathered pages, so a room marks this answer from them too.+ taint_refs: [...gather.pages.map(pg => ({ table: 'pages' as const, sourceId: pg.source_id ?? 'default', slug: pg.slug })),+ ...gather.takes.map(t => ({ table: 'takes' as const, id: t.take_id }))],usage: null, // [E2] no LLM ran — no accounting...windowMeta,diagnostics: {diff --git a/test/access-room-cli.serial.test.ts b/test/access-room-cli.serial.test.tsindex 472d398472..9d15452bf9 100644--- a/test/access-room-cli.serial.test.ts+++ b/test/access-room-cli.serial.test.ts@@ -22,11 +22,11 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { createPersistenceIpcProvider } from '../src/core/persistence/provider.ts';-import { persistenceSocketPathForConfig, startPersistenceIpcServer } from '../src/core/persistence/ipc.ts';+import { persistenceSocketPathForConfig, requestPersistenceOperation, startPersistenceIpcServer } from '../src/core/persistence/ipc.ts';import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';import { addMember } from '../src/core/access/members.ts';import { clearOwner, setOwner } from '../src/core/access/owner.ts';-import { delegatedRoom, routedRoom } from '../src/cli/room.ts';+import { delegatedRoom, roomSummaryLine, routedRoom } from '../src/cli/room.ts';import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';import { withEnv } from './helpers/with-env.ts';@@ -41,8 +41,8 @@ function env(home: string): Record<string, string> {return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_NO_BANNER: '1' };}-async function cli(root: string, home: string, args: string[], stdin?: string) {- const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: env(home), stdin: stdin === undefined ? 'ignore' : new Blob([stdin]), stdout: 'pipe', stderr: 'pipe' });+async function cli(root: string, home: string, args: string[], stdin?: string, extra: Record<string, string> = {}) {+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: { ...env(home), ...extra }, stdin: stdin === undefined ? 'ignore' : new Blob([stdin]), stdout: 'pipe', stderr: 'pipe' });const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);return { stdout, stderr, exitCode };}@@ -58,7 +58,7 @@ const marks = (items: Array<{ slug?: string; room_access?: unknown }>) => Objectdescribe('--room on the direct path (repo-less PGLite)', () => {let root: string, home: string, db: string;- const run = (args: string[], stdin?: string) => cli(root, home, args, stdin);+ const run = (args: string[], stdin?: string, extra?: Record<string, string>) => cli(root, home, args, stdin, extra);async function withBrain<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {const config = { engine: 'pglite' as const, database_path: db };const engine = await createEngine(config);@@ -135,6 +135,27 @@ describe('--room on the direct path (repo-less PGLite)', () => {}, 180_000);});+describe('--room under an enforced member', () => {+ test('a CLI held to one member may not ask what another room reads: every item unknown (not_permitted), the read unchanged', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gb-room-enforced-'));+ const home = join(root, 'home'), db = join(root, 'db');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: db }));+ const config = { engine: 'pglite' as const, database_path: db };+ const engine = await createEngine(config);+ await engine.connect(config);+ try { await engine.initSchema(); await seed(engine); } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ try {+ const out = await cli(root, home, ['list', '--json', '--room', 'owner-example'], undefined, { GBRAIN_ENFORCED_MEMBER: 'alice-example' });+ expect(out.exitCode).toBe(0);+ const doc = JSON.parse(out.stdout) as { results: Array<Record<string, unknown>>; _meta: { room: Record<string, unknown> } };+ expect(Object.keys(marks(doc.results))).toEqual([OPEN]);+ expect(Object.values(marks(doc.results))).toEqual([{ readable: 'unknown', reason: 'not_permitted' }]);+ expect(doc._meta.room).toMatchObject({ complete: false, unavailable: 'not_permitted' });+ } finally { rmSync(root, { recursive: true, force: true }); }+ }, 180_000);+});+describe('--room through a live PGLite owner', () => {let dir: string;let engine: PGLiteEngine;@@ -184,4 +205,29 @@ describe('--room fallbacks for a brain that cannot mark', () => {const fromHost = await routedRoom('list_pages', [{ slug: OPEN, room_access: { readable: true } }], marked, 'alice-example');expect({ local: fromHost.local, meta: fromHost.marked.meta }).toEqual({ local: false, meta: marked as never });});++ test('the summary lists at most 20 items, then how many more', () => {+ const above = Array.from({ length: 23 }, (_, i) => ({ source_id: 'default', slug: 'notes/p' + i, reason: 'readers' }));+ const text = roomSummaryLine({ principals: ['member:alice-example'], declared_by: 'harness', complete: true, counts: { items: 23, readable: 0, above: 23, unknown: 0 }, by_reason: { readers: 23 }, above });+ expect(text.trimEnd().split('\n').length).toBe(22);+ expect(text).toContain('and 3 more');+ });+});++describe('the owner socket accepts a room only as a bounded string', () => {+ const request = (extra: Record<string, unknown>) => ({ version: 1, kind: 'operation', brain_id: '00000000-0000-4000-8000-000000000001', operation: 'get_page', params: { slug: OPEN },+ registration: { id: '00000000-0000-4000-8000-000000000002', credential: 'a'.repeat(64), lane: 'cli' }, routing: { source: null, cwd: '/tmp' }, ...extra });+ // A valid envelope reaches the (absent) socket and fails there; an invalid one is refused before anything is sent.+ const accepted = async (extra: Record<string, unknown>) => {+ try { await requestPersistenceOperation(join(tmpdir(), 'gb-room-no-socket-' + process.pid), request(extra) as never, 500); return 'sent'; }+ catch (e) { return String((e as { code?: unknown }).code) === 'invalid_params' ? 'refused' : 'sent'; }+ };+ test('room alone or beside write_wait_ms passes; a non-string, an over-long room or an unknown key does not', async () => {+ expect(await accepted({})).toBe('sent');+ expect(await accepted({ room: 'alice-example' })).toBe('sent');+ expect(await accepted({ room: 'alice-example', write_wait_ms: 10 })).toBe('sent');+ expect(await accepted({ room: ['alice-example'] })).toBe('refused');+ expect(await accepted({ room: 'a'.repeat(4097) })).toBe('refused');+ expect(await accepted({ other: 1 })).toBe('refused');+ });});diff --git a/test/access-room.test.ts b/test/access-room.test.tsindex 4b442e374f..48e91b3481 100644--- a/test/access-room.test.ts+++ b/test/access-room.test.ts@@ -316,7 +316,8 @@ for (const kind of testBackends()) {const out = await call('owner', 'think', { question: 'harbor ledger planning' }, { room: { header: 'alice-example' } });expect(out.isError).toBe(false);const access = (out.json as { room_access?: { readable: unknown; reason?: string } }).room_access;- expect(access).toBeDefined();+ // Marked from the evidence the synthesis retrieved: with none kept, the mark would be not_identified.+ expect(access?.reason).not.toBe('not_identified');expect(out.meta?.room).toMatchObject({ counts: { items: 1 } });expect(out.text).not.toContain('taint_refs');}, 120_000);