Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* Subagent brain-tool registry tests. Covers:
* - every allow-list name exists in OPERATIONS (catches renames upstream)
* - Anthropic tool-name constraint enforced
* - put_page schema is namespace-wrapped per subagent
* - execute() invokes the op handler with viaSubagent=true + subagentId
* - filterAllowedTools narrows registry + rejects unknown names
* - denied ops (file_upload etc.) do NOT appear in the registry
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import * as fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { operations, OperationError } from '../src/core/operations.ts';
import {
BRAIN_TOOL_ALLOWLIST,
buildBrainTools,
filterAllowedTools,
__testing,
} from '../src/core/minions/tools/brain-allowlist.ts';
import type { GBrainConfig } from '../src/core/config.ts';
import type { ToolCtx } from '../src/core/minions/types.ts';
import { withEnv } from './helpers/with-env.ts';
import { loadActivePackForWriteVocabulary } from '../src/core/schema-pack/write-vocabulary.ts';
import { classifyStoredType } from '../src/core/schema-pack/type-usage.ts';
import { MAX_FILE_SIZE } from '../src/core/import-file.ts';
let engine: PGLiteEngine;
let fixtureDir: string;
const config: GBrainConfig = { engine: 'pglite' } as GBrainConfig;
beforeAll(async () => {
fixtureDir = fs.mkdtempSync(join(tmpdir(), 'gbrain-brain-tools-'));
engine = new PGLiteEngine();
await engine.connect({ database_url: '' });
await engine.initSchema();
}, 60_000); // OAuth v25 + full migration chain needs breathing room
afterAll(async () => {
if (engine) await engine.disconnect();
if (fixtureDir) fs.rmSync(fixtureDir, { recursive: true, force: true });
}, 60_000);
beforeEach(async () => {
await engine.executeRaw('DELETE FROM pages');
});
describe('BRAIN_TOOL_ALLOWLIST', () => {
test('every name exists in src/core/operations.ts OPERATIONS', () => {
const opNames = new Set(operations.map(o => o.name));
const missing = [...BRAIN_TOOL_ALLOWLIST].filter(n => !opNames.has(n));
expect(missing).toEqual([]);
});
test('contains delegated page tools and excludes local-only attachments', () => {
// v0.29 added get_recent_salience + find_anomalies (read-only).
// get_recent_transcripts is deliberately excluded — subagent calls always
// have ctx.remote=true, and the v0.29 trust gate rejects remote callers.
// v114 (#1941) added list_link_sources (read-only provenance discovery);
// the edge-WRITE ops add_link/remove_link stay out (separate trust call).
// #2778 added add_timeline_entry (write, fenced like put_page via
// operations.ts:enforceSubagentSlugFence).
expect(BRAIN_TOOL_ALLOWLIST.size).toBe(13);
expect(BRAIN_TOOL_ALLOWLIST.has('file_list')).toBe(false);
expect(BRAIN_TOOL_ALLOWLIST.has('file_url')).toBe(false);
expect(BRAIN_TOOL_ALLOWLIST.has('add_timeline_entry')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('query')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('search')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('get_page')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('list_pages')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('put_page')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('get_recent_salience')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('find_anomalies')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('list_link_sources')).toBe(true);
expect(BRAIN_TOOL_ALLOWLIST.has('add_link')).toBe(false);
expect(BRAIN_TOOL_ALLOWLIST.has('remove_link')).toBe(false);
expect(BRAIN_TOOL_ALLOWLIST.has('get_recent_transcripts')).toBe(false);
});
test('does NOT contain destructive ops', () => {
expect(BRAIN_TOOL_ALLOWLIST.has('file_upload')).toBe(false);
expect(BRAIN_TOOL_ALLOWLIST.has('delete_page')).toBe(false);
expect(BRAIN_TOOL_ALLOWLIST.has('delete_file')).toBe(false);
expect(BRAIN_TOOL_ALLOWLIST.has('sync')).toBe(false);
});
});
describe('buildBrainTools', () => {
test('produces one ToolDef per allow-listed op that exists in operations.ts', () => {
const tools = buildBrainTools({ subagentId: 42, engine, config });
const opNames = new Set(operations.map(o => o.name));
const expected = [...BRAIN_TOOL_ALLOWLIST].filter(n => opNames.has(n)).length;
expect(tools.length).toBe(expected);
});
test('tool names are brain_<op> and match Anthropic constraint', () => {
const tools = buildBrainTools({ subagentId: 7, engine, config });
for (const t of tools) {
expect(t.name).toMatch(__testing.ANTHROPIC_NAME_RE);
expect(t.name.startsWith('brain_')).toBe(true);
}
});
test('tools are flagged idempotent in v0.15', () => {
const tools = buildBrainTools({ subagentId: 1, engine, config });
expect(tools.every(t => t.idempotent === true)).toBe(true);
});
test('tools carry the op description verbatim', () => {
const tools = buildBrainTools({ subagentId: 1, engine, config });
const getPage = tools.find(t => t.name === 'brain_get_page');
const op = operations.find(o => o.name === 'get_page');
expect(getPage?.description).toBe(op!.description);
});
test('put_page schema is namespace-wrapped per subagent', () => {
const tools42 = buildBrainTools({ subagentId: 42, engine, config });
const putPage42 = tools42.find(t => t.name === 'brain_put_page');
const slug42 = ((putPage42!.input_schema as any).properties as any).slug;
expect(slug42.pattern).toBe('^wiki/agents/42/.+');
expect(slug42.description).toContain('wiki/agents/42/');
const tools7 = buildBrainTools({ subagentId: 7, engine, config });
const putPage7 = tools7.find(t => t.name === 'brain_put_page');
const slug7 = ((putPage7!.input_schema as any).properties as any).slug;
expect(slug7.pattern).toBe('^wiki/agents/7/.+');
});
test('non-put_page tools do NOT get a pattern on slug', () => {
const tools = buildBrainTools({ subagentId: 42, engine, config });
const getPage = tools.find(t => t.name === 'brain_get_page');
const slug = ((getPage!.input_schema as any).properties as any).slug;
expect(slug).toBeDefined();
expect(slug.pattern).toBeUndefined();
});
test('execute() names a missing required parameter instead of crashing', async () => {
const tools = buildBrainTools({ subagentId: 42, engine, config });
const search = tools.find(t => t.name === 'brain_search');
expect(search).toBeDefined();
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
await expect(search!.execute({}, ctx)).rejects.toThrow(/brain_search: Missing required parameter: query/);
await expect(search!.execute(undefined, ctx)).rejects.toThrow(/Missing required parameter/);
});
test('execute() rejects a type mismatch and an unknown enum value by name (wave review)', async () => {
const tools = buildBrainTools({ subagentId: 42, engine, config });
const search = tools.find(t => t.name === 'brain_search')!;
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
await expect(search.execute({ query: 'x', limit: 'ten' }, ctx)).rejects.toThrow(/brain_search: Parameter "limit" must be a number/);
await expect(search.execute({ query: 'x', salience: 'loud' }, ctx)).rejects.toThrow(/brain_search: Parameter "salience" must be one of: off, on, strong/);
});
test('execute() normalizes optional absent idioms (null / "") before validation and the handler (wave review)', async () => {
// Same order the MCP dispatchers keep. `updated_after: ""` raw would reach
// list_pages' ::timestamptz filter; `type: null` is the JSON-client spelling
// of "omitted". Both must land as a plain empty listing, not a crash.
const tools = buildBrainTools({ subagentId: 42, engine, config });
const listPages = tools.find(t => t.name === 'brain_list_pages')!;
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
const res = await listPages.execute({ updated_after: '', type: null, limit: 5 }, ctx) as unknown;
expect(res).toBeDefined();
});
test('execute() on get_page include_content returns the body once (#6297)', async () => {
await engine.putPage('notes/payload-example', { type: 'note', title: 'Payload example', compiled_truth: 'Distinctive body text for the payload test.', timeline: '' });
const tools = buildBrainTools({ subagentId: 42, engine, config });
const getPage = tools.find(t => t.name === 'brain_get_page')!;
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
const res = await getPage.execute({ slug: 'notes/payload-example', include_content: true }, ctx) as Record<string, unknown>;
expect(String(res.content)).toContain('Distinctive body text');
expect(res).not.toHaveProperty('compiled_truth');
expect(res).not.toHaveProperty('timeline');
expect(JSON.stringify(res).split('Distinctive body text').length - 1).toBe(1);
});
test('execute() on put_page with valid namespace slug succeeds', async () => {
const tools = buildBrainTools({ subagentId: 42, engine, config });
const putPage = tools.find(t => t.name === 'brain_put_page');
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
const res = await putPage!.execute(
{ slug: 'wiki/agents/42/notes', content: '---\ntitle: Notes\n---\nbody' },
ctx,
);
expect(res).toBeTruthy();
});
test('execute() on put_page with out-of-namespace slug throws permission_denied', async () => {
const tools = buildBrainTools({ subagentId: 42, engine, config });
const putPage = tools.find(t => t.name === 'brain_put_page');
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
await expect(
putPage!.execute(
{ slug: 'wiki/analysis/stomp', content: '---\ntitle: x\n---\nb' },
ctx,
),
).rejects.toBeInstanceOf(OperationError);
});
// #1586: sourceId threads through buildBrainTools → buildOpContext →
// put_page → importFromContent, so subagent writes land in the cycle's
// resolved source instead of the hardcoded 'default'.
test('execute() on put_page writes to the configured sourceId (#1586)', async () => {
// Write-through needs a real directory for this source's local_path —
// put_page now rejects a write whose file can't be written to disk.
const sourceRoot = join(fixtureDir, 'mybrain');
fs.mkdirSync(sourceRoot);
await engine.executeRaw(
`INSERT INTO sources (id, name, local_path, config, archived, created_at)
VALUES ('mybrain', 'My Brain', $1, '{}'::jsonb, false, now())
ON CONFLICT (id) DO NOTHING`,
[sourceRoot],
);
const tools = buildBrainTools({
subagentId: 42,
engine,
config,
allowedSlugPrefixes: ['wiki/personal/reflections/*'],
sourceId: 'mybrain',
});
const putPage = tools.find(t => t.name === 'brain_put_page');
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
await putPage!.execute(
{ slug: 'wiki/personal/reflections/2026-07-17-scoped', content: '---\ntitle: Scoped\n---\nbody' },
ctx,
);
const rows = await engine.executeRaw<{ source_id: string }>(
`SELECT source_id FROM pages WHERE slug = 'wiki/personal/reflections/2026-07-17-scoped'`,
);
expect(rows.length).toBe(1);
expect(rows[0].source_id).toBe('mybrain');
});
test('buildBrainTools rejects a malformed sourceId at build time (#1586)', () => {
expect(() =>
buildBrainTools({ subagentId: 1, engine, config, sourceId: '../evil' }),
).toThrow();
});
});
describe('filterAllowedTools', () => {
test('passes prefixed names through', () => {
const tools = buildBrainTools({ subagentId: 1, engine, config });
const filtered = filterAllowedTools(tools, ['brain_get_page', 'brain_search']);
expect(filtered.map(t => t.name)).toEqual(['brain_get_page', 'brain_search']);
});
test('accepts un-prefixed names as a convenience', () => {
const tools = buildBrainTools({ subagentId: 1, engine, config });
const filtered = filterAllowedTools(tools, ['get_page', 'search']);
expect(filtered.map(t => t.name)).toEqual(['brain_get_page', 'brain_search']);
});
test('rejects unknown tool names (no silent ignore)', () => {
const tools = buildBrainTools({ subagentId: 1, engine, config });
expect(() => filterAllowedTools(tools, ['brain_typo_nope'])).toThrow(/unknown tool/);
});
test('deduplicates when both prefixed + unprefixed given', () => {
const tools = buildBrainTools({ subagentId: 1, engine, config });
const filtered = filterAllowedTools(tools, ['brain_get_page', 'get_page']);
expect(filtered.length).toBe(1);
});
test('empty array yields empty registry', () => {
const tools = buildBrainTools({ subagentId: 1, engine, config });
expect(filterAllowedTools(tools, [])).toEqual([]);
});
});
describe('sanitizeToolName', () => {
test('returns within 64 chars', () => {
// Synthetic: simulate an op name long enough to need slicing.
const long = 'a'.repeat(100);
expect(__testing.sanitizeToolName(long).length).toBeLessThanOrEqual(64);
});
test('replaces non-conforming chars with _', () => {
expect(__testing.sanitizeToolName('foo.bar')).toBe('brain_foo_bar');
});
});
// #4852: trusted-workspace subagents (dream synth agentic lane, patterns,
// delegated jobs) author page content model-side and mint types no bundled
// pack declares (`reflection` / `original` / `pattern`); the reverse-write puts
// that type on disk as explicit frontmatter and every `gbrain sync` warns.
// The oneshot lane already pins its output to 'note' (F5); the seam extends
// that rule: an EXPLICIT undeclared type rewrites to 'note' + legacy_type.
describe('brain_put_page pins undeclared model-authored types (#4852)', () => {
const PREFIXES = ['wiki/personal/patterns/*'];
async function putUnderPack(slug: string, content: string, allowedSlugPrefixes?: readonly string[]) {
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-base-v2' }, async () => {
const tools = buildBrainTools({ subagentId: 42, engine, config, allowedSlugPrefixes });
const putPage = tools.find(t => t.name === 'brain_put_page');
await putPage!.execute({ slug, content }, ctx);
});
return (await engine.getPage(slug, { sourceId: 'default' }))!;
}
test('explicit undeclared type under a slug allow-list → note + frontmatter.legacy_type', async () => {
const page = await putUnderPack(
'wiki/personal/patterns/recurring-theme',
'---\ntype: pattern\ntitle: Recurring theme\n---\n\nBody [[wiki/personal/reflections/x]]',
PREFIXES,
);
expect(page.type).toBe('note');
expect(page.frontmatter.legacy_type).toBe('pattern');
expect(page.title).toBe('Recurring theme');
expect(page.compiled_truth).toContain('Body [[wiki/personal/reflections/x]]');
// The sync type-warning path has nothing to say about the stored type.
const pack = await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-base-v2' }, () =>
loadActivePackForWriteVocabulary({ engine, remote: true }));
expect(classifyStoredType(page.type, pack!.manifest).kind).toBe('canonical');
});
test('same request UUID replays frozen normalized content after the active pack changes', async () => {
const slug = 'wiki/personal/patterns/frozen-type';
const args = { slug, request_id: randomUUID(), content: '---\ntype: pattern\ntitle: Frozen type\n---\nOriginal model-authored observation.' };
const tools = buildBrainTools({ subagentId: 42, engine, config, allowedSlugPrefixes: PREFIXES });
const tool = tools.find(t => t.name === 'brain_put_page')!;
const ctx: ToolCtx = { engine, jobId: 1, remote: true };
const first = await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-base-v2' }, () => tool.execute(args, ctx)) as Record<string, unknown>;
expect(first.state).toBe('committed');
const before = await engine.readPageSnapshot(slug, { sourceId: 'default' });
expect(before?.page.type).toBe('note');
const replay = await withEnv({ GBRAIN_SCHEMA_PACK: 'missing-fixture-pack' }, () => tool.execute(args, ctx)) as Record<string, unknown>;
expect(replay.request_id).toBe(args.request_id);
expect(replay.revision).toBe(first.revision);
expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).toEqual(before);
expect(await engine.executeRaw('SELECT id FROM page_versions WHERE page_id=$1', [before!.page.id])).toHaveLength(0);
const rows = await engine.executeRaw<{digest:string;intent:{content:string}}>('SELECT digest,intent FROM persistence_requests WHERE request_id=$1::uuid', [args.request_id]);
expect(rows).toHaveLength(1);
expect(rows[0].intent.content).toContain('type: note');
expect(args.content).toContain('type: pattern');
});
test('scoped normalization retains raw-size and sanitized YAML rejection guards', async () => {
const tools = buildBrainTools({ subagentId: 42, engine, config, allowedSlugPrefixes: PREFIXES });
const tool = tools.find(t => t.name === 'brain_put_page')!;
await withEnv({ GBRAIN_SCHEMA_PACK: 'gbrain-base-v2' }, async () => {
for (const [content, code] of [
['---\ntype: pattern\ntitle: Example\n---\nBody' + ' '.repeat(MAX_FILE_SIZE), 'request_too_large'],
['---\ntype: pattern\nprivate_marker: [\n---\nPrivate fixture text', 'invalid_params'],
]) {
const error = await tool.execute({ slug: 'wiki/personal/patterns/rejected', content, request_id: randomUUID() },
{ engine, jobId: 1, remote: true }).then(() => null, error => error);
// Invalid YAML fails its admitted request; an over-ceiling body is refused before admission (no request).
if (code === 'request_too_large') expect(error).toMatchObject({ code, writeRequest: undefined });
else expect(error).toMatchObject({ code, writeRequest: { state: 'failed' } });
expect(error.message).not.toContain('private_marker');
expect(await engine.getPage('wiki/personal/patterns/rejected', { sourceId: 'default' })).toBeNull();
}
});
});
test('declared type is stored untouched (no legacy_type)', async () => {
const page = await putUnderPack(
'wiki/personal/patterns/declared',
'---\ntype: note\ntitle: Declared\n---\n\nBody',
PREFIXES,
);
expect(page.type).toBe('note');
expect(page.frontmatter.legacy_type).toBeUndefined();
});
test('declared alias is stored literally (alias_of stays a sync warning, not a rewrite)', async () => {
const page = await putUnderPack(
'wiki/personal/patterns/aliased',
'---\ntype: insight\ntitle: Aliased\n---\n\nBody',
PREFIXES,
);
expect(page.type).toBe('insight');
expect(page.frontmatter.legacy_type).toBeUndefined();
});
test('no explicit type → pack inference untouched', async () => {
const page = await putUnderPack(
'wiki/personal/patterns/inferred',
'---\ntitle: Inferred\n---\n\nBody',
PREFIXES,
);
expect(page.type).toBe('concept');
expect(page.frontmatter.legacy_type).toBeUndefined();
});
test('same write WITHOUT a slug allow-list (legacy agents namespace) stores the literal type', async () => {
const page = await putUnderPack(
'wiki/agents/42/pattern-literal',
'---\ntype: pattern\ntitle: Literal\n---\n\nBody',
);
expect(page.type).toBe('pattern');
expect(page.frontmatter.legacy_type).toBeUndefined();
});
});