Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: adversarial review fixes (symlinked HOME lane scope, loops notice on read failure, managed turn-rule yield)

garrytanbe5ce8c33557
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 17e7f22079..1d36b55fc6 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, resolve } from 'node:path';
+import { basename, 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 { hasTurnRuleHook, isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnRuleHarness } from '../core/setup/turn-hook.ts';
@@ -501,9 +501,13 @@ function harnessLaneWires(brainHome: string, host: 'claude-code' | 'codex', conf
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)))));
+ if (!targets.some((t) => typeof t.path === 'string')) return true;
+ const real = (p: string): string => {
+ const abs = resolve(p);
+ try { return realpathSync(abs); } catch { return dirname(abs) === abs ? abs : join(real(dirname(abs)), basename(abs)); }
+ };
+ const dirs = new Set(configDirs.map(real));
+ return targets.some((t) => (t.kind === 'hooks' && t.scope !== 'user') || (typeof t.path === 'string' && dirs.has(real(dirname(resolve(t.path))))));
}
function liveOwnerOf(cfg: GBrainConfig | null, ours: boolean): { dataDir?: string; liveOwner: Target['live_owner'] } {
diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.ts
index 98347ae115..3d74e6c328 100644
--- a/src/core/ops/loops.ts
+++ b/src/core/ops/loops.ts
@@ -69,7 +69,7 @@ interface GoogleSourceFreshness {
async function googleSourceFreshness(
ctx: OperationContext,
scope: { sourceId?: string; sourceIds?: string[] },
-): Promise<{ sources: GoogleSourceFreshness[]; stale: boolean; staleSources: string[] }> {
+): Promise<{ sources: GoogleSourceFreshness[]; stale: boolean; staleSources: string[]; failed?: true }> {
try {
const rows = await ctx.engine.executeRaw<{ id: string; last_sync_at: string | null; config: unknown }>(
`SELECT id, last_sync_at, config FROM sources WHERE archived IS NOT TRUE`,
@@ -101,7 +101,7 @@ async function googleSourceFreshness(
// Fail TOWARD stale: this surface's invariant is "stale-but-confident is
// worse than nothing" — a DB error must not present confident output
// with the stale warning suppressed.
- return { sources: [], stale: true, staleSources: [] };
+ return { sources: [], stale: true, staleSources: [], failed: true };
}
}
@@ -485,7 +485,7 @@ const open_loops: Operation = {
});
const freshness = await googleSourceFreshness(ctx, scope);
const noGoogleSources = freshness.sources.length === 0;
- if (!trusted && noGoogleSources) ctx.emitNotice?.(noGoogleInScopeNotice(scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : [])));
+ if (!trusted && noGoogleSources && !freshness.failed && loops.length === 0) ctx.emitNotice?.(noGoogleInScopeNotice(scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : [])));
const partialStaleSources = freshness.stale ? [] : freshness.staleSources;
const coverage = await heldCoverage(ctx, freshness.sources, trusted);
const deepLinks = trusted ? await deepLinksFor(ctx, loops) : new Map<string, string>();
diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.ts
index c23d50692a..6347b3c4b0 100644
--- a/src/core/setup/turn-hook-check.ts
+++ b/src/core/setup/turn-hook-check.ts
@@ -234,7 +234,7 @@ export function verifyTurnHook(harness: string, opts: { projectDir?: string; run
if (state.via === 'plugin') return { ok: true, state, reason: 'plugin_lane', message: `${state.detail}; check it with ${state.native_inspect}` };
if ((harness === 'claude-code' || harness === 'codex') && state.command) {
// A command from a project's settings file is the repo's, not the user's: never run it.
- if (harness === 'claude-code' && state.source !== claudeUserSettingsPath()) return { ok: true, state, reason: 'project_unverified', message: `${state.detail}; a project hook is not run here, so check it with ${state.native_inspect}` };
+ if (harness === 'claude-code' && state.source !== claudeUserSettingsPath()) return { ok: true, state, reason: 'project_unverified', message: `${state.detail}; a hook outside the user settings file (project or managed) is not run here, so check it with ${state.native_inspect}` };
const r = run(['sh', '-c', state.command], JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: '', session_id: 'gbrain-install-check' }));
if (!r.ok) return fail('hook_failed', `the UserPromptSubmit hook exited non-zero (${r.output.trim().split('\n').at(-1) || 'no output'})`);
if (!r.output.includes('GBrain: before answering')) return fail('no_rule', 'the UserPromptSubmit hook ran but did not add the brain-first rule (is the brain-first block installed for this harness?)');
diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.ts
index 648fd2f00a..c613eb7fcb 100644
--- a/src/core/setup/turn-hook.ts
+++ b/src/core/setup/turn-hook.ts
@@ -123,7 +123,7 @@ export function turnRuleHookYields(harness: string, cwd: string, managedDir?: st
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))
- || claudeManagedSettingsPaths(managedDir).some((path) => claudePromptEntries(path).some((e) => isOtherGbrainEntry(e)));
+ || claudeManagedSettingsPaths(managedDir).some((path) => claudePromptEntries(path).some((e) => isTurnRuleEntry(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/loops-remote-scope-notice-7286.test.ts b/test/loops-remote-scope-notice-7286.test.ts
index e084309e22..54e81d384f 100644
--- a/test/loops-remote-scope-notice-7286.test.ts
+++ b/test/loops-remote-scope-notice-7286.test.ts
@@ -70,6 +70,18 @@ describe('#7286 open_loops for a remote caller bound to a non-google source', ()
expect(notices.map(n => n.code)).not.toContain('loops_no_google_in_scope');
});
+ test('a failed google-source read carries no such notice (it is not a grant problem)', async () => {
+ const notices: Notice[] = [];
+ const failing = new Proxy(engine, { get(t, k, r) {
+ if (k === 'executeRaw') return (sql: string, params?: unknown[]) => /FROM sources WHERE archived/.test(sql) ? Promise.reject(new Error('connection reset')) : t.executeRaw(sql, params as never);
+ const v = Reflect.get(t, k, r); return typeof v === 'function' ? v.bind(t) : v;
+ } });
+ const ctx = { engine: failing, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'source-a',
+ emitNotice: (n: Notice) => notices.push(n) } as unknown as OperationContext;
+ await openLoops.handler(ctx, {});
+ expect(notices.map(n => n.code)).not.toContain('loops_no_google_in_scope');
+ });
+
test('names the sources it read, not the whole grant, when source_id narrows a federated read', async () => {
await engine.executeRaw(`INSERT INTO sources (id, name, config, last_sync_at) VALUES ('mail-a', 'mail-a', '{"kind":"google"}'::jsonb, now()), ('notes-a', 'notes-a', '{}'::jsonb, NULL) ON CONFLICT (id) DO NOTHING`);
const notices: Notice[] = [];
diff --git a/test/setup-harness-lane-scope-7771.test.ts b/test/setup-harness-lane-scope-7771.test.ts
index 5ad0f8e16e..a24bf54940 100644
--- a/test/setup-harness-lane-scope-7771.test.ts
+++ b/test/setup-harness-lane-scope-7771.test.ts
@@ -1,5 +1,5 @@
import { afterAll, describe, expect, test } from 'bun:test';
-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { runCli } from './helpers/cli-spawn.ts';
@@ -73,6 +73,16 @@ describe('setup: bootstrap harness lane scoped to the configuration it wired (#7
expect(r.doc).toMatchObject({ code: 'setup_owner_conflict', reason: 'harness_lane' });
});
+ test('claude-code: a harness lane wired through another spelling of this HOME (a symlink) still refuses', async () => {
+ const b = box();
+ writeHarnessReceipt(b, claudeTargets(b.home));
+ const link = join(b.root, 'home-link');
+ symlinkSync(b.home, link);
+ const r = await setup({ ...b, home: link }, ['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')));
diff --git a/test/turn-hook-managed-settings-8057.test.ts b/test/turn-hook-managed-settings-8057.test.ts
index b4c0757f4e..b20fc8446e 100644
--- a/test/turn-hook-managed-settings-8057.test.ts
+++ b/test/turn-hook-managed-settings-8057.test.ts
@@ -55,6 +55,15 @@ describe('Claude Code managed-settings hooks (#8057)', () => {
});
});
+ test('a gbrain turn-rule hook in managed settings makes the user turn-rule lane yield', async () => {
+ const s = sandbox();
+ const turnRule = { hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: '/opt/gbrain/bin/gbrain hook user-prompt', _gbrain: 'turn-rule-v1' }] }] } };
+ writeFileSync(join(s.managed, 'managed-settings.json'), JSON.stringify(turnRule));
+ await withEnv(s.env, async () => {
+ expect(turnRuleHookYields('claude-code', s.project, s.managed)).toBe(true);
+ });
+ });
+
test('the default managed directory is the platform system path', () => {
const [file] = claudeManagedSettingsPaths();
expect(file.endsWith('managed-settings.json')).toBe(true);