Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(setup): rewrite a same-server legacy OpenClaw plugin; never verify one left alone
garrytancf549a3d5337
diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.tsindex efabf42502..ae8b9be066 100644--- a/src/core/setup/brain-first.ts+++ b/src/core/setup/brain-first.ts@@ -431,7 +431,8 @@ function syncBrainFirstLocked(opts: { target: BrainFirstTarget; access: BrainFirif (decision.value === 'declined') {// The target moved (Codex: a non-empty AGENTS.override.md now wins), so an opt-out also strips the// blocks this harness still has at its other user-global paths; otherwise their records keep the per-turn rule on.- if (!target.project) {+ // Each OpenClaw workspace is another agent's own file, so opting one out leaves the others.+ if (!target.project && target.harness !== 'openclaw') {for (const other of readBrainFirstLedger().filter((e) => e.harness === target.harness && e.path !== target.path && e.status === 'installed' && !isProjectSurface(e.harness, e.path))) {syncBrainFirst({ ...opts, target: { ...target, path: other.path }, access: other.access });}diff --git a/src/core/setup/openclaw-turn-plugin.ts b/src/core/setup/openclaw-turn-plugin.tsindex 66f7778b4f..8e9a3e0073 100644--- a/src/core/setup/openclaw-turn-plugin.ts+++ b/src/core/setup/openclaw-turn-plugin.ts@@ -71,23 +71,38 @@ const installArgv = (bin: string, dir: string): string[][] => [const shown = (argv: string[]) => argv.map((a) => (/^[\w./:=@-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(' ');-/** The access an installed plugin records in its package.json: undefined with no plugin, null when an older gbrain wrote it without one. */-function installedAccess(dir: string): BrainFirstAccess | null | undefined {+/**+ * What an installed plugin was written for: the access its package.json records, else (an older gbrain recorded+ * none) the server or launcher its RULE literal names. undefined with no plugin, null when neither can be read.+ */+function installedAccess(dir: string): { access: BrainFirstAccess; recorded: boolean } | null | undefined {if (!existsSync(join(dir, 'index.js'))) return undefined;- try { return (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { gbrain?: { access?: BrainFirstAccess } }).gbrain?.access ?? null; } catch { return null; }+ try {+ const recorded = (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { gbrain?: { access?: BrainFirstAccess } }).gbrain?.access;+ if (recorded) return { access: recorded, recorded: true };+ const literal = /^const RULE = (".*");$/m.exec(readFileSync(join(dir, 'index.js'), 'utf8'))?.[1];+ const rule = literal ? JSON.parse(literal) as string : '';+ const server = /on the `([^`]+)` MCP server/.exec(rule)?.[1];+ const launcher = /check GBrain first \(`(.+?) search "<names>"`/.exec(rule)?.[1];+ return server ? { access: { kind: 'mcp', server }, recorded: false } : launcher ? { access: { kind: 'cli', launcher }, recorded: false } : null;+ } catch { return null; }}const named = (a: BrainFirstAccess) => (a.kind === 'mcp' ? `the \`${a.server}\` MCP server` : `\`${a.launcher}\``);/*** Write the plugin and install it with OpenClaw's CLI (accepted decision). Never throws. Every agent on the gateway gets- * the plugin's rule, so a `workspace`-scoped run leaves an installed plugin whose rule would change to another server.+ * the plugin's rule, so a `workspace`-scoped run leaves an installed plugin whose rule would name another server (or+ * one it cannot read) and prints, unverified, the command that changes it for every agent.*/export function syncOpenclawTurnPlugin(opts: { access: BrainFirstAccess; dryRun: boolean; workspace?: string; openclawBin?: string | null; run?: Run }): OpenclawTurnPluginOutcome {const dir = openclawTurnPluginDir();const installed = opts.workspace ? installedAccess(dir) : undefined;- if (installed !== undefined && (!installed || renderBrainFirstTurnRule(installed, 'openclaw') !== renderBrainFirstTurnRule(opts.access, 'openclaw'))) {- return { action: 'skip', path: dir, detail: `${dir} left as it is: every agent on this OpenClaw gateway gets its rule, which ${installed ? `names ${named(installed)}` : 'an older gbrain wrote without recording its server'}, so a --workspace run does not rewrite it. To change it for every agent: gbrain setup openclaw --remove --workspace ${opts.workspace}, then run this again` };+ const same = installed && (installed.recorded+ ? renderBrainFirstTurnRule(installed.access, 'openclaw') === renderBrainFirstTurnRule(opts.access, 'openclaw')+ : named(installed.access) === named(opts.access));+ if (installed !== undefined && !same) {+ return { action: 'print', path: dir, detail: `${dir} left as it is: every agent on this OpenClaw gateway gets its rule, which ${installed ? `names ${named(installed.access)}` : 'gbrain cannot read'}, so a --workspace run does not rewrite it. To change it for every agent, run this, then this setup again`, commands: [`gbrain setup openclaw --remove --workspace ${opts.workspace}`] };}const files = openclawTurnPluginFiles(opts.access);const bin = opts.openclawBin !== undefined ? opts.openclawBin : findOpenclaw();diff --git a/test/brain-first-turn-rule.test.ts b/test/brain-first-turn-rule.test.tsindex ac91d3b7b8..390dbfc194 100644--- a/test/brain-first-turn-rule.test.ts+++ b/test/brain-first-turn-rule.test.ts@@ -336,8 +336,9 @@ describe('per-turn rule: OpenClaw before_prompt_build plugin', () => {const index = readFileSync(join(openclawTurnPluginDir(), 'index.js'), 'utf8');const rec = recorder();const other = syncOpenclawTurnPlugin({ access: { kind: 'mcp', server: 'gbrain-a' }, workspace: '/ws/a', dryRun: false, openclawBin: '/bin/openclaw', run: rec.run });- expect(other.action).toBe('skip');+ expect(other.action).toBe('print');expect(other.detail).toContain('names the `gbrain` MCP server');+ expect(other.commands).toEqual(['gbrain setup openclaw --remove --workspace /ws/a']);expect(readFileSync(join(openclawTurnPluginDir(), 'index.js'), 'utf8')).toBe(index);expect(rec.calls).toEqual([]);expect(syncOpenclawTurnPlugin({ access, workspace: '/ws/a', dryRun: false, openclawBin: '/bin/openclaw', run: recorder().run }).action).toBe('keep');@@ -348,6 +349,40 @@ describe('per-turn rule: OpenClaw before_prompt_build plugin', () => {});});+ test('a plugin an older gbrain wrote (no recorded access): a same-server --workspace run rewrites it; another server or an unreadable rule is left', async () => {+ const legacy = (rule: string) => {+ const dir = openclawTurnPluginDir();+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'package.json'), `${JSON.stringify({ name: OPENCLAW_TURN_PLUGIN_ID, version: '1.0.0', private: true, type: 'module', openclaw: { extensions: ['./index.js'] } }, null, 2)}\n`);+ writeFileSync(join(dir, 'index.js'), [`const RULE = ${JSON.stringify(rule)};`, 'export default {', ` id: '${OPENCLAW_TURN_PLUGIN_ID}',`, ' register(api) {', " api.on('before_prompt_build', () => ({ prependContext: RULE }));", ' },', '};', ''].join('\n'));+ return dir;+ };+ await withEnv({ OPENCLAW_STATE_DIR: state(), OPENCLAW_PROFILE: undefined }, async () => {+ const dir = legacy(renderBrainFirstTurnRule(access, 'openclaw'));+ expect(syncOpenclawTurnPlugin({ access, workspace: '/ws/a', dryRun: false, openclawBin: '/bin/openclaw', run: recorder().run }).action).toBe('write');+ expect(JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).gbrain).toEqual({ access });+ const mod = await import(join(dir, 'index.js'));+ const handlers: Record<string, (event?: unknown, ctx?: unknown) => unknown> = {};+ mod.default.register({ on: (event: string, fn: (event?: unknown, ctx?: unknown) => unknown) => { handlers[event] = fn; } });+ expect(handlers.before_prompt_build({}, { inputProvenance: { kind: 'internal_system' } })).toEqual({ prependContext: renderBrainFirstTurnRule(access, 'openclaw', { reply: false }) });+ });+ await withEnv({ OPENCLAW_STATE_DIR: state(), OPENCLAW_PROFILE: undefined }, async () => {+ const dir = legacy(renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain-b' }, 'openclaw'));+ const index = readFileSync(join(dir, 'index.js'), 'utf8');+ const other = syncOpenclawTurnPlugin({ access, workspace: '/ws/a', dryRun: false, openclawBin: '/bin/openclaw', run: recorder().run });+ expect(other.action).toBe('print');+ expect(other.detail).toContain('names the `gbrain-b` MCP server');+ expect(readFileSync(join(dir, 'index.js'), 'utf8')).toBe(index);+ });+ await withEnv({ OPENCLAW_STATE_DIR: state(), OPENCLAW_PROFILE: undefined }, async () => {+ const dir = legacy('not a gbrain rule');+ const unreadable = syncOpenclawTurnPlugin({ access, workspace: '/ws/a', dryRun: false, openclawBin: '/bin/openclaw', run: recorder().run });+ expect(unreadable.action).toBe('print');+ expect(unreadable.detail).toContain('gbrain cannot read');+ expect(readFileSync(join(dir, 'index.js'), 'utf8')).toContain('not a gbrain rule');+ });+ });+test('removal keeps the directory OpenClaw still loads when the uninstall fails or openclaw is not on PATH', async () => {await withEnv({ OPENCLAW_STATE_DIR: state(), OPENCLAW_PROFILE: undefined }, async () => {syncOpenclawTurnPlugin({ access, dryRun: false, openclawBin: '/bin/openclaw', run: recorder().run });diff --git a/test/setup-brain-first.test.ts b/test/setup-brain-first.test.tsindex 1cbaed019b..7129752551 100644--- a/test/setup-brain-first.test.ts+++ b/test/setup-brain-first.test.ts@@ -24,6 +24,7 @@ import {BRAIN_FIRST_END,renderBrainFirstBlock,renderBrainFirstSnippet,+ renderBrainFirstTurnRule,} from '../src/core/setup/brain-first.ts';import { harnessWiringCheck, instructionBlockViews, withInstructionBlocks, withSurfaceNote, type InstructionBlockView } from '../src/commands/doctor/checks/harness-wiring.ts';import { installHarnessConnection } from '../src/core/harness/install.ts';@@ -280,22 +281,65 @@ describe('brain-first block: placement rules', () => {expect(existsSync(join(b.home, '.openclaw', 'gbrain'))).toBe(false);});+ /** A fake openclaw CLI: `config set` enables the plugin in openclaw.json (as enable + config set do), `plugins inspect` reports it loaded. */+ function fakeOpenclaw(b: Box): Record<string, string> {+ const cfg = join(b.home, '.openclaw', 'openclaw.json');+ const enabled = JSON.stringify({ plugins: { entries: { 'gbrain-turn-rule': { enabled: true, hooks: { allowConversationAccess: true } } } } });+ writeFileSync(join(b.root, 'bin', 'openclaw'), [+ '#!/bin/sh',+ `case "$*" in "config set"*) printf '%s' '${enabled}' > '${cfg}';; "plugins inspect"*) echo '{"id":"gbrain-turn-rule","status":"loaded","imported":true,"hooks":["before_prompt_build"]}';; esac`,+ 'exit 0',+ '',+ ].join('\n'));+ chmodSync(join(b.root, 'bin', 'openclaw'), 0o755);+ return { PATH: `${join(b.root, 'bin')}:${process.env.PATH ?? ''}` };+ }+test('openclaw --workspace: the gateway-shared plugin is not rewritten for another server name or removed by one workspace opting out', async () => {const b = box();mkdirSync(join(b.home, '.openclaw', 'workspace'), { recursive: true });- writeFileSync(join(b.root, 'bin', 'openclaw'), '#!/bin/sh\nexit 0\n');- chmodSync(join(b.root, 'bin', 'openclaw'), 0o755);- const path = { PATH: `${join(b.root, 'bin')}:${process.env.PATH ?? ''}` };+ const path = fakeOpenclaw(b);const dir = join(b.home, '.openclaw', 'gbrain', 'gbrain-turn-rule');- await setup(b, ['openclaw'], path);+ const first = await setup(b, ['openclaw'], path);+ expect(first.exitCode).toBe(0);+ expect(first.doc.turn_hook_check.ok).toBe(true);const index = read(join(dir, 'index.js'));const ws = join(b.home, 'ws-a');+ mkdirSync(ws);const renamed = await setup(b, ['openclaw', '--workspace', ws, '--name', 'gbrain-a', '--instructions-only'], path);- expect(renamed.doc.turn_hook.action).toBe('skip');+ expect(renamed.exitCode).toBe(0);+ expect(renamed.doc.turn_hook.action).toBe('print');+ expect(renamed.doc.turn_hook.commands).toEqual([`gbrain setup openclaw --remove --workspace ${ws}`]);expect(read(join(dir, 'index.js'))).toBe(index);const declined = await setup(b, ['openclaw', '--workspace', ws, '--no-instructions'], path);+ expect(declined.exitCode).toBe(0);+ expect(declined.doc.instructions.action).toBe('remove');expect(declined.doc.turn_hook.action).toBe('skip');expect(read(join(dir, 'index.js'))).toBe(index);+ expect(read(join(b.home, '.openclaw', 'workspace', 'AGENTS.md'))).toContain(BRAIN_FIRST_BEGIN);+ });++ test('openclaw --workspace on a disabled plugin an older gbrain wrote: another server exits 0 with the way out, the same server rewrites and enables it', async () => {+ const b = box();+ mkdirSync(join(b.home, '.openclaw', 'workspace'), { recursive: true });+ const path = fakeOpenclaw(b);+ const dir = join(b.home, '.openclaw', 'gbrain', 'gbrain-turn-rule');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'package.json'), `${JSON.stringify({ name: 'gbrain-turn-rule', version: '1.0.0', private: true, type: 'module', openclaw: { extensions: ['./index.js'] } }, null, 2)}\n`);+ writeFileSync(join(dir, 'index.js'), [`const RULE = ${JSON.stringify(renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' }, 'openclaw'))};`, 'export default {', " id: 'gbrain-turn-rule',", ' register(api) {', " api.on('before_prompt_build', () => ({ prependContext: RULE }));", ' },', '};', ''].join('\n'));+ writeFileSync(join(b.home, '.openclaw', 'openclaw.json'), JSON.stringify({ plugins: { entries: { 'gbrain-turn-rule': { enabled: false } } } }));+ const ws = join(b.home, 'ws-a');+ mkdirSync(ws);+ for (let i = 0; i < 2; i++) {+ const other = await setup(b, ['openclaw', '--workspace', ws, '--name', 'gbrain-a', '--instructions-only'], path);+ expect(other.exitCode).toBe(0);+ expect(other.doc.turn_hook.action).toBe('print');+ }+ const same = await setup(b, ['openclaw', '--workspace', ws, '--instructions-only'], path);+ expect(same.exitCode).toBe(0);+ expect(same.doc.turn_hook.action).toBe('write');+ expect(same.doc.turn_hook_check.ok).toBe(true);+ expect(JSON.parse(read(join(dir, 'package.json'))).gbrain).toEqual({ access: { kind: 'mcp', server: 'gbrain' } });});test('a damaged block is preserved and reported, never guessed through', async () => {