Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(security): MCP serve starts through the hook launcher; serve reads the session dir from GBRAIN_HOOK_CWD (#8426)

garrytand578d40528a4
diff --git a/.agents/gbrain-launcher b/.agents/gbrain-launcher
index bc5b5a4772..711ee51ba1 100755
--- a/.agents/gbrain-launcher
+++ b/.agents/gbrain-launcher
@@ -19,7 +19,8 @@
# install. On a miss this exits 127 with the recovery path on stderr; the
# bundled `setup` skill walks the install interactively.
#
-# `hook …` (the plugin's per-turn hook) is the exception: on a miss it exits 0
+# `hook …` (the plugin's per-turn hook) is the exception: it runs from this
+# launcher's directory with the session directory in GBRAIN_HOOK_CWD, and on a miss it exits 0
# with no output, so a plugin-first install without the CLI shows no hook
# error on every turn. With GBRAIN_HOOK_LANE=plugin it also exits 0 silently
# when the binary predates the plugin lane (PLUGIN_LANE_MIN): such a CLI
@@ -35,6 +36,19 @@ PLUGIN_LANE_MIN=0.60.498.0
HOOK=0
[ "${1:-}" = "hook" ] && HOOK=1
+# Hooks start in the session's directory, where a script-mode gbrain (and
+# the version probe below) would load that directory's bunfig.toml and .env
+# (#8428). Record it in GBRAIN_HOOK_CWD, which `gbrain hook` reads as the
+# session directory, and run from this launcher's own directory instead.
+if [ "$HOOK" = 1 ]; then
+ GBRAIN_HOOK_CWD=$PWD
+ export GBRAIN_HOOK_CWD
+ case "$0" in
+ /*/*) cd "${0%/*}" || exit 0 ;;
+ *) exit 0 ;;
+ esac
+fi
+
resolve_bin() {
if [ -n "${GBRAIN_BIN:-}" ]; then
if [ ! -x "$GBRAIN_BIN" ]; then
diff --git a/plugin-variants/gbrain-coding/.agents/gbrain-launcher b/plugin-variants/gbrain-coding/.agents/gbrain-launcher
index bc5b5a4772..711ee51ba1 100755
--- a/plugin-variants/gbrain-coding/.agents/gbrain-launcher
+++ b/plugin-variants/gbrain-coding/.agents/gbrain-launcher
@@ -19,7 +19,8 @@
# install. On a miss this exits 127 with the recovery path on stderr; the
# bundled `setup` skill walks the install interactively.
#
-# `hook …` (the plugin's per-turn hook) is the exception: on a miss it exits 0
+# `hook …` (the plugin's per-turn hook) is the exception: it runs from this
+# launcher's directory with the session directory in GBRAIN_HOOK_CWD, and on a miss it exits 0
# with no output, so a plugin-first install without the CLI shows no hook
# error on every turn. With GBRAIN_HOOK_LANE=plugin it also exits 0 silently
# when the binary predates the plugin lane (PLUGIN_LANE_MIN): such a CLI
@@ -35,6 +36,19 @@ PLUGIN_LANE_MIN=0.60.498.0
HOOK=0
[ "${1:-}" = "hook" ] && HOOK=1
+# Hooks start in the session's directory, where a script-mode gbrain (and
+# the version probe below) would load that directory's bunfig.toml and .env
+# (#8428). Record it in GBRAIN_HOOK_CWD, which `gbrain hook` reads as the
+# session directory, and run from this launcher's own directory instead.
+if [ "$HOOK" = 1 ]; then
+ GBRAIN_HOOK_CWD=$PWD
+ export GBRAIN_HOOK_CWD
+ case "$0" in
+ /*/*) cd "${0%/*}" || exit 0 ;;
+ *) exit 0 ;;
+ esac
+fi
+
resolve_bin() {
if [ -n "${GBRAIN_BIN:-}" ]; then
if [ ! -x "$GBRAIN_BIN" ]; then
diff --git a/plugin-variants/gbrain-daily/.agents/gbrain-launcher b/plugin-variants/gbrain-daily/.agents/gbrain-launcher
index bc5b5a4772..711ee51ba1 100755
--- a/plugin-variants/gbrain-daily/.agents/gbrain-launcher
+++ b/plugin-variants/gbrain-daily/.agents/gbrain-launcher
@@ -19,7 +19,8 @@
# install. On a miss this exits 127 with the recovery path on stderr; the
# bundled `setup` skill walks the install interactively.
#
-# `hook …` (the plugin's per-turn hook) is the exception: on a miss it exits 0
+# `hook …` (the plugin's per-turn hook) is the exception: it runs from this
+# launcher's directory with the session directory in GBRAIN_HOOK_CWD, and on a miss it exits 0
# with no output, so a plugin-first install without the CLI shows no hook
# error on every turn. With GBRAIN_HOOK_LANE=plugin it also exits 0 silently
# when the binary predates the plugin lane (PLUGIN_LANE_MIN): such a CLI
@@ -35,6 +36,19 @@ PLUGIN_LANE_MIN=0.60.498.0
HOOK=0
[ "${1:-}" = "hook" ] && HOOK=1
+# Hooks start in the session's directory, where a script-mode gbrain (and
+# the version probe below) would load that directory's bunfig.toml and .env
+# (#8428). Record it in GBRAIN_HOOK_CWD, which `gbrain hook` reads as the
+# session directory, and run from this launcher's own directory instead.
+if [ "$HOOK" = 1 ]; then
+ GBRAIN_HOOK_CWD=$PWD
+ export GBRAIN_HOOK_CWD
+ case "$0" in
+ /*/*) cd "${0%/*}" || exit 0 ;;
+ *) exit 0 ;;
+ esac
+fi
+
resolve_bin() {
if [ -n "${GBRAIN_BIN:-}" ]; then
if [ ! -x "$GBRAIN_BIN" ]; then
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 4b163a364f..674037abc6 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -29,6 +29,7 @@ import {
shouldEmitDbAccessMarker,
} from '../core/pg-access-classify.ts';
import { resolveBrainId as resolveBrainIdForDbMarker } from '../core/brain-resolver.ts';
+import { captureHookSessionCwd } from '../core/session-cwd.ts';
import type { GBrainConfig } from '../core/config.ts';
import type { AIGatewayConfig } from '../core/ai/types.ts';
import type { BrainEngine } from '../core/engine.ts';
@@ -317,6 +318,8 @@ async function main() {
let command = args[0];
installCliRoutingFor(() => command, args);
+ // #8426: a serve the hook launcher started reads the session directory from GBRAIN_HOOK_CWD, before any brain or source resolution.
+ if (command === 'serve') captureHookSessionCwd();
if (!command || command === '--help' || command === '-h') {
printHelp();
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index 394f05773a..5b15dbf651 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -64,6 +64,7 @@ import {
removeClaudeHooks,
} from '../core/bootstrap/hooks.ts';
import { removeCodexHooks, writeCodexHooks } from '../core/bootstrap/codex-hooks.ts';
+import { ensureHookLauncher, hookLauncherPath } from '../core/setup/hook-launcher.ts';
import { isRegistrationSurface, registeredAdvertise, registeredSurface, REGISTRATION_ADVERTISE, REGISTRATION_SURFACE, registrationAdvertise, stdioServeArgv } from '../core/mcp-registration.ts';
import type { McpSurface } from '../mcp/surface.ts';
import {
@@ -397,6 +398,7 @@ async function verifyMcpTargetsWorkspace(
name: string,
gbrainBin: string,
sourceId: string,
+ hookLauncher?: string,
): Promise<{ verdict: 'match' | 'mismatch' | 'unknown'; surface?: McpSurface | null; advertise?: McpSurface | null }> {
// Exec-lane harnesses only. opencode registrations go through the direct
// JSONC writer whose 4-state fingerprint IS the [FIX7] check (structural,
@@ -417,7 +419,7 @@ async function verifyMcpTargetsWorkspace(
if (res.code !== 0) return { verdict: 'unknown' };
const out = `${res.stdout}\n${res.stderr}`;
if (out.trim() === '') return { verdict: 'unknown' };
- const hasBin = out.includes(gbrainBin);
+ const hasBin = out.includes(gbrainBin) && (!hookLauncher || out.includes(hookLauncher));
const hasSource = out.includes(`GBRAIN_SOURCE=${sourceId}`);
return { verdict: hasBin && hasSource ? 'match' : 'mismatch', surface: registeredSurface(out), advertise: registeredAdvertise(out) };
}
@@ -1436,10 +1438,15 @@ async function runHooks(
'workspace-bound registration with `--mcp-even-if-plugin`.',
);
}
+ // A user-scope stdio server starts through the launcher, never in the session's directory (#8426).
+ const hookLauncher = harness === 'codex' || mcpScope === 'user' ? hookLauncherPath() : undefined;
const buildArgvs = (surface?: McpSurface | null, advertise?: McpSurface | null) => harness === 'claude-code'
- ? registerClaudeMcp({ gbrainBin, scope: mcpScope, sourceId, surface, advertise, ...(gbrainHome ? { gbrainHome } : {}) })
- : registerCodexMcp({ gbrainBin, sourceId, surface, advertise, ...(gbrainHome ? { gbrainHome } : {}) });
+ ? registerClaudeMcp({ gbrainBin, scope: mcpScope, sourceId, surface, advertise, ...(gbrainHome ? { gbrainHome } : {}), ...(hookLauncher ? { hookLauncher } : {}) })
+ : registerCodexMcp({ gbrainBin, sourceId, surface, advertise, ...(gbrainHome ? { gbrainHome } : {}), ...(hookLauncher ? { hookLauncher } : {}) });
const argvs = mcpPluginOwned ? [] : buildArgvs(surfaceFlag ?? undefined, registrationAdvertise({ userChoseSurface: surfaceFlag !== null }));
+ if (argvs.length && hookLauncher) {
+ try { ensureHookLauncher(hookLauncher); } catch (e) { console.error(`MCP registration skipped: ${(e as Error).message}`); return 1; }
+ }
for (const argv of argvs) {
const mcpName = argv[3] ?? 'gbrain'; // ['<host>','mcp','add',<name>,…]
const res = await runner(argv);
@@ -1461,7 +1468,7 @@ async function runHooks(
// [FIX7] "already registered" is NOT proof the registration is OURS.
// Verify it targets this workspace's serve; if it points elsewhere,
// remove + re-add rather than blessing a foreign/stale registration.
- const { verdict, surface: priorSurface, advertise: priorAdvertise } = await verifyMcpTargetsWorkspace(runner, harness, mcpName, gbrainBin, sourceId);
+ const { verdict, surface: priorSurface, advertise: priorAdvertise } = await verifyMcpTargetsWorkspace(runner, harness, mcpName, gbrainBin, sourceId, hookLauncher);
if (verdict === 'match') {
console.log('MCP server already registered for this workspace — kept.');
} else if (verdict === 'mismatch') {
@@ -1497,7 +1504,7 @@ async function runHooks(
// is NOT ours. Re-verify and abort rather than bless a foreign
// endpoint that would intercept memory ops. (Only the recorded
// warn-then-continue step-2 smoke did this before; here it's fatal.)
- const post = (await verifyMcpTargetsWorkspace(runner, harness, mcpName, gbrainBin, sourceId)).verdict;
+ const post = (await verifyMcpTargetsWorkspace(runner, harness, mcpName, gbrainBin, sourceId, hookLauncher)).verdict;
if (post === 'mismatch') {
console.error(
`after replacing '${mcpName}', it STILL targets a different workspace/binary — ` +
@@ -1524,7 +1531,7 @@ async function runHooks(
if (!mcpSkipped && !mcpPluginOwned) try {
const listBin = harness === 'claude-code' ? 'claude' : 'codex';
const scopeLabel = harness === 'claude-code' ? mcpScope : 'user-global';
- const { verdict } = await verifyMcpTargetsWorkspace(runner, harness, 'gbrain', gbrainBin, sourceId);
+ const { verdict } = await verifyMcpTargetsWorkspace(runner, harness, 'gbrain', gbrainBin, sourceId, harness === 'codex' || mcpScope === 'user' ? hookLauncherPath() : undefined);
if (verdict === 'match') {
console.log(`MCP registered with ${harness} (scope: ${scopeLabel}) — verified targeting this workspace.`);
} else if (verdict === 'mismatch') {
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 17ed30ad58..c12b7b5f18 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -37,6 +37,7 @@ import { writeJsonDocument } from '../core/cli-force-exit.ts';
import { configDir, gbrainPath, loadConfig, type GBrainConfig } from '../core/config.ts';
import { resolveGbrainBin } from '../core/gbrain-bin.ts';
import { isRegistrationSurface, isValidName, REGISTRATION_SURFACE, registrationAdvertise, stdioServeArgv } from '../core/mcp-registration.ts';
+import { hookLauncherPath } from '../core/setup/hook-launcher.ts';
import { isValidSourceId } from '../core/source-id.ts';
import { peekLock } from '../core/pglite-lock.ts';
import { claudePluginProvidesName, codexPluginProvidesName } from '../core/bootstrap/plugin-lanes.ts';
@@ -312,7 +313,7 @@ function describeTarget(t: Target, out: Out, harness: SetupHarnessId = 'claude-c
say(out, `Target (${HARNESS_LABEL[harness]}, ${t.scope} scope):`);
say(out, ` brain ${brain}`);
say(out, ` source ${t.source.id ? `'${t.source.id}' (pinned, from ${t.source.from === 'flag' ? '--source' : 'GBRAIN_SOURCE'})` : 'the brain\'s default source (unpinned)'}`);
- say(out, ` transport stdio MCP: ${stdioServeArgv(t.launcher, t.surface, t.advertise ?? null).join(' ')}${t.advertise ? ` (lists the ${t.advertise === 'verbs' ? 'memory verbs and request_tools' : `${t.advertise} tools`}; every ${t.surface} tool stays callable)` : ''}`);
+ say(out, ` transport stdio MCP: ${[hookLauncherPath(t.brain.config_dir), ...stdioServeArgv(t.launcher, t.surface, t.advertise ?? null)].join(' ')}${t.advertise ? ` (lists the ${t.advertise === 'verbs' ? 'memory verbs and request_tools' : `${t.advertise} tools`}; every ${t.surface} tool stays callable)` : ''}`);
say(out, ` owner ${t.registration_owner === 'setup' ? `this setup (${t.receipt_path})` : t.registration_owner === 'plugin' ? `the gbrain ${HARNESS_LABEL[harness]} plugin (MCP); setup adds hooks only` : `none yet; setup will own '${t.name}'`}`);
if (t.live_owner) say(out, ` live gbrain ${t.live_owner.transport === 'http' ? 'serve --http' : 'stdio serve'} PID ${t.live_owner.pid}${t.live_owner.ours ? ' (started by this registration)' : ''}`);
say(out, ` files ${t.config_path} (MCP${t.hooks_path ? ' + hook trust' : ''}), ${t.hooks_path ?? t.settings_path} (hooks)`);
@@ -416,7 +417,7 @@ export async function runSetup(args: string[]): Promise<number> {
if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags.name), out);
const pluginOwner = flags.name === 'gbrain' ? claudePluginProvidesName(claudeUserSettingsPath(), 'gbrain') : null;
- const { dataDir, liveOwner } = liveOwnerOf(cfg, prior?.status === 'installed' && found.mcp.state === 'current');
+ const { dataDir, liveOwner } = liveOwnerOf(cfg, prior?.status === 'installed' && (found.mcp.state === 'current' || found.mcp.state === 'owned'));
const target: Target = {
brain: !cfg ? { kind: 'new-local-pglite', path: gbrainPath('brain.pglite'), config_dir: brainHome }
: cfg.engine === 'pglite' ? { kind: 'local-pglite', path: dataDir, config_dir: brainHome } : { kind: 'local-postgres', config_dir: brainHome },
@@ -566,7 +567,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags.name, 'codex'), out);
const pluginOwner = codexPluginProvidesName(paths.configPath, flags.name);
- const { dataDir, liveOwner } = liveOwnerOf(cfg, prior?.status === 'installed' && found.mcp.state === 'current');
+ const { dataDir, liveOwner } = liveOwnerOf(cfg, prior?.status === 'installed' && (found.mcp.state === 'current' || found.mcp.state === 'owned'));
const target: Target = {
brain: !cfg ? { kind: 'new-local-pglite', path: gbrainPath('brain.pglite'), config_dir: brainHome }
: cfg.engine === 'pglite' ? { kind: 'local-pglite', path: dataDir, config_dir: brainHome } : { kind: 'local-postgres', config_dir: brainHome },
diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.ts
index 08f044d377..34a479edb9 100644
--- a/src/core/bootstrap/hooks.ts
+++ b/src/core/bootstrap/hooks.ts
@@ -1129,6 +1129,8 @@ export interface ClaudeMcpRegistration {
surface?: McpSurface | null;
/** `serve --advertise`; null lists the whole surface (registrationAdvertise decides). */
advertise?: McpSurface | null;
+ /** The trusted-directory launcher serve starts through (src/core/setup/hook-launcher.ts): the harness starts stdio servers in the session's directory (#8426). User scope only; a project file travels. */
+ hookLauncher?: string;
}
export type CodexMcpRegistration = Omit<ClaudeMcpRegistration, 'scope'>;
@@ -1156,7 +1158,7 @@ export function registerClaudeMcp(p: ClaudeMcpRegistration): string[][] {
'-e', `GBRAIN_SOURCE=${p.sourceId}`,
];
if (p.gbrainHome) argv.push('-e', `GBRAIN_HOME=${p.gbrainHome}`);
- argv.push('--', ...stdioServeArgv(p.gbrainBin, p.surface, p.advertise ?? null));
+ argv.push('--', ...(p.hookLauncher ? [p.hookLauncher] : []), ...stdioServeArgv(p.gbrainBin, p.surface, p.advertise ?? null));
return [argv];
}
@@ -1173,6 +1175,6 @@ export function registerCodexMcp(p: CodexMcpRegistration): string[][] {
const name = p.name ?? 'gbrain';
const argv = ['codex', 'mcp', 'add', name, '--env', `GBRAIN_SOURCE=${p.sourceId}`];
if (p.gbrainHome) argv.push('--env', `GBRAIN_HOME=${p.gbrainHome}`);
- argv.push('--', ...stdioServeArgv(p.gbrainBin, p.surface, p.advertise ?? null));
+ argv.push('--', ...(p.hookLauncher ? [p.hookLauncher] : []), ...stdioServeArgv(p.gbrainBin, p.surface, p.advertise ?? null));
return [argv];
}
diff --git a/src/core/brain-resolver.ts b/src/core/brain-resolver.ts
index cbe779fcaa..18c600a0c0 100644
--- a/src/core/brain-resolver.ts
+++ b/src/core/brain-resolver.ts
@@ -24,6 +24,7 @@ import { join, dirname, resolve } from 'path';
import { HOST_BRAIN_ID, loadMounts, validateMountId, type MountEntry } from './brain-registry.ts';
import { isTrustedDotfile, realpathOrResolve } from './path-confine.ts';
import { getCliOptions } from './cli-options.ts';
+import { hookSessionCwd } from './session-cwd.ts';
const DOTFILE = '.gbrain-mount';
/** Same regex as brain-registry. Kept in sync. */
@@ -95,7 +96,7 @@ function longestPathPrefixMount(mounts: MountEntry[], cwd: string): MountEntry |
*/
export function resolveBrainId(
explicit: string | null | undefined,
- cwd: string = process.cwd(),
+ cwd: string = hookSessionCwd(),
mountsLoader: () => MountEntry[] = loadMounts,
): string {
// 1. Explicit flag wins.
diff --git a/src/core/context-engine.ts b/src/core/context-engine.ts
index 528dfc7e48..cb874c0a51 100644
--- a/src/core/context-engine.ts
+++ b/src/core/context-engine.ts
@@ -22,6 +22,7 @@ import { backupNagReadOnlyConsult, backupNoticeText, loadBackupStatus } from './
import { estimateMessageTokens, openClawCoreLane } from './context/openclaw-core.ts';
import { TURN_CONTEXT_ENVELOPE } from './context/turn-context-envelope.ts';
import { loadContextModule } from './context/load-warning.ts';
+import { hookSessionCwd } from './session-cwd.ts';
// Types inlined from openclaw/plugin-sdk to avoid hard dependency during development.
// At runtime inside OpenClaw, the real SDK is available; these types ensure build compat.
@@ -967,7 +968,7 @@ export function createGBrainContextEngine(ctx: {
*/
resolveEntities?: ReflexResolveEntitiesFn;
}): ContextEngine {
- const workspaceDir = ctx.workspaceDir ?? process.cwd();
+ const workspaceDir = ctx.workspaceDir ?? hookSessionCwd();
// Warm the Postgres connection ahead of the first salient turn (no-op for
// PGLite/host paths). Fire-and-forget; never blocks engine construction.
warmReflex();
diff --git a/src/core/context/corpus-source.ts b/src/core/context/corpus-source.ts
index bebafbc467..b5288dc33d 100644
--- a/src/core/context/corpus-source.ts
+++ b/src/core/context/corpus-source.ts
@@ -50,6 +50,7 @@ import {
parseWbFileName,
sessionSourceFileName,
} from './corpus-segments.ts';
+import { hookSessionCwd } from '../session-cwd.ts';
export type SessionSourceTier = 'env' | 'dotfile' | 'serve' | 'engine' | 'operator';
@@ -155,7 +156,7 @@ async function engineFreeSessionSource(cwd: string | null): Promise<{ sourceId:
const { resolveSourceIdEngineFree } = await import('../source-resolver.ts');
let id: string | null;
try {
- id = resolveSourceIdEngineFree(null, cwd ?? process.cwd());
+ id = resolveSourceIdEngineFree(null, cwd ?? hookSessionCwd());
} catch {
return null;
}
diff --git a/src/core/ops/files.ts b/src/core/ops/files.ts
index 0881d8a071..dd819dd041 100644
--- a/src/core/ops/files.ts
+++ b/src/core/ops/files.ts
@@ -10,6 +10,7 @@ import { opError } from './contract.ts';
import { hostFix, readFix } from './op-fix.ts';
import { validateFilename, validatePageSlug, validateUploadPath } from './context.ts';
import { privatePagesFilterForCaller, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { hookSessionCwd } from '../session-cwd.ts';
// --- File Operations ---
@@ -80,7 +81,7 @@ const file_upload: Operation = {
// can upload from anywhere on the filesystem (loose) — the user owns the machine.
// Default is strict when ctx.remote is undefined (defense-in-depth).
const strict = ctx.remote !== false;
- validateUploadPath(filePath, process.cwd(), strict);
+ validateUploadPath(filePath, hookSessionCwd(), strict);
if (pageSlug) validatePageSlug(pageSlug);
const filename = basename(filePath);
validateFilename(filename);
diff --git a/src/core/ops/skillopt.ts b/src/core/ops/skillopt.ts
index f098a9295e..43afb4b2b8 100644
--- a/src/core/ops/skillopt.ts
+++ b/src/core/ops/skillopt.ts
@@ -11,6 +11,7 @@
import type { Operation } from './contract.ts';
import { opError } from './contract.ts';
import { hostFix, invalidParam, paramUse } from './op-fix.ts';
+import { hookSessionCwd } from '../session-cwd.ts';
// v0.41.18.0 (A7 + T16, codex finding #5): MCP op for federated / thin-client
// brain installs to drive `gbrain onboard --auto` over MCP. Admin scope
@@ -218,7 +219,7 @@ const run_skillopt: Operation = {
}
const skillsDir = sharedSkill
? await (await import('../shared-skills/optimizer.ts')).sharedOptimizerSkillsDir(ctx, sharedSkill.source_id, sharedSkill.source_incarnation)
- : autoDetectSkillsDirReadOnly(process.cwd()).dir;
+ : autoDetectSkillsDirReadOnly(hookSessionCwd()).dir;
if (!skillsDir) {
throw opError('config_error', 'run_skillopt: skills directory not found',
'The brain host has no skills directory to optimize. Run `gbrain doctor --json` on the host; it reports where gbrain looks for skills.');
diff --git a/src/core/readiness.ts b/src/core/readiness.ts
index 5dca7bb54b..0578472c2d 100644
--- a/src/core/readiness.ts
+++ b/src/core/readiness.ts
@@ -27,6 +27,7 @@ import type { GBrainConfig } from './config.ts';
import type { McpSurface } from '../mcp/surface.ts';
import { REGISTRATION_SURFACE, registrationAdvertise, stdioServeArgv } from './mcp-registration.ts';
import { gbrainPath } from './config.ts';
+import { hookLauncherPath } from './setup/hook-launcher.ts';
import type { BrainEngine } from './engine.ts';
import { redactForTransport, type Action, type ActionInput, type Effect, type Transport } from './agent-output.ts';
import { detectCapabilities } from './capability.ts';
@@ -414,11 +415,11 @@ const SURFACE_GLOSS: Record<McpSurface, string> = {
function stdioRegistration(h: ReadinessHarness, bin: string, chosen?: McpSurface): Action {
const surface = chosen ?? REGISTRATION_SURFACE;
const advertise = registrationAdvertise({ userChoseSurface: chosen !== undefined });
- const serve = stdioServeArgv(bin, surface, advertise);
- const argv = h === 'claude-code' ? ['claude', 'mcp', 'add', 'gbrain', '--', ...serve]
- : h === 'codex' ? ['codex', 'mcp', 'add', 'gbrain', '--', ...serve]
- : ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks', ...(chosen ? ['--surface', chosen] : [])];
- const hooks = h === 'opencode' ? ' No lifecycle hooks are installed (--no-hooks); it must run inside an initialized agent workspace.' : ' No hooks, tool pre-approvals or tokens are added.';
+ // Claude Code and Codex start stdio servers in the session's directory, so setup registers serve behind its launcher (#8426).
+ const serve = h === 'opencode' ? stdioServeArgv(bin, surface, advertise) : [hookLauncherPath(), ...stdioServeArgv(bin, surface, advertise)];
+ const argv = h === 'opencode' ? ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks', ...(chosen ? ['--surface', chosen] : [])]
+ : ['gbrain', 'setup', h, '--no-hooks', '--no-instructions', '--gbrain-bin', bin, ...(chosen ? ['--surface', chosen] : [])];
+ const hooks = h === 'opencode' ? ' No lifecycle hooks are installed (--no-hooks); it must run inside an initialized agent workspace.' : ' No hooks, instruction blocks, tool pre-approvals or tokens are added.';
return {
argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false,
why: `Registers gbrain as a stdio MCP server (${serve.join(' ')}, ${advertise ? `listing ${SURFACE_GLOSS[advertise]} and request_tools; ${SURFACE_GLOSS[surface]} stays callable` : SURFACE_GLOSS[surface]}) in ${HARNESS_DESTINATION[h]}, so new ${HARNESS_LABEL[h]} sessions get memory tools.${hooks}`,
@@ -464,7 +465,7 @@ export function harnessWiringEntry(input: HarnessWiringInput): ReadinessEntry {
if (harnesses.length === 0) {
return { ...base, state: 'missing', reason: 'no_harness_detected', why: 'No agent harness was detected.',
fix: { consent: ['persistent_install'], actor: 'user', requires_exclusive: false, docs: MEMORY_VERBS_INSTALL,
- why: `Register \`${stdioServeArgv('<absolute path to gbrain>', input.surface ?? REGISTRATION_SURFACE, registrationAdvertise({ userChoseSurface: input.surface !== undefined })).join(' ')}\` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw).`,
+ why: `For Claude Code or Codex, run \`gbrain setup claude-code\` or \`gbrain setup codex\` (it registers serve behind gbrain's launcher, so the session directory's bunfig.toml and .env never load). For any other host, register \`${stdioServeArgv('<absolute path to gbrain>', input.surface ?? REGISTRATION_SURFACE, registrationAdvertise({ userChoseSurface: input.surface !== undefined })).join(' ')}\` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw).`,
user_message: 'Which agent app should get gbrain memory? The install guide has a one-line command for each.' } };
}
if (lockOwner?.transport === 'http') {
diff --git a/src/core/repo-root.ts b/src/core/repo-root.ts
index 4f6e327e01..1032bdde5c 100644
--- a/src/core/repo-root.ts
+++ b/src/core/repo-root.ts
@@ -4,6 +4,7 @@ import { isAbsolute, join, resolve as resolvePath } from 'path';
import { RESOLVER_FILENAMES, hasResolverFile } from './resolver-filenames.ts';
import { isPathContained } from './path-confine.ts';
import { parseSkillFrontmatter } from './skill-frontmatter.ts';
+import { hookSessionCwd } from './session-cwd.ts';
/**
* Walk up from `startDir` looking for a `skills/` directory that
@@ -14,7 +15,7 @@ import { parseSkillFrontmatter } from './skill-frontmatter.ts';
* `startDir` is parameterized so tests can run hermetically against
* fixtures. Default matches the prior `doctor.ts`-private implementation.
*/
-export function findRepoRoot(startDir: string = process.cwd()): string | null {
+export function findRepoRoot(startDir: string = hookSessionCwd()): string | null {
let dir = startDir;
for (let i = 0; i < 10; i++) {
if (hasResolverFile(join(dir, 'skills'))) return dir;
@@ -154,7 +155,7 @@ function resolveWorkspaceSkillsDir(
* `startDir` + `env` params keep tests hermetic.
*/
export function autoDetectSkillsDir(
- startDir: string = process.cwd(),
+ startDir: string = hookSessionCwd(),
env: NodeJS.ProcessEnv = process.env,
): SkillsDirDetection {
// 0. $GBRAIN_SKILLS_DIR explicit operator override. Safe for all callers
@@ -275,7 +276,7 @@ function isGbrainRepoRoot(dir: string): boolean {
* blast radius to write-path callers.
*/
export function autoDetectSkillsDirReadOnly(
- startDir: string = process.cwd(),
+ startDir: string = hookSessionCwd(),
env: NodeJS.ProcessEnv = process.env,
): SkillsDirDetection {
if (env.GBRAIN_SKILLS_DIR) {
diff --git a/src/core/session-cwd.ts b/src/core/session-cwd.ts
new file mode 100644
index 0000000000..84957f28cc
--- /dev/null
+++ b/src/core/session-cwd.ts
@@ -0,0 +1,35 @@
+/**
+ * session-cwd.ts — the session directory for a gbrain process the hook
+ * launcher started (#8424, #8426). The launcher
+ * (src/core/setup/hook-launcher.ts) records the harness session's directory
+ * in GBRAIN_HOOK_CWD and starts gbrain from its own directory, so Bun never
+ * reads the session's bunfig.toml or .env. `gbrain hook` and `gbrain serve`
+ * capture it at start; every read that means "the user's working directory"
+ * (.gbrain-source, .gbrain-mount, the upload root, the skills dir) defaults
+ * to sessionCwd(), which is process.cwd() for every other command. Nothing
+ * here changes the process's working directory: a gbrain child started from
+ * the session directory would load its bunfig.toml again.
+ */
+import { realpathSync } from 'node:fs';
+
+export const HOOK_CWD_ENV = 'GBRAIN_HOOK_CWD';
+
+let capturedSessionCwd: string | null = null;
+
+/**
+ * Take the session directory the launcher recorded and drop it from the
+ * environment, so no child inherits a stale value. Resolved like
+ * process.cwd() (sh keeps a symlinked $PWD), so project matching against
+ * setup's realpath'd directories still holds.
+ */
+export function captureHookSessionCwd(): void {
+ const recorded = process.env[HOOK_CWD_ENV];
+ delete process.env[HOOK_CWD_ENV];
+ if (!recorded || !recorded.startsWith('/')) { capturedSessionCwd = null; return; }
+ try { capturedSessionCwd = realpathSync(recorded); } catch { capturedSessionCwd = recorded; }
+}
+
+/** The session directory: what the launcher recorded, else this process's directory. */
+export function hookSessionCwd(): string {
+ return capturedSessionCwd ?? process.cwd();
+}
diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.ts
index e12e9806b5..1263744a0d 100644
--- a/src/core/setup/claude-code.ts
+++ b/src/core/setup/claude-code.ts
@@ -179,7 +179,8 @@ export function desiredMcpEntry(plan: ClaudeSetupPlan): Record<string, unknown>
const env: Record<string, string> = {};
if (plan.gbrainHomeEnv) env.GBRAIN_HOME = plan.gbrainHomeEnv;
if (plan.sourceId) env.GBRAIN_SOURCE = plan.sourceId;
- return { type: 'stdio', command: plan.launcher, args: stdioServeArgv(plan.launcher, plan.surface, plan.advertise).slice(1), env };
+ // The harness starts stdio servers in the session's directory, so serve starts through the launcher too (#8426).
+ return { type: 'stdio', command: hookLauncherPath(plan.brainHome), args: stdioServeArgv(plan.launcher, plan.surface, plan.advertise), env };
}
export function desiredHookHashes(plan: ClaudeSetupPlan): HookHashes {
@@ -275,8 +276,8 @@ export async function applyClaudeSetup(
const paths = claudeSetupPaths(plan);
const lock = await acquireBootstrapLock(dirname(paths.configPath));
try {
- // Every hook command starts gbrain through the launcher, so it goes down before anything names it (#8424).
- if (plan.events.length) ensureHookLauncher(hookLauncherPath(plan.brainHome));
+ // The MCP entry and every hook command start gbrain through the launcher, so it goes down before anything names it (#8424, #8426).
+ ensureHookLauncher(hookLauncherPath(plan.brainHome));
const found = inspectClaudeSetup(plan);
if (opts.mcpMustBeCurrent && opts.pluginOwner === null && found.mcp.state !== 'current') throw new Error(`the '${plan.name}' MCP entry changed before the hooks were rewritten`);
const now = new Date().toISOString();
diff --git a/src/core/setup/codex.ts b/src/core/setup/codex.ts
index cb6f3861ac..5f0348d0db 100644
--- a/src/core/setup/codex.ts
+++ b/src/core/setup/codex.ts
@@ -136,11 +136,12 @@ export function readCodexSetupReceipt(receiptPath: string): { setup: CodexSetupR
const writeReceipt = (path: string, receipt: CodexSetupReceipt) => atomicWriteTextFile(path, `${JSON.stringify(receipt, null, 2)}\n`, { forceMode: 0o600 });
-export function desiredCodexMcpEntry(plan: Pick<CodexSetupPlan, 'launcher' | 'surface' | 'advertise' | 'gbrainHomeEnv' | 'sourceId'>): Record<string, CodexTomlValue> {
+export function desiredCodexMcpEntry(plan: Pick<CodexSetupPlan, 'launcher' | 'brainHome' | 'surface' | 'advertise' | 'gbrainHomeEnv' | 'sourceId'>): Record<string, CodexTomlValue> {
const env: Record<string, string> = {};
if (plan.gbrainHomeEnv) env.GBRAIN_HOME = plan.gbrainHomeEnv;
if (plan.sourceId) env.GBRAIN_SOURCE = plan.sourceId;
- return { command: plan.launcher, args: stdioServeArgv(plan.launcher, plan.surface, plan.advertise).slice(1), ...(Object.keys(env).length ? { env } : {}) };
+ // Codex starts stdio servers in the session's directory, so serve starts through the launcher too (#8426).
+ return { command: hookLauncherPath(plan.brainHome), args: stdioServeArgv(plan.launcher, plan.surface, plan.advertise), ...(Object.keys(env).length ? { env } : {}) };
}
function desiredGroups(plan: CodexSetupPlan): Partial<Record<CodexSetupEvent, CodexHookGroup>> {
@@ -239,8 +240,8 @@ export async function applyCodexSetup(
mkdirSync(dirname(paths.configPath), { recursive: true, mode: 0o700 });
const lock = await acquireBootstrapLock(dirname(paths.configPath));
try {
- // Every hook command starts gbrain through the launcher, so it goes down before anything names it (#8424).
- if (plan.events.length) ensureHookLauncher(hookLauncherPath(plan.brainHome));
+ // The MCP table and every hook command start gbrain through the launcher, so it goes down before anything names it (#8424, #8426).
+ ensureHookLauncher(hookLauncherPath(plan.brainHome));
const found = inspectCodexSetup(plan);
if (opts.mcpMustBeCurrent && opts.pluginOwner === null && found.mcp.state !== 'current') throw new Error(`the '${plan.name}' MCP entry changed before the hooks were rewritten`);
const prior = found.prior;
diff --git a/src/core/setup/hook-launcher.ts b/src/core/setup/hook-launcher.ts
index f768245714..b5259d60ed 100644
--- a/src/core/setup/hook-launcher.ts
+++ b/src/core/setup/hook-launcher.ts
@@ -19,13 +19,12 @@
* session directory from GBRAIN_HOOK_CWD where it used process.cwd().
*/
import { randomBytes } from 'node:crypto';
-import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { configDir } from '../config.ts';
export const HOOK_LAUNCHER_NAME = 'gbrain-hook';
export const HOOK_LAUNCHER_DIR = 'hook-launcher';
-export const HOOK_CWD_ENV = 'GBRAIN_HOOK_CWD';
export const HOOK_LAUNCHER_SCRIPT = `#!/bin/sh
# gbrain hook launcher v1, written by gbrain setup (#8424); gbrain setup rewrites it.
@@ -138,22 +137,4 @@ export function hookLauncherInCommand(command: string): string | null {
return shellWords(command)?.find((w) => w.startsWith('/') && w.endsWith(suffix)) ?? null;
}
-let capturedSessionCwd: string | null = null;
-
-/**
- * `gbrain hook` start: take the session directory the launcher recorded and
- * drop it from the environment, so no child inherits a stale value. Resolved
- * like process.cwd() (sh keeps a symlinked $PWD), so project matching against
- * setup's realpath'd directories still holds.
- */
-export function captureHookSessionCwd(): void {
- const recorded = process.env[HOOK_CWD_ENV];
- delete process.env[HOOK_CWD_ENV];
- if (!recorded || !recorded.startsWith('/')) { capturedSessionCwd = null; return; }
- try { capturedSessionCwd = realpathSync(recorded); } catch { capturedSessionCwd = recorded; }
-}
-
-/** The session directory for `gbrain hook`: what the launcher recorded, else this process's directory. */
-export function hookSessionCwd(): string {
- return capturedSessionCwd ?? process.cwd();
-}
+export { HOOK_CWD_ENV, captureHookSessionCwd, hookSessionCwd } from '../session-cwd.ts';
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index 10063ecb14..49da64fc06 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -23,6 +23,7 @@ import { isSourceFederated, parseSourceConfig } from './sources-load.ts';
import { SOURCE_ID_RE, isValidSourceId, ALL_SOURCES } from './source-id.ts';
import { isTrustedDotfile, realpathOrResolve, realpathOrResolveAsync } from './path-confine.ts';
import { noteResolvedSource } from './fix-routing.ts';
+import { hookSessionCwd } from './session-cwd.ts';
// Re-export so scope-resolution call sites can import the sentinel from
// either module (#1712).
@@ -165,7 +166,7 @@ export async function resolveRegisteredLocalPathSource(engine: BrainEngine, cwd:
export async function resolveSourceId(
engine: BrainEngine,
explicit: string | null | undefined,
- cwd: string = process.cwd(),
+ cwd: string = hookSessionCwd(),
// Local IPC already evaluated the client's flag/env/dotfile tiers. The
// owner's environment must never redirect that client's unscoped request.
// `env` stands in for GBRAIN_SOURCE when a resident serve resolves for a
@@ -272,7 +273,7 @@ async function resolveSourceIdChain(
*/
export function resolveSourceIdEngineFree(
explicit: string | null | undefined,
- cwd: string = process.cwd(),
+ cwd: string = hookSessionCwd(),
opts: { env?: string } = {},
): string | null {
if (explicit) {
@@ -802,7 +803,7 @@ export async function resolveSourceForRepoPath(
*/
export async function getDefaultSourcePath(
engine: BrainEngine,
- cwd: string = process.cwd(),
+ cwd: string = hookSessionCwd(),
): Promise<string | null> {
const seen: { registered?: RegisteredSource[] } = {};
const sourceId = await resolveSourceIdChain(engine, null, cwd, {}, seen);
@@ -854,7 +855,7 @@ export type SourceTier = typeof SOURCE_TIER_NAMES[number];
export async function resolveSourceWithTier(
engine: BrainEngine,
explicit: string | null | undefined,
- cwd: string = process.cwd(),
+ cwd: string = hookSessionCwd(),
opts: { env?: string } = {},
): Promise<{ source_id: string; tier: SourceTier; detail?: string }> {
const resolved = await resolveSourceWithTierChain(engine, explicit, cwd, opts);
diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.ts
index 2b5bdb968a..213221303e 100644
--- a/src/core/sources-ops.ts
+++ b/src/core/sources-ops.ts
@@ -62,6 +62,7 @@ import { DEFAULT_CALENDAR_ID } from './google/types.ts';
import { resolveSourceWithTier, type SourceTier } from './source-resolver.ts';
import { deleteSourceRow } from './source-delete.ts';
import { defaultCloneDir, isOwnedClone } from './url-clone.ts';
+import { hookSessionCwd } from './session-cwd.ts';
// ── Errors ──────────────────────────────────────────────────────────────────
@@ -812,7 +813,7 @@ export interface ScopedSourceResolution {
*/
export async function resolveScopedSourceOrThrow(
engine: BrainEngine,
- cwd: string = process.cwd(),
+ cwd: string = hookSessionCwd(),
): Promise<ScopedSourceResolution> {
const resolved = await resolveSourceWithTier(engine, null, cwd);
if (resolved.tier !== 'seed_default') {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 58f7124d75..0e2c17638c 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -28,6 +28,7 @@ import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback
import { isEngineDegraded, onEngineRecovered } from '../core/degraded-marker.ts';
import { assertStdioSourceBindable } from './source-preflight.ts';
import { readOnlyServeSkipsResidentDuties } from '../core/direct-pool-profile.ts';
+import { hookSessionCwd } from '../core/session-cwd.ts';
/**
* Largest JSON-RPC message the stdio server reads (the SDK default is 10 MiB,
@@ -106,7 +107,7 @@ function deferredBoot(opts: { degraded: boolean }) {
export async function resolveMcpStdioSourceScope(
engine: BrainEngine,
- cwd: string = process.cwd(),
+ cwd: string = hookSessionCwd(),
opts: { warmConfig?: boolean } = {},
): Promise<{
sourceId: string;
@@ -465,7 +466,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// as local CLI dispatch: GBRAIN_SOURCE, then .gbrain-source, then the
// non-explicit fallback tiers. Non-explicit tiers may widen to federated
// local reads; explicit/env/dotfile scopes stay scalar.
- const sourceScope = await resolveMcpStdioSourceScope(engine, process.cwd(), { warmConfig: OPERATION_MANIFEST.find(o => o.name === name)?.mutating === false });
+ const sourceScope = await resolveMcpStdioSourceScope(engine, hookSessionCwd(), { warmConfig: OPERATION_MANIFEST.find(o => o.name === name)?.mutating === false });
// v0.28: stdio MCP has no per-token auth (local pipe). Default the
// takes-holder allow-list to ['world'] so agent-facing callers don't
// see private hunches via takes_list / takes_search / query. Operators