Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-188 review fixes: keep the OpenClaw plugin dir until uninstall succeeds; never rewrite an unreadable Hermes allowlist or append to a flow-style config.yaml; bounded YAML load; classify GBRAIN_AGENT_INSTRUCTIONS
garrytan4f7b1084e196
diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.tsindex c4b778fec5..f3fb333d5f 100644--- a/src/core/setup/hermes-turn-hook.ts+++ b/src/core/setup/hermes-turn-hook.ts@@ -17,8 +17,8 @@*/import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';-import { load } from 'js-yaml';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { loadBoundedYaml } from '../data-frontmatter.ts';import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';import { renderBrainFirstTurnRule, writeUnlessChanged, type BrainFirstAccess } from './brain-first.ts';@@ -44,13 +44,12 @@ function hookYaml(command: string): string {interface Allowlist { approvals: Array<Record<string, unknown>> }+/** Throws on a file gbrain cannot read as Hermes does (utf-8-sig JSON object), so it is never rewritten without the user's approvals. */function readAllowlist(path: string): Allowlist {- try {- const raw = JSON.parse(readFileSync(path, 'utf8')) as Allowlist;- return raw && Array.isArray(raw.approvals) ? raw : { ...raw, approvals: [] };- } catch {- return { approvals: [] };- }+ if (!existsSync(path)) return { approvals: [] };+ const raw = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, '')) as Allowlist;+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`${ALLOWLIST} is not a JSON object`);+ return Array.isArray(raw.approvals) ? raw : { ...raw, approvals: [] };}const approves = (e: Record<string, unknown>, command: string) => e.event === EVENT && e.command === command;@@ -83,11 +82,13 @@ export function syncHermesTurnHook(opts: { hermesHome: string; access: BrainFirsconst probe = probeBlock(MARKERS, text);if (probe.state === 'damaged') return print('the gbrain turn-rule markers in config.yaml are damaged');if (probe.state === 'absent') {- const doc = load(text) as Record<string, unknown> | null | undefined;+ const doc = loadBoundedYaml(text) as Record<string, unknown> | null | undefined;if (doc !== null && doc !== undefined && typeof doc !== 'object') return print('config.yaml is not a YAML mapping');if (doc && 'hooks' in doc) return print('config.yaml already has a hooks: section, which gbrain does not edit');}+ readAllowlist(join(opts.hermesHome, ALLOWLIST));const next = spliceBlock(MARKERS, text, hookYaml(command));+ if (probe.state === 'absent' && !(loadBoundedYaml(next) as Record<string, unknown> | null)?.hooks) return print('config.yaml would not parse with the hook appended');if (next === text) {if (!opts.dryRun) approve(opts.hermesHome, command);return { action: 'keep', path, detail: `per-turn rule hook (${EVENT}) in ${path}` };diff --git a/src/core/setup/openclaw-turn-plugin.ts b/src/core/setup/openclaw-turn-plugin.tsindex b125e485b5..252212d991 100644--- a/src/core/setup/openclaw-turn-plugin.ts+++ b/src/core/setup/openclaw-turn-plugin.ts@@ -96,7 +96,11 @@ export function syncOpenclawTurnPlugin(opts: { access: BrainFirstAccess; dryRun:return { action: changed ? 'write' : 'keep', path: dir, detail: `per-turn rule plugin ${OPENCLAW_TURN_PLUGIN_ID} (before_prompt_build) at ${dir}, installed and enabled; restart the gateway if it is running` };}-/** Uninstall the plugin and delete its directory (decline or --remove). Never throws. */+/**+ * Uninstall the plugin, then delete its directory (decline or --remove). Never throws. The directory stays+ * until the uninstall succeeds: `install --link` put it in plugins.load.paths, and OpenClaw refuses a config+ * whose load path is missing.+ */export function removeOpenclawTurnPlugin(opts: { dryRun: boolean; openclawBin?: string | null; run?: Run }): OpenclawTurnPluginOutcome {const dir = openclawTurnPluginDir();if (!existsSync(dir)) return { action: 'skip', path: dir, detail: `no per-turn rule plugin at ${dir}` };@@ -104,11 +108,10 @@ export function removeOpenclawTurnPlugin(opts: { dryRun: boolean; openclawBin?:const bin = opts.openclawBin !== undefined ? opts.openclawBin : findOpenclaw();const uninstall = [bin ?? 'openclaw', 'plugins', 'uninstall', OPENCLAW_TURN_PLUGIN_ID, '--force'];const r = bin ? (opts.run ?? defaultRun)(uninstall) : { ok: false, output: 'no openclaw on PATH' };+ if (!r.ok) return { action: 'print', path: dir, detail: `${dir} left in place (OpenClaw still loads it); ${r.output.split('\n').at(-1)}, so run this on the OpenClaw host, then delete ${dir}`, commands: [shown(uninstall)] };try {rmSync(dir, { recursive: true, force: true });if (readdirSync(dirname(dir)).length === 0) rmdirSync(dirname(dir));- } catch { /* the uninstall outcome below is what matters */ }- return r.ok- ? { action: 'remove', path: dir, detail: `per-turn rule plugin ${OPENCLAW_TURN_PLUGIN_ID} uninstalled and ${dir} removed` }- : { action: 'print', path: dir, detail: `${dir} removed; ${r.output.split('\n').at(-1)}, so run this on the OpenClaw host`, commands: [shown(uninstall)] };+ } catch { /* uninstalled; a leftover directory is no longer loaded */ }+ return { action: 'remove', path: dir, detail: `per-turn rule plugin ${OPENCLAW_TURN_PLUGIN_ID} uninstalled and ${dir} removed` };}diff --git a/test/brain-first-turn-rule.test.ts b/test/brain-first-turn-rule.test.tsindex 9ff383af6d..8bf4ed6dc3 100644--- a/test/brain-first-turn-rule.test.ts+++ b/test/brain-first-turn-rule.test.ts@@ -121,6 +121,22 @@ describe('per-turn rule: Hermes pre_llm_call hook in config.yaml', () => {expect(JSON.parse(cmd.slice("/bin/echo '".length, -1))).toEqual({ context: renderBrainFirstTurnRule(access) });});+ test('a flow-style config.yaml, or an allowlist gbrain cannot read, gets the entry printed and both files left as they are', () => {+ const flow = '{model: alice-example-model, agent: {max_turns: 4}}\n';+ const d = hermes(flow);+ expect(syncHermesTurnHook({ hermesHome: d, access, dryRun: false }).action).toBe('print');+ expect(cfg(d)).toBe(flow);+ const unreadable = hermes('model: x\n');+ writeFileSync(join(unreadable, 'shell-hooks-allowlist.json'), '{"approvals": [{"event": "post_tool_call", "command": "/opt/x"}],}');+ expect(syncHermesTurnHook({ hermesHome: unreadable, access, dryRun: false }).action).toBe('print');+ expect(cfg(unreadable)).toBe('model: x\n');+ expect(readFileSync(join(unreadable, 'shell-hooks-allowlist.json'), 'utf8')).toContain('post_tool_call');+ const bom = hermes('model: x\n');+ writeFileSync(join(bom, 'shell-hooks-allowlist.json'), '\uFEFF' + JSON.stringify({ approvals: [{ event: 'post_tool_call', command: '/opt/x' }] }));+ expect(syncHermesTurnHook({ hermesHome: bom, access, dryRun: false }).action).toBe('write');+ expect(approvals(bom).map((e) => e.event)).toEqual(['post_tool_call', 'pre_llm_call']);+ });+test('appends a marked hook after the user\'s text, approves exactly that command, keeps on a re-run, and removal undoes both', () => {const mine = '# my config\nmodel:\n default: alice-example-model\n';const other = { event: 'pre_tool_call', command: '/usr/bin/true', approved_at: 'x', script_mtime_at_approval: null };@@ -233,4 +249,18 @@ describe('per-turn rule: OpenClaw before_prompt_build plugin', () => {expect(existsSync(join(st, 'gbrain'))).toBe(false);});});++ 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 });+ const failed = removeOpenclawTurnPlugin({ dryRun: false, openclawBin: '/bin/openclaw', run: recorder('uninstall').run });+ expect(failed.action).toBe('print');+ expect(failed.commands).toEqual([`/bin/openclaw plugins uninstall ${OPENCLAW_TURN_PLUGIN_ID} --force`]);+ expect(existsSync(join(openclawTurnPluginDir(), 'index.js'))).toBe(true);+ const noBin = removeOpenclawTurnPlugin({ dryRun: false, openclawBin: null });+ expect(noBin.action).toBe('print');+ expect(noBin.commands).toEqual([`openclaw plugins uninstall ${OPENCLAW_TURN_PLUGIN_ID} --force`]);+ expect(existsSync(join(openclawTurnPluginDir(), 'index.js'))).toBe(true);+ });+ });});diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.tsindex c76be0bdce..60f7cc01c0 100644--- a/test/cli-socket.test.ts+++ b/test/cli-socket.test.ts@@ -86,7 +86,7 @@ const NOT_READ_BEHAVIOR_PREFIXES = ['GBRAIN_PROGRESSIVE_BATCH_', 'GBRAIN_QUEUE_', 'GBRAIN_SETUP_', 'GBRAIN_STOP_PUSH', 'GBRAIN_SUPERVIS', 'GBRAIN_SWEEP', 'GBRAIN_SYNC', 'GBRAIN_WORKER_',];const NOT_READ_BEHAVIOR = new Set([- 'GBRAIN_HOME', 'GBRAIN_SERVE_LOG_MAX_BYTES', 'GBRAIN_SERVE_LOG_MAX_FILES', 'GBRAIN_SERVE_LOG_DEDUPE_SECONDS', 'GBRAIN_BRAIN_ID', 'GBRAIN_MOUNTS_PATH', 'GBRAIN_CWD_ENV_QUARANTINED',+ 'GBRAIN_AGENT_INSTRUCTIONS', 'GBRAIN_HOME', 'GBRAIN_SERVE_LOG_MAX_BYTES', 'GBRAIN_SERVE_LOG_MAX_FILES', 'GBRAIN_SERVE_LOG_DEDUPE_SECONDS', 'GBRAIN_BRAIN_ID', 'GBRAIN_MOUNTS_PATH', 'GBRAIN_CWD_ENV_QUARANTINED','GBRAIN_FAIL_ON_EMPTY', 'GBRAIN_CLI_SOCKET', 'GBRAIN_DEBUG', 'GBRAIN_SQL_TRACE', 'GBRAIN_SQL_TRACE_LABEL', 'GBRAIN_MEMORY_TRACE', 'GBRAIN_LME_DEBUG', 'GBRAIN_SOURCE','GBRAIN_DATABASE_URL', 'GBRAIN_DIRECT_DATABASE_URL', 'GBRAIN_DIRECT_POOL_SIZE', 'GBRAIN_DIRECT_POOL_BY_COMMAND', 'GBRAIN_DISABLE_DIRECT_POOL', 'GBRAIN_PREPARE','GBRAIN_IDLE_TX_TIMEOUT', 'GBRAIN_MAX_CONNECTIONS', 'GBRAIN_NO_RETRY_CONNECT', 'GBRAIN_DB_ACCESS',