Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(setup): scope the bootstrap-harness owner conflict to the configuration it wired; read Claude Code managed-settings hooks (#7771, #8057)
garrytan27ee7b7f5944
diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex c512a2d86a..ac09da929e 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -23,7 +23,7 @@* Engine-free: setup never opens the database itself.*/import { realpathSync } from 'node:fs';-import { dirname, join } from 'node:path';+import { dirname, join, resolve } from 'node:path';import { removeHermesTurnHook, syncHermesTurnHook } from '../core/setup/hermes-turn-hook.ts';import { removeOpenclawTurnPlugin, syncOpenclawTurnPlugin } from '../core/setup/openclaw-turn-plugin.ts';import { isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnRuleHarness } from '../core/setup/turn-hook.ts';@@ -436,8 +436,7 @@ export async function runSetup(args: string[]): Promise<number> {actor: 'agent', argv: ['gbrain', 'setup', 'claude-code', '--instructions-only', ...(flags.name === 'gbrain' ? [] : ['--name', flags.name]), ...(scope === 'project' ? ['--scope', 'project'] : [])],why: 'Keeps that entry and adds only the brain-first block and the per-turn hook, so its sessions are told to check gbrain first on every turn. Or preview a setup under another name (--name), or remove that entry yourself and run setup again.', verify: verifyDryRun('claude-code', flags.name) }), out);}- const harnessReceipt = readHarnessReceiptState(brainHome);- const harnessLane = harnessReceipt.state === 'ok' && harnessReceipt.receipt.targets.some((t) => t.host === 'claude-code');+ const harnessLane = harnessLaneWires(brainHome, 'claude-code', [dirname(claudeUserSettingsPath()), dirname(found.settingsPath)]);const laneEvents = found.otherLaneEvents.filter((e) => (plan.events as string[]).includes(e));if (harnessLane || laneEvents.length > 0) {return refuse(ownerConflict('harness_lane', `${harnessLane ? '`gbrain bootstrap harness` already wires Claude Code for this install' : `${found.settingsPath} already wires ${laneEvents.join(', ')} through another gbrain install lane`}; two lanes would fire every hook twice.`, {@@ -489,6 +488,23 @@ export async function runSetup(args: string[]): Promise<number> {}}+/**+ * #7771: whether `gbrain bootstrap harness` wired the configuration setup is+ * about to wire. One install can serve several HOMEs (or CODEX_HOMEs), so the+ * lane conflicts only through a target in one of `configDirs`, project-scoped+ * hooks (every configuration loads a project's), or a receipt that records+ * no paths for the host.+ */+function harnessLaneWires(brainHome: string, host: 'claude-code' | 'codex', configDirs: string[]): boolean {+ const state = readHarnessReceiptState(brainHome);+ if (state.state !== 'ok') return false;+ const targets = state.receipt.targets.filter((t) => t.host === host);+ if (targets.length === 0) return false;+ if (!targets.some((t) => t.path)) return true;+ const dirs = new Set(configDirs.map((d) => resolve(d)));+ return targets.some((t) => (t.kind === 'hooks' && t.scope !== 'user') || (!!t.path && dirs.has(dirname(resolve(t.path)))));+}+function liveOwnerOf(cfg: GBrainConfig | null, ours: boolean): { dataDir?: string; liveOwner: Target['live_owner'] } {const dataDir = cfg && cfg.engine === 'pglite' && !cfg.database_url ? cfg.database_path ?? gbrainPath('brain.pglite') : undefined;const lock = dataDir ? peekLock(dataDir) : null;@@ -586,8 +602,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConactor: 'agent', argv: ['gbrain', 'setup', 'codex', '--instructions-only', ...(flags.name === 'gbrain' ? [] : ['--name', flags.name])],why: 'Keeps that table and adds only the brain-first block and the per-turn hook, so its sessions are told to check gbrain first on every turn. Or preview a setup under another name (--name), or remove that table yourself and run setup again.', verify: verifyDryRun('codex', flags.name) }), out);}- const harnessReceipt = readHarnessReceiptState(brainHome);- const harnessLane = harnessReceipt.state === 'ok' && harnessReceipt.receipt.targets.some((t) => t.host === 'codex');+ const harnessLane = harnessLaneWires(brainHome, 'codex', [dirname(found.configPath), dirname(found.hooksPath)]);const laneEvents = found.otherLaneEvents.filter((e) => (plan.events as string[]).includes(e));if (harnessLane || laneEvents.length > 0) {return refuse(ownerConflict('harness_lane', `${harnessLane ? '`gbrain bootstrap harness` already wires Codex for this install' : `${found.hooksPath} already wires ${laneEvents.join(', ')} through gbrain's bootstrap Codex lane`}; two lanes would fire every hook twice.`, {diff --git a/src/core/bootstrap/host-specs.ts b/src/core/bootstrap/host-specs.tsindex 1b41a172f3..ec05b2b2df 100644--- a/src/core/bootstrap/host-specs.ts+++ b/src/core/bootstrap/host-specs.ts@@ -19,7 +19,7 @@* gbrain code.*/-import { existsSync } from 'node:fs';+import { existsSync, readdirSync } from 'node:fs';import { homedir } from 'node:os';import { basename, dirname, join } from 'node:path';@@ -284,6 +284,24 @@ export function claudeUserSettingsPath(): string {return join(claudeConfigBase(), 'settings.json');}+function claudeManagedSettingsDir(): string {+ if (process.platform === 'darwin') return '/Library/Application Support/ClaudeCode';+ if (process.platform === 'win32') return 'C:\\Program Files\\ClaudeCode';+ return '/etc/claude-code';+}++/**+ * #8057: Claude Code's managed settings, which apply to every session on the+ * machine: managed-settings.json, then its managed-settings.d/*.json drop-ins+ * in name order. `dir` defaults to the platform's system directory.+ */+export function claudeManagedSettingsPaths(dir = claudeManagedSettingsDir()): string[] {+ const dropIns = join(dir, 'managed-settings.d');+ let names: string[] = [];+ try { names = readdirSync(dropIns).filter((n) => n.endsWith('.json')).sort(); } catch { /* no drop-in directory */ }+ return [join(dir, 'managed-settings.json'), ...names.map((n) => join(dropIns, n))];+}+/*** #4325: the config-dir base itself, exported for detection — a machine with* a `~/.claude` (or CLAUDE_CONFIG_DIR) directory has Claude Code configureddiff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.tsindex f7afbeb741..0f4dbbe216 100644--- a/src/core/setup/turn-hook-check.ts+++ b/src/core/setup/turn-hook-check.ts@@ -18,7 +18,7 @@ import { bunSpawnSync } from '../spawn.ts';import { codexHookCensus, codexHookGroupRuns, codexHookTrustHash } from '../bootstrap/codex-hooks.ts';import { readCodexTomlTable } from '../bootstrap/codex-toml.ts';import { classifyHarnessHook } from '../bootstrap/hooks.ts';-import { GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';+import { GBRAIN_HOOK_MARKER_KEY, claudeManagedSettingsPaths, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';import { enabledPluginLanes } from '../bootstrap/plugin-lanes.ts';import { brainFirstTarget, openclawConfigPath, parseJson5ish } from './brain-first.ts';import { inspectHermesTurnHook } from './hermes-turn-hook.ts';@@ -61,12 +61,12 @@ function claudeEntries(path: string): Array<Record<string, unknown>> {const isGbrainPromptEntry = (e: Record<string, unknown>) =>isTurnRuleEntry(e) || typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string' || !!classifyHarnessHook(e, 'UserPromptSubmit', 'any');-/** Files only, no process run. `projectDir`: a project-scope Claude Code install's directory. */-export function inspectTurnHook(harness: string, opts: { projectDir?: string } = {}): TurnHookState {+/** Files only, no process run. `projectDir`: a project-scope Claude Code install's directory; `managedDir`: Claude Code's managed-settings directory (default: the system one). */+export function inspectTurnHook(harness: string, opts: { projectDir?: string; managedDir?: string } = {}): TurnHookState {const native_inspect = TURN_HOOK_NATIVE_INSPECT[harness];const plugin = enabledPluginLanes('gbrain').find((l) => l.harness === harness);if (harness === 'claude-code') {- const files = [claudeUserSettingsPath(), ...(opts.projectDir ? [join(opts.projectDir, '.claude', 'settings.local.json'), join(opts.projectDir, '.claude', 'settings.json')] : [])];+ const files = [claudeUserSettingsPath(), ...(opts.projectDir ? [join(opts.projectDir, '.claude', 'settings.local.json'), join(opts.projectDir, '.claude', 'settings.json')] : []), ...claudeManagedSettingsPaths(opts.managedDir)];for (const path of files) {const committed = !!opts.projectDir && path === join(opts.projectDir, '.claude', 'settings.json');const entries = claudeEntries(path).filter((e) => isTurnRuleEntry(e) || isOtherGbrainEntry(e, committed));diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.tsindex 8a007ed13d..73bd702ae7 100644--- a/src/core/setup/turn-hook.ts+++ b/src/core/setup/turn-hook.ts@@ -35,7 +35,7 @@ import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';import { codexHookCensus, codexHookGroupRuns, codexHookTrustHash, codexSetupHookGroup, codexSetupTrustEntry, writeCodexSetupHooks, type CodexHookGroup } from '../bootstrap/codex-hooks.ts';import { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable } from '../bootstrap/codex-toml.ts';import { buildClaudeHookCommand, classifyHarnessHook, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';-import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, GBRAIN_HOOK_MARKER_KEY, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';+import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, GBRAIN_HOOK_MARKER_KEY, claudeManagedSettingsPaths, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';export const TURN_RULE_LANE = 'turn-rule';export const TURN_RULE_MARKER = 'turn-rule-v1';@@ -110,14 +110,15 @@ export function isOtherGbrainEntry(e: Record<string, unknown>, committed = false* UserPromptSubmit for this harness, and that hook adds the same rule.* Fail-open (an unreadable file counts as not wired).*/-export function turnRuleHookYields(harness: string, cwd: string): boolean {+export function turnRuleHookYields(harness: string, cwd: string, managedDir?: string): boolean {if (harness === 'codex') {// Only a group Codex actually runs (trusted, enabled) carries the rule.try { return codexHookCensus(codexHooksPath()).some((g) => g.event === EVENT && (g.lane === 'setup' || g.lane === 'bootstrap') && codexHookGroupRuns(codexHooksPath(), codexConfigPath(), g)); } catch { return false; }}return claudePromptEntries(claudeUserSettingsPath()).some((e) => isOtherGbrainEntry(e))|| claudePromptEntries(join(cwd, '.claude', 'settings.local.json')).some((e) => isOtherGbrainEntry(e))- || claudePromptEntries(join(cwd, '.claude', 'settings.json')).some((e) => isOtherGbrainEntry(e, true));+ || claudePromptEntries(join(cwd, '.claude', 'settings.json')).some((e) => isOtherGbrainEntry(e, true))+ || claudeManagedSettingsPaths(managedDir).some((path) => claudePromptEntries(path).some((e) => isOtherGbrainEntry(e)));}/** Install or refresh the turn-rule hook. Never throws; anything it cannot write safely comes back as `print` with the command that wires it. */diff --git a/test/setup-harness-lane-scope-7771.test.ts b/test/setup-harness-lane-scope-7771.test.tsnew file mode 100644index 0000000000..5ad0f8e16e--- /dev/null+++ b/test/setup-harness-lane-scope-7771.test.ts@@ -0,0 +1,104 @@+import { afterAll, describe, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import type { HarnessTarget } from '../src/core/bootstrap/format.ts';+import { VERSION } from '../src/version.ts';++// #7771: one gbrain install (one GBRAIN_HOME) can serve two Claude Code or+// Codex configurations under different HOMEs. The bootstrap harness lane is+// an owner conflict for `gbrain setup` only when it wired the configuration+// setup is about to wire (or a project, which every configuration loads).++const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++function box() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-setup-lane-7771-'));+ roots.push(root);+ const home = join(root, 'home-b'); const other = join(root, 'home-a');+ mkdirSync(home, { recursive: true }); mkdirSync(other, { recursive: true });+ const bin = join(root, 'bin', 'gbrain');+ mkdirSync(join(root, 'bin'));+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ return { root, home, other, gbrainHome: join(root, 'gbrain-home'), bin };+}+type Box = ReturnType<typeof box>;++function writeHarnessReceipt(b: Box, targets: Array<Omit<HarnessTarget, 'state'>>) {+ const dir = join(b.gbrainHome, '.gbrain', 'bootstrap');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'harness.json'), JSON.stringify({+ harness_receipt_version: 1, created_at: new Date().toISOString(), created_by: `gbrain@${VERSION}`,+ url: 'http://192.0.2.1:9/mcp', source_id: 'default', token: { name: 'bootstrap-harness', minted: false },+ targets: targets.map((t) => ({ state: 'confirmed', ...t })),+ }));+}++const claudeTargets = (home: string, hooksScope = 'user', hooksPath = join(home, '.claude', 'settings.json')): Array<Omit<HarnessTarget, 'state'>> => [+ { host: 'claude-code', kind: 'mcp', scope: 'user', name: 'gbrain', mechanism: 'claude-cli' },+ { host: 'claude-code', kind: 'permission', scope: 'user', path: join(home, '.claude', 'settings.json'), entry: 'mcp__gbrain' },+ { host: 'claude-code', kind: 'hooks', scope: hooksScope, path: hooksPath, marker: 'bootstrap-v1' },+];+const codexTargets = (home: string): Array<Omit<HarnessTarget, 'state'>> => [+ { host: 'codex', kind: 'mcp', scope: 'user', path: join(home, '.codex', 'config.toml'), name: 'gbrain', mechanism: 'toml-block' },+];++async function setup(b: Box, args: string[]) {+ const r = await runCli(['setup', ...args, '--dry-run', '--json', '--gbrain-bin', b.bin], {+ env: { CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, HOME: b.home, GBRAIN_HOME: b.gbrainHome },+ });+ let doc: any = null;+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }+ return { ...r, doc };+}++describe('setup: bootstrap harness lane scoped to the configuration it wired (#7771)', () => {+ test('claude-code: a harness lane wired under another HOME does not block setup', async () => {+ const b = box();+ writeHarnessReceipt(b, claudeTargets(b.other));+ const r = await setup(b, ['claude-code']);+ expect(r.doc?.reason).not.toBe('harness_lane');+ expect(r.exitCode).toBe(0);+ });++ test('claude-code: a harness lane wired in this HOME still refuses', async () => {+ const b = box();+ writeHarnessReceipt(b, claudeTargets(b.home));+ const r = await setup(b, ['claude-code']);+ expect(r.exitCode).toBe(1);+ expect(r.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'harness_lane' });+ });++ test('claude-code: project-scoped harness hooks refuse from any HOME (every configuration loads a project)', async () => {+ const b = box();+ writeHarnessReceipt(b, claudeTargets(b.other, join(b.root, 'project'), join(b.root, 'project', '.claude', 'settings.json')));+ const r = await setup(b, ['claude-code']);+ expect(r.exitCode).toBe(1);+ expect(r.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'harness_lane' });+ });++ test('claude-code: a receipt whose targets record no paths still refuses', async () => {+ const b = box();+ writeHarnessReceipt(b, [{ host: 'claude-code', kind: 'mcp', scope: 'user', name: 'gbrain', mechanism: 'claude-cli' }]);+ const r = await setup(b, ['claude-code']);+ expect(r.exitCode).toBe(1);+ expect(r.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'harness_lane' });+ });++ test('codex: a harness lane wired under another CODEX_HOME does not block setup; the same one refuses', async () => {+ const elsewhere = box();+ writeHarnessReceipt(elsewhere, codexTargets(elsewhere.other));+ const ok = await setup(elsewhere, ['codex']);+ expect(ok.doc?.reason).not.toBe('harness_lane');+ expect(ok.exitCode).toBe(0);+ const same = box();+ writeHarnessReceipt(same, codexTargets(same.home));+ const refused = await setup(same, ['codex']);+ expect(refused.exitCode).toBe(1);+ expect(refused.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'harness_lane' });+ });+});diff --git a/test/turn-hook-managed-settings-8057.test.ts b/test/turn-hook-managed-settings-8057.test.tsnew file mode 100644index 0000000000..b4c0757f4e--- /dev/null+++ b/test/turn-hook-managed-settings-8057.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { withEnv } from './helpers/with-env.ts';+import { claudeManagedSettingsPaths } from '../src/core/bootstrap/host-specs.ts';+import { inspectTurnHook } from '../src/core/setup/turn-hook-check.ts';+import { turnRuleHookYields } from '../src/core/setup/turn-hook.ts';++// #8057: Claude Code also reads hooks from its managed settings+// (managed-settings.json and managed-settings.d/*.json in the system+// directory). A gbrain UserPromptSubmit hook there wires every session.++const promptHook = { hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: '/opt/gbrain/bin/gbrain hook user-prompt', _gbrain: 'setup-v1' }] }] } };++function sandbox() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-managed-8057-'));+ const home = join(root, 'home'); const managed = join(root, 'managed'); const project = join(root, 'project');+ for (const d of [join(home, '.claude'), managed, project]) mkdirSync(d, { recursive: true });+ writeFileSync(join(home, '.claude', 'settings.json'), '{}');+ const env = { HOME: home, CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: join(home, '.codex') };+ return { home, managed, project, env };+}++describe('Claude Code managed-settings hooks (#8057)', () => {+ test('a gbrain UserPromptSubmit hook in managed-settings.json counts as wired', async () => {+ const s = sandbox();+ writeFileSync(join(s.managed, 'managed-settings.json'), JSON.stringify(promptHook));+ await withEnv(s.env, async () => {+ const state = inspectTurnHook('claude-code', { managedDir: s.managed });+ expect(state.state).toBe('wired');+ expect(state.source).toBe(join(s.managed, 'managed-settings.json'));+ expect(turnRuleHookYields('claude-code', s.project, s.managed)).toBe(true);+ });+ });++ test('a drop-in under managed-settings.d counts as wired', async () => {+ const s = sandbox();+ mkdirSync(join(s.managed, 'managed-settings.d'));+ writeFileSync(join(s.managed, 'managed-settings.d', '10-gbrain.json'), JSON.stringify(promptHook));+ await withEnv(s.env, async () => {+ expect(inspectTurnHook('claude-code', { managedDir: s.managed }).state).toBe('wired');+ expect(turnRuleHookYields('claude-code', s.project, s.managed)).toBe(true);+ });+ });++ test('no managed hook: still missing, the turn-rule lane does not yield, and the message names the managed file', async () => {+ const s = sandbox();+ writeFileSync(join(s.managed, 'managed-settings.json'), JSON.stringify({ permissions: { allow: [] } }));+ await withEnv(s.env, async () => {+ const state = inspectTurnHook('claude-code', { managedDir: s.managed });+ expect(state.state).toBe('missing');+ expect(state.detail).toContain(join(s.managed, 'managed-settings.json'));+ expect(turnRuleHookYields('claude-code', s.project, s.managed)).toBe(false);+ });+ });++ test('the default managed directory is the platform system path', () => {+ const [file] = claudeManagedSettingsPaths();+ expect(file.endsWith('managed-settings.json')).toBe(true);+ if (process.platform === 'linux') expect(file).toBe('/etc/claude-code/managed-settings.json');+ if (process.platform === 'darwin') expect(file).toBe('/Library/Application Support/ClaudeCode/managed-settings.json');+ });+});