Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(embedded): examples/embedded-two-brains.ts acceptance example, run by a test (B3a H)
garrytan5b6a2ff50597
diff --git a/examples/embedded-two-brains.ts b/examples/embedded-two-brains.tsnew file mode 100644index 0000000000..7540029791--- /dev/null+++ b/examples/embedded-two-brains.ts@@ -0,0 +1,78 @@+/**+ * Two brains in one process, opened from settings (docs/ENGINES.md "Opening an engine from settings").+ *+ * Each brain gets its own database, host identity and AI provider. Here the providers are two fake+ * OpenAI-compatible embedding servers on 127.0.0.1, so nothing leaves the machine and no key is real. The example+ * puts a page in each brain, searches each, closes both, and exits 1 if either provider saw the other brain's key+ * or a brain found the other brain's page. Only package exports are used.+ *+ * bun examples/embedded-two-brains.ts+ */+import { randomUUID } from 'node:crypto';+import { openEngine } from 'gbrain/engine-open';+import { importFromContent } from 'gbrain/import-file';+import { hybridSearch } from 'gbrain/search/hybrid';++const DIMENSIONS = 1536;++/** A fake embedding provider that records the bearer of every request it gets. */+function fakeProvider(): { url: string; bearers: Set<string>; stop: () => void } {+ const bearers = new Set<string>();+ const server = Bun.serve({+ hostname: '127.0.0.1',+ port: 0,+ async fetch(request) {+ bearers.add(request.headers.get('authorization') ?? '');+ const { input } = await request.json() as { input: string[] };+ const data = input.map((text, index) => ({+ object: 'embedding', index, embedding: Array.from({ length: DIMENSIONS }, (_, i) => ((text.length + i) % 13) / 13 + 0.01),+ }));+ return Response.json({ object: 'list', data, model: 'text-embedding-3-small', usage: { prompt_tokens: input.length, total_tokens: input.length } });+ },+ });+ return { url: `http://127.0.0.1:${server.port}/v1`, bearers, stop: () => server.stop(true) };+}++async function openBrain(name: string, apiKey: string, baseUrl: string) {+ const engine = await openEngine({+ embedded_core: true,+ engine: 'pglite',+ database: {},+ host: { id: randomUUID() },+ embedding: { model: 'openai:text-embedding-3-small', dimensions: DIMENSIONS },+ ai: { providers: { openai: { apiKey, baseUrl } } },+ });+ await engine.initSchema();+ await importFromContent(engine, `notes/${name}`, `---\ntitle: ${name}\n---\nThe quarterly plan for ${name} lives here.\n`);+ return engine;+}++const providerA = fakeProvider();+const providerB = fakeProvider();+const keyA = `sk-brain-a-${randomUUID()}`;+const keyB = `sk-brain-b-${randomUUID()}`;+const problems: string[] = [];+try {+ const brainA = await openBrain('brain-a', keyA, providerA.url);+ const brainB = await openBrain('brain-b', keyB, providerB.url);+ try {+ const foundA = (await hybridSearch(brainA, 'quarterly plan')).map(result => result.slug);+ const foundB = (await hybridSearch(brainB, 'quarterly plan')).map(result => result.slug);+ if (!foundA.includes('notes/brain-a') || foundA.includes('notes/brain-b')) problems.push(`brain-a found ${JSON.stringify(foundA)}`);+ if (!foundB.includes('notes/brain-b') || foundB.includes('notes/brain-a')) problems.push(`brain-b found ${JSON.stringify(foundB)}`);+ } finally {+ await Promise.all([brainA.disconnect(), brainB.disconnect()]);+ }+ const only = (seen: Set<string>, want: string) => seen.size === 1 && seen.has(`Bearer ${want}`);+ if (!only(providerA.bearers, keyA)) problems.push(`provider A saw ${providerA.bearers.size} distinct keys, not only brain-a's`);+ if (!only(providerB.bearers, keyB)) problems.push(`provider B saw ${providerB.bearers.size} distinct keys, not only brain-b's`);+} finally {+ providerA.stop();+ providerB.stop();+}++if (problems.length) {+ console.error(`embedded-two-brains: FAILED\n ${problems.join('\n ')}`);+ process.exit(1);+}+console.log('embedded-two-brains: ok (each brain found its own page; each provider saw only its own brain\'s key)');diff --git a/test/examples-embedded-two-brains.test.ts b/test/examples-embedded-two-brains.test.tsnew file mode 100644index 0000000000..851f9df521--- /dev/null+++ b/test/examples-embedded-two-brains.test.ts@@ -0,0 +1,24 @@+/**+ * GBRA-283 B3a acceptance: examples/embedded-two-brains.ts, which uses only package exports, runs to completion. It+ * opens two brains with distinct fake providers on 127.0.0.1, puts a page in each, searches, closes, and exits 1 if+ * either provider saw the other brain's key or a brain found the other's page. No provider key from this process+ * reaches it.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const ROOT = join(import.meta.dir, '..');+const SCRUBBED = /^(OPENAI|ANTHROPIC|VOYAGE|GEMINI|GOOGLE_GENERATIVE_AI|TYPESAFE|JEV_TYPESAFE|GROQ|MISTRAL|DEEPSEEK|TOGETHER|OPENROUTER)_|^(GBRAIN_|DATABASE_URL$|HOME$)/;++describe('examples/embedded-two-brains.ts', () => {+ test('two brains with distinct fake providers never cross keys or pages', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-example-two-brains-'));+ const env = { ...Object.fromEntries(Object.entries(Bun.env).filter(([name]) => !SCRUBBED.test(name))), HOME: home, GBRAIN_HOME: home };+ const run = Bun.spawn(['bun', 'examples/embedded-two-brains.ts'], { cwd: ROOT, env, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited]);+ expect({ code, failed: stderr.includes('FAILED') ? stderr : null }).toEqual({ code: 0, failed: null });+ expect(stdout).toContain('embedded-two-brains: ok');+ }, 180_000);+});