Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(setup): install the per-turn rule hook on Windows

garrytanbb0cc166de31
diff --git a/src/core/session-cwd.ts b/src/core/session-cwd.ts
index 84957f28cc..63119fe4d2 100644
--- a/src/core/session-cwd.ts
+++ b/src/core/session-cwd.ts
@@ -11,6 +11,8 @@
* the session directory would load its bunfig.toml again.
*/
import { realpathSync } from 'node:fs';
+import { posix, win32 } from 'node:path';
+import { msysToNativePath } from './path-confine.ts';
export const HOOK_CWD_ENV = 'GBRAIN_HOOK_CWD';
@@ -20,12 +22,13 @@ 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.
+ * setup's realpath'd directories still holds. On Windows the launcher runs
+ * under Git Bash, whose $PWD is /c/..., so that form is mapped back to C:\...
*/
-export function captureHookSessionCwd(): void {
- const recorded = process.env[HOOK_CWD_ENV];
+export function captureHookSessionCwd(platform: NodeJS.Platform = process.platform): void {
+ const recorded = msysToNativePath(process.env[HOOK_CWD_ENV] ?? '', platform);
delete process.env[HOOK_CWD_ENV];
- if (!recorded || !recorded.startsWith('/')) { capturedSessionCwd = null; return; }
+ if (!recorded || !(platform === 'win32' ? win32 : posix).isAbsolute(recorded)) { capturedSessionCwd = null; return; }
try { capturedSessionCwd = realpathSync(recorded); } catch { capturedSessionCwd = recorded; }
}
diff --git a/src/core/setup/hook-launcher.ts b/src/core/setup/hook-launcher.ts
index f087a0e41b..63c8f7a385 100644
--- a/src/core/setup/hook-launcher.ts
+++ b/src/core/setup/hook-launcher.ts
@@ -20,8 +20,9 @@
*/
import { randomBytes } from 'node:crypto';
import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
+import { dirname, join, win32 } from 'node:path';
import { configDir } from '../config.ts';
+import { msysToNativePath } from '../path-confine.ts';
export const HOOK_LAUNCHER_NAME = 'gbrain-hook';
export const HOOK_LAUNCHER_DIR = 'hook-launcher';
@@ -131,14 +132,21 @@ export function shellWords(command: string): string[] | null {
return words;
}
-/** An absolute path shaped like a hook launcher (<config dir>/hook-launcher/gbrain-hook). */
+/** An absolute path (POSIX, or a Windows drive or UNC path) shaped like a hook launcher (<config dir>/hook-launcher/gbrain-hook). */
export function isHookLauncherPath(path: string): boolean {
- return path.startsWith('/') && path.endsWith(`/${HOOK_LAUNCHER_DIR}/${HOOK_LAUNCHER_NAME}`);
+ return (path.startsWith('/') || win32.isAbsolute(path)) && path.replace(/\\/g, '/').endsWith(`/${HOOK_LAUNCHER_DIR}/${HOOK_LAUNCHER_NAME}`);
}
-/** The launcher a hook command runs gbrain through, or null for a command that starts gbrain in the session directory. */
-export function hookLauncherInCommand(command: string): string | null {
- return shellWords(command)?.find(isHookLauncherPath) ?? null;
+/** A path as a hook command names it: Claude Code runs hooks through Git Bash on Windows, which (like the launcher's own check) wants /c/... for C:\... */
+export function hookShellPath(path: string): string {
+ const drive = /^([A-Za-z]):[\\/](.*)$/.exec(path);
+ return drive ? `/${drive[1]!.toLowerCase()}/${drive[2]!.replace(/\\/g, '/')}` : path;
+}
+
+/** The launcher a hook command runs gbrain through, as a path this platform's file calls can read, or null for a command that starts gbrain in the session directory. */
+export function hookLauncherInCommand(command: string, platform: NodeJS.Platform = process.platform): string | null {
+ const launcher = shellWords(command)?.find(isHookLauncherPath);
+ return launcher ? msysToNativePath(launcher, platform) : null;
}
export { HOOK_CWD_ENV, captureHookSessionCwd, hookSessionCwd } from '../session-cwd.ts';
diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.ts
index 648fd2f00a..1519e05969 100644
--- a/src/core/setup/turn-hook.ts
+++ b/src/core/setup/turn-hook.ts
@@ -31,14 +31,14 @@
* inspect command when it does not.
*/
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
+import { dirname, join, win32 } from 'node:path';
import { bunSpawnSync } from '../spawn.ts';
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, claudeManagedSettingsPaths, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';
-import { ensureHookLauncher, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';
+import { ensureHookLauncher, hookLauncherPath, hookLauncherState, hookShellPath } from './hook-launcher.ts';
export const TURN_RULE_LANE = 'turn-rule';
export const TURN_RULE_MARKER = 'turn-rule-v1';
@@ -72,7 +72,7 @@ const claudePath = (p: TurnHookPaths) => p.claudeSettings ?? claudeUserSettingsP
const codexPaths = (p: TurnHookPaths) => ({ hooks: p.codexHooks ?? codexHooksPath(), config: p.codexConfig ?? codexConfigPath() });
export function claudeTurnRuleCommand(gbrainBin: string, gbrainHome: string | undefined, launcher: string): string {
- return buildClaudeHookCommand(gbrainBin, EVENT, { ...(gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE }, launcher);
+ return buildClaudeHookCommand(hookShellPath(gbrainBin), EVENT, { ...(gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE }, hookShellPath(launcher));
}
export function codexTurnRuleGroup(gbrainBin: string, gbrainHome: string | undefined, launcher: string): CodexHookGroup {
@@ -131,7 +131,8 @@ export function syncTurnRuleHook(opts: { harness: TurnRuleHarness; gbrainBin: st
const paths = opts.paths ?? {};
const where = opts.harness === 'codex' ? codexPaths(paths).hooks : claudePath(paths);
const print = (why: string): TurnHookOutcome => ({ harness: opts.harness, action: 'print', path: where, detail: `per-turn rule hook not installed: ${why}`, next: opts.rerun });
- if (!opts.gbrainBin || !opts.gbrainBin.startsWith('/')) return print('no absolute gbrain binary was found (harnesses inherit no PATH); install gbrain globally or pass --gbrain-bin');
+ if (!opts.gbrainBin || !(opts.gbrainBin.startsWith('/') || win32.isAbsolute(opts.gbrainBin))) return print('no absolute gbrain binary was found (harnesses inherit no PATH); install gbrain globally or pass --gbrain-bin');
+ if (opts.harness === 'codex' && !opts.gbrainBin.startsWith('/')) return print('Codex runs hook commands on Windows without a POSIX shell, so it cannot run gbrain\'s hook launcher');
try {
const launcher = paths.hookLauncher ?? hookLauncherPath();
// The launcher goes down first: a hook that names it must find it.
@@ -155,7 +156,7 @@ function syncClaude(bin: string, home: string | undefined, launcher: string, pat
if (dryRun) return { harness: 'claude-code', action: 'write', path, detail };
mkdirSync(dirname(path), { recursive: true });
const owned = new Set([wantHash, ...ours.map((e) => hookEntryHash(e)).filter((h): h is string => !!h)]);
- writeClaudeHooksAt(path, { gbrainBin: bin, hookLauncher: launcher, env: { ...(home ? { GBRAIN_HOME: home } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE, GBRAIN_SEAT: '' },
+ writeClaudeHooksAt(path, { gbrainBin: hookShellPath(bin), hookLauncher: hookShellPath(launcher), env: { ...(home ? { GBRAIN_HOME: home } : {}), GBRAIN_HOOK_LANE: TURN_RULE_LANE, GBRAIN_SEAT: '' },
events: [EVENT], marker: TURN_RULE_MARKER, ownedEntryHashes: owned, freshMode: 0o600 });
return { harness: 'claude-code', action: 'write', path, detail };
}
diff --git a/test/turn-hook-windows-paths-8449.test.ts b/test/turn-hook-windows-paths-8449.test.ts
new file mode 100644
index 0000000000..6971ddf252
--- /dev/null
+++ b/test/turn-hook-windows-paths-8449.test.ts
@@ -0,0 +1,69 @@
+/**
+ * #8449: a Windows gbrain install (drive-letter paths) gets the per-turn rule
+ * hook. Claude Code runs hook commands through Git Bash on Windows, so the
+ * command names the launcher and binary in Git Bash's /c/... form, which the
+ * POSIX launcher's own absolute-path check accepts; gbrain maps that form back
+ * to the native path when it reads the launcher file or the session directory. Codex runs hooks on
+ * Windows without a POSIX shell, so it still gets the printed step. Paths are
+ * passed in, so this runs the same on every platform.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, win32 } from 'node:path';
+import { claudeTurnRuleCommand, isTurnRuleEntry, syncTurnRuleHook } from '../src/core/setup/turn-hook.ts';
+import { captureHookSessionCwd, hookLauncherInCommand, hookSessionCwd, hookShellPath, isHookLauncherPath, shellWords } from '../src/core/setup/hook-launcher.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+const winHome = win32.join('C:\\', 'Users', 'alice example');
+const gbrainBin = win32.join(winHome, '.bun', 'bin', 'gbrain.exe');
+const winLauncher = win32.join(winHome, '.gbrain', 'hook-launcher', 'gbrain-hook');
+
+describe('per-turn rule hook with Windows drive-letter paths (#8449)', () => {
+ test('claude-code: a drive-letter --gbrain-bin is accepted and the command names Git Bash paths', () => {
+ const settings = join(mkdtempSync(join(tmpdir(), 'gbrain-win-hook-')), 'settings.json');
+ roots.push(settings.slice(0, -'/settings.json'.length));
+ const o = syncTurnRuleHook({ harness: 'claude-code', gbrainBin, paths: { claudeSettings: settings, hookLauncher: winLauncher }, dryRun: true, rerun: 'gbrain setup claude-code --instructions-only' });
+ expect(o.action).toBe('write');
+ const command = claudeTurnRuleCommand(gbrainBin, undefined, winLauncher);
+ expect(shellWords(command)).toEqual(['env', 'GBRAIN_HOOK_LANE=turn-rule', '/c/Users/alice example/.gbrain/hook-launcher/gbrain-hook', '/c/Users/alice example/.bun/bin/gbrain.exe', 'hook', 'user-prompt']);
+ expect(isTurnRuleEntry({ type: 'command', command })).toBe(true);
+ });
+
+ test('the launcher is found in that command, and read at its native path on Windows only', () => {
+ const command = claudeTurnRuleCommand(gbrainBin, undefined, winLauncher);
+ expect(hookLauncherInCommand(command, 'win32')).toBe(winLauncher);
+ expect(hookLauncherInCommand(command, 'linux')).toBe('/c/Users/alice example/.gbrain/hook-launcher/gbrain-hook');
+ expect(isHookLauncherPath(winLauncher)).toBe(true);
+ expect(isHookLauncherPath('C:/Users/alice example/.gbrain/hook-launcher/gbrain-hook')).toBe(true);
+ expect(isHookLauncherPath('.gbrain\\hook-launcher\\gbrain-hook')).toBe(false);
+ expect(hookShellPath('/home/alice-example/.gbrain/hook-launcher/gbrain-hook')).toBe('/home/alice-example/.gbrain/hook-launcher/gbrain-hook');
+ });
+
+ test('the session directory Git Bash records (/c/...) is read back as the native Windows path', async () => {
+ await withEnv({ GBRAIN_HOOK_CWD: '/c/Users/alice example/project' }, async () => {
+ captureHookSessionCwd('win32');
+ expect(process.env.GBRAIN_HOOK_CWD).toBeUndefined();
+ expect(hookSessionCwd()).toBe('C:\\Users\\alice example\\project');
+ });
+ await withEnv({ GBRAIN_HOOK_CWD: 'relative\\dir' }, async () => {
+ captureHookSessionCwd('win32');
+ expect(hookSessionCwd()).toBe(process.cwd());
+ });
+ });
+
+ test('codex: a drive-letter binary prints the step with the reason, not "no absolute gbrain binary"', () => {
+ const o = syncTurnRuleHook({ harness: 'codex', gbrainBin, paths: { codexHooks: join(tmpdir(), 'gbrain-win-no-such', 'hooks.json'), codexConfig: join(tmpdir(), 'gbrain-win-no-such', 'config.toml'), hookLauncher: winLauncher }, dryRun: true, rerun: 'gbrain setup codex --instructions-only' });
+ expect(o.action).toBe('print');
+ expect(o.detail).toContain('POSIX shell');
+ expect(o.detail).not.toContain('no absolute gbrain binary');
+ });
+
+ test('a relative binary is still refused', () => {
+ const o = syncTurnRuleHook({ harness: 'claude-code', gbrainBin: 'gbrain.exe', paths: { hookLauncher: winLauncher }, dryRun: true, rerun: 'x' });
+ expect(o.detail).toContain('no absolute gbrain binary');
+ });
+});