Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

Cache the Windows Bun path across hook processes (#6763)

wangshun4ef222b58717
diff --git a/plugin/scripts/bun-runner.js b/plugin/scripts/bun-runner.js
index 8e17359cd..894aa011b 100644
--- a/plugin/scripts/bun-runner.js
+++ b/plugin/scripts/bun-runner.js
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { spawnSync, spawn } from 'child_process';
-import { existsSync, readFileSync, mkdirSync, chmodSync, appendFileSync } from 'fs';
+import { existsSync, readFileSync, mkdirSync, chmodSync, appendFileSync, writeFileSync } from 'fs';
import { join, dirname, resolve, basename } from 'path';
import { homedir } from 'os';
import { fileURLToPath } from 'url';
@@ -20,6 +20,34 @@ function fixBrokenScriptPath(argPath) {
return argPath;
}
+// Every hook is a separate process, so a Bun path discovered through where.exe
+// is remembered on disk. The next hook reads it back instead of paying another
+// synchronous PATH scan (#6761). Mirrors src/launcher/bun-runtime.ts.
+function bunPathCacheFile() {
+ const dataDir = process.env.CLAUDE_MEM_DATA_DIR
+ ? expandHome(process.env.CLAUDE_MEM_DATA_DIR)
+ : join(homedir(), '.claude-mem');
+ return join(dataDir, 'run', 'bun-path');
+}
+
+function readCachedBunPath(cacheFile, notInCwd) {
+ try {
+ const cachedPath = readFileSync(cacheFile, 'utf-8').trim();
+ return cachedPath && notInCwd(cachedPath) && existsSync(cachedPath) ? cachedPath : null;
+ } catch {
+ return null;
+ }
+}
+
+function writeCachedBunPath(cacheFile, bunPath) {
+ try {
+ mkdirSync(dirname(cacheFile), { recursive: true, mode: 0o700 });
+ writeFileSync(cacheFile, `${bunPath}\n`, { mode: 0o600 });
+ } catch {
+ // A read-only or unwritable data directory only costs the next where.exe.
+ }
+}
+
function findBun() {
const bunInstall = typeof process.env.BUN_INSTALL === 'string' ? process.env.BUN_INSTALL.trim() : '';
const bunEnv = typeof process.env.BUN === 'string' ? process.env.BUN.trim() : '';
@@ -72,6 +100,14 @@ function findBun() {
const cwdNorm = normalizeForCwdCompare(process.cwd());
const notInCwd = line => normalizeForCwdCompare(dirname(line)) !== cwdNorm;
+ const cacheFile = IS_WINDOWS ? bunPathCacheFile() : null;
+ if (cacheFile) {
+ const cachedBunPath = readCachedBunPath(cacheFile, notInCwd);
+ if (cachedBunPath) {
+ return cachedBunPath;
+ }
+ }
+
const pathCheck = IS_WINDOWS
? spawnSync(whereExe, ['bun'], {
encoding: 'utf-8',
@@ -105,10 +141,12 @@ function findBun() {
: [];
const bunExePath = firstInstallPaths.find(line => line.toLowerCase().endsWith('bun.exe'));
if (bunExePath) {
+ writeCachedBunPath(cacheFile, bunExePath);
return bunExePath;
}
const bunCmdPath = firstInstallPaths.find(line => line.toLowerCase().endsWith('bun.cmd'));
if (bunCmdPath) {
+ writeCachedBunPath(cacheFile, bunCmdPath);
return bunCmdPath;
}
// The official installer ships bun.exe only (no bun.cmd shim). Return
@@ -117,6 +155,7 @@ function findBun() {
// cmd.exe drops entirely when it exceeds ~8191 chars (issue #3196).
const firstWherePath = bunPaths.find(Boolean);
if (firstWherePath) {
+ writeCachedBunPath(cacheFile, firstWherePath);
return firstWherePath;
}
// Every where hit was garbled or stale (#4694): fall through to the
diff --git a/src/launcher/bun-runtime.ts b/src/launcher/bun-runtime.ts
index 2f0da7970..07fb57b34 100644
--- a/src/launcher/bun-runtime.ts
+++ b/src/launcher/bun-runtime.ts
@@ -1,8 +1,9 @@
import { spawn, spawnSync, type ChildProcess } from 'child_process';
-import { existsSync } from 'fs';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { dirname, join } from 'path';
import { isCurrentDirectoryCandidate } from '../shared/spawn.js';
+import { expandHome } from '../shared/expand-home.js';
export const BUN_PATH_LOOKUP_TIMEOUT_MS = 1500;
@@ -15,6 +16,11 @@ interface BunLookupOptions {
timeoutMs?: number;
/** Working directory where.exe results are filtered against. */
cwd?: string;
+ /**
+ * Where to remember a Bun path found through where.exe. Defaults to
+ * `<data dir>/run/bun-path` on Windows; null disables the cache.
+ */
+ cacheFilePath?: string | null;
}
interface PathLookupResult {
@@ -27,6 +33,45 @@ function windowsSystem32Executable(executableName: string, env: NodeJS.ProcessEn
return join(systemRoot, 'System32', executableName);
}
+/**
+ * Every hook is a separate process, so a Bun path discovered through where.exe
+ * is remembered on disk. The next hook reads it back instead of paying another
+ * synchronous PATH scan (#6761). The file lives under the owner-controlled
+ * data directory, never the project cwd.
+ */
+function defaultBunPathCacheFilePath(env: NodeJS.ProcessEnv, homeDirectory: string): string {
+ const configuredDataDir = typeof env.CLAUDE_MEM_DATA_DIR === 'string' ? env.CLAUDE_MEM_DATA_DIR.trim() : '';
+ const dataDirectory = configuredDataDir
+ ? expandHome(configuredDataDir, 'win32', homeDirectory)
+ : join(homeDirectory, '.claude-mem');
+ return join(dataDirectory, 'run', 'bun-path');
+}
+
+function readCachedBunPath(
+ cacheFilePath: string | null,
+ exists: (path: string) => boolean,
+ cwd: string
+): string | null {
+ if (!cacheFilePath) return null;
+ try {
+ const cachedPath = readFileSync(cacheFilePath, 'utf-8').trim();
+ if (!cachedPath || isCurrentDirectoryCandidate(cachedPath, cwd)) return null;
+ return exists(cachedPath) ? cachedPath : null;
+ } catch {
+ return null;
+ }
+}
+
+function writeCachedBunPath(cacheFilePath: string | null, bunPath: string): void {
+ if (!cacheFilePath) return;
+ try {
+ mkdirSync(dirname(cacheFilePath), { recursive: true, mode: 0o700 });
+ writeFileSync(cacheFilePath, `${bunPath}\n`, { mode: 0o600 });
+ } catch {
+ // A read-only or unwritable data directory only costs the next where.exe.
+ }
+}
+
function knownBunPaths(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, homeDirectory: string): string[] {
const bunInstall = typeof env.BUN_INSTALL === 'string' ? env.BUN_INSTALL.trim() : '';
const bunEnv = typeof env.BUN === 'string' ? env.BUN.trim() : '';
@@ -104,6 +149,7 @@ export async function findBun(options: BunLookupOptions = {}): Promise<string |
const homeDirectory = options.homeDirectory ?? homedir();
const exists = options.exists ?? existsSync;
const knownPaths = knownBunPaths(platform, env, homeDirectory);
+ const cwd = options.cwd ?? process.cwd();
// The Windows launcher runs inside every hook. Check explicit locations first
// so the usual ~/.bun installation does not synchronously invoke where.exe.
@@ -112,6 +158,12 @@ export async function findBun(options: BunLookupOptions = {}): Promise<string |
if (bunPath && exists(bunPath)) return bunPath;
}
+ const cacheFilePath = options.cacheFilePath === undefined
+ ? defaultBunPathCacheFilePath(env, homeDirectory)
+ : options.cacheFilePath;
+ const cachedBunPath = readCachedBunPath(cacheFilePath, exists, cwd);
+ if (cachedBunPath) return cachedBunPath;
+
const pathCheck = await runPathLookup(
windowsSystem32Executable('where.exe', env),
['bun'],
@@ -124,7 +176,6 @@ export async function findBun(options: BunLookupOptions = {}): Promise<string |
// can arrive garbled; keep only lines that exist on disk (#4694). It
// also searches the current directory first: hooks run inside the user's
// project, so a bun.exe planted there must never be returned.
- const cwd = options.cwd ?? process.cwd();
const bunPaths = pathCheck.stdout
.split(/\r?\n/)
.map((line) => line.trim())
@@ -140,13 +191,22 @@ export async function findBun(options: BunLookupOptions = {}): Promise<string |
? bunPaths.filter((line) => dirname(line).toLowerCase() === firstBunDir)
: [];
const bunExePath = firstInstallPaths.find((line) => line.toLowerCase().endsWith('bun.exe'));
- if (bunExePath) return bunExePath;
+ if (bunExePath) {
+ writeCachedBunPath(cacheFilePath, bunExePath);
+ return bunExePath;
+ }
const bunCmdPath = firstInstallPaths.find((line) => line.toLowerCase().endsWith('bun.cmd'));
- if (bunCmdPath) return bunCmdPath;
+ if (bunCmdPath) {
+ writeCachedBunPath(cacheFilePath, bunCmdPath);
+ return bunCmdPath;
+ }
// The official installer ships bun.exe only (no bun.cmd shim). Return
// the resolved absolute path instead of relying on the child's PATH.
const firstWherePath = bunPaths.find(Boolean);
- if (firstWherePath) return firstWherePath;
+ if (firstWherePath) {
+ writeCachedBunPath(cacheFilePath, firstWherePath);
+ return firstWherePath;
+ }
}
return null;
}
diff --git a/src/launcher/launcher-protocol.ts b/src/launcher/launcher-protocol.ts
index 37e9f6df3..4ff7b778b 100644
--- a/src/launcher/launcher-protocol.ts
+++ b/src/launcher/launcher-protocol.ts
@@ -17,5 +17,7 @@
* whole worker bundle.
* 4 — preserve the exit status of the new local messages subcommand.
* 5 — forward a complete hook JSON payload without waiting for stdin to close.
+ * 6 — remember a where.exe Bun path on disk so later hooks skip the lookup
+ * (#6761).
*/
-export const LAUNCHER_PROTOCOL = 5;
+export const LAUNCHER_PROTOCOL = 6;
diff --git a/tests/bun-runner.test.ts b/tests/bun-runner.test.ts
index e9fe57d66..014f4a209 100644
--- a/tests/bun-runner.test.ts
+++ b/tests/bun-runner.test.ts
@@ -7,13 +7,20 @@ import { delimiter, dirname, join, win32 } from 'path';
const BUN_RUNNER_PATH = join(import.meta.dir, '..', 'plugin', 'scripts', 'bun-runner.js');
const source = readFileSync(BUN_RUNNER_PATH, 'utf-8');
const findBunSource = source.slice(
- source.indexOf('function findBun() {'),
+ source.indexOf('function bunPathCacheFile() {'),
source.indexOf('\nfunction isPluginDisabledInClaudeSettings() {')
);
type FindBun = () => string | null;
const createFindBun = new Function(
'deps',
- `const { IS_WINDOWS, dirname, existsSync, homedir, join, spawnSync, process = globalThis.process } = deps;\n${findBunSource}\nreturn findBun;`
+ `const {
+ IS_WINDOWS, dirname, existsSync, homedir, join, spawnSync,
+ readFileSync = () => { throw new Error('ENOENT'); },
+ writeFileSync = () => {},
+ mkdirSync = () => {},
+ expandHome = (path) => path,
+ process = globalThis.process,
+ } = deps;\n${findBunSource}\nreturn findBun;`
) as (deps: {
IS_WINDOWS: boolean;
dirname: typeof win32.dirname;
@@ -21,6 +28,10 @@ const createFindBun = new Function(
homedir: () => string;
join: typeof join;
spawnSync: typeof spawnSync;
+ readFileSync?: (path: string, encoding: string) => string;
+ writeFileSync?: (path: string, data: string, options?: { mode?: number }) => void;
+ mkdirSync?: (path: string, options?: { recursive?: boolean; mode?: number }) => void;
+ expandHome?: (path: string) => string;
process?: { env: NodeJS.ProcessEnv; cwd: () => string };
}) => FindBun;
@@ -146,6 +157,39 @@ describe('bun-runner.js Windows known paths before where (#4934)', () => {
});
});
+describe('bun-runner.js Windows Bun path cache (#6761)', () => {
+ it('reuses a cached where.exe hit on the next hook process', () => {
+ let cachedPath = '';
+ let whereCalls = 0;
+ const bunPath = 'C:\\scoop\\shims\\bun.exe';
+ const findBun = createFindBun({
+ IS_WINDOWS: true,
+ dirname: win32.dirname,
+ existsSync: (p: string) => p === bunPath,
+ homedir: () => 'C:\\Users\\fixture',
+ join: win32.join,
+ readFileSync: (path: string) => {
+ if (path !== win32.join('C:\\Users\\fixture', '.claude-mem', 'run', 'bun-path')) throw new Error('ENOENT');
+ if (!cachedPath) throw new Error('ENOENT');
+ return cachedPath;
+ },
+ writeFileSync: (_path: string, data: string) => { cachedPath = data.trim(); },
+ mkdirSync: () => {},
+ expandHome: (path: string) => path,
+ process: { env: { SystemRoot: 'C:\\Windows' }, cwd: () => 'C:\\project' },
+ spawnSync: (() => {
+ whereCalls += 1;
+ return { status: 0, stdout: `${bunPath}\r\n`, stderr: '' };
+ }) as unknown as typeof spawnSync,
+ });
+
+ expect(findBun()).toBe(bunPath);
+ expect(whereCalls).toBe(1);
+ expect(findBun()).toBe(bunPath);
+ expect(whereCalls).toBe(1);
+ });
+});
+
describe('bun-runner.js Windows PATH ordering', () => {
it('keeps an earlier bun.cmd ahead of a later bun.exe', () => {
expect(findBunForWhereOutput([
diff --git a/tests/launcher/bun-runtime.test.ts b/tests/launcher/bun-runtime.test.ts
index 311d3c60a..bccf070be 100644
--- a/tests/launcher/bun-runtime.test.ts
+++ b/tests/launcher/bun-runtime.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from "bun:test";
import { EventEmitter } from "node:events";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
import { join } from "node:path";
import type { ChildProcess } from "node:child_process";
import { findBun } from "../../src/launcher/bun-runtime.js";
@@ -69,6 +71,7 @@ describe("findBun Windows discovery", () => {
cwd: "C:\\work\\project",
exists: (candidate) => candidate === plantedBun || candidate === realBun,
spawnProcess: (() => child) as never,
+ cacheFilePath: null,
timeoutMs: 100,
});
setTimeout(() => {
@@ -79,6 +82,84 @@ describe("findBun Windows discovery", () => {
expect(await resultPromise).toBe(realBun);
});
+ it("caches the where.exe result so later hooks skip the lookup (#6761)", async () => {
+ // Every hook is its own process, so the cache has to live on disk: the
+ // first hook that has to ask where.exe records the answer, and the next
+ // hook reuses it instead of paying another synchronous lookup.
+ const cacheRoot = mkdtempSync(join(tmpdir(), "claude-mem-bun-path-"));
+ try {
+ const bunPath = join(cacheRoot, "tools", "bun.exe");
+ mkdirSync(join(cacheRoot, "tools"), { recursive: true });
+ writeFileSync(bunPath, "");
+ const cacheFilePath = join(cacheRoot, "run", "bun-path");
+ let lookupCount = 0;
+ const lookup = () => {
+ lookupCount += 1;
+ const child = pendingChildProcess();
+ setTimeout(() => {
+ child.stdout.emit("data", `${bunPath}\r\n`);
+ child.emit("close", 0, null);
+ }, 1);
+ return child;
+ };
+ const options = {
+ platform: "win32" as const,
+ env: { SystemRoot: "C:\\Windows", CLAUDE_MEM_DATA_DIR: cacheRoot },
+ homeDirectory: join(cacheRoot, "home"),
+ exists: existsSync,
+ spawnProcess: (() => lookup()) as never,
+ timeoutMs: 100,
+ };
+
+ expect(await findBun(options)).toBe(bunPath);
+ expect(lookupCount).toBe(1);
+
+ expect(await findBun(options)).toBe(bunPath);
+ expect(lookupCount).toBe(1);
+ expect(existsSync(cacheFilePath)).toBe(true);
+ } finally {
+ rmSync(cacheRoot, { recursive: true, force: true });
+ }
+ });
+
+ it("ignores a stale cached Bun path and refreshes it (#6761)", async () => {
+ const cacheRoot = mkdtempSync(join(tmpdir(), "claude-mem-bun-path-stale-"));
+ try {
+ const stalePath = join(cacheRoot, "tools", "removed-bun.exe");
+ const bunPath = join(cacheRoot, "tools", "bun.exe");
+ mkdirSync(join(cacheRoot, "tools"), { recursive: true });
+ writeFileSync(bunPath, "");
+ const cacheFilePath = join(cacheRoot, "run", "bun-path");
+ mkdirSync(join(cacheRoot, "run"), { recursive: true });
+ writeFileSync(cacheFilePath, `${stalePath}\n`);
+ let lookupCount = 0;
+ const options = {
+ platform: "win32" as const,
+ env: { SystemRoot: "C:\\Windows", CLAUDE_MEM_DATA_DIR: cacheRoot },
+ homeDirectory: join(cacheRoot, "home"),
+ exists: existsSync,
+ spawnProcess: (() => {
+ lookupCount += 1;
+ const child = pendingChildProcess();
+ setTimeout(() => {
+ child.stdout.emit("data", `${bunPath}\r\n`);
+ child.emit("close", 0, null);
+ }, 1);
+ return child;
+ }) as never,
+ timeoutMs: 100,
+ };
+
+ expect(await findBun(options)).toBe(bunPath);
+ expect(lookupCount).toBe(1);
+ expect(readFileSync(cacheFilePath, "utf-8").trim()).toBe(bunPath);
+ expect(await findBun(options)).toBe(bunPath);
+ expect(lookupCount).toBe(1);
+ } finally {
+ rmSync(cacheRoot, { recursive: true, force: true });
+ }
+ });
+
it("returns at the deadline even when killing where.exe emits no close event", async () => {
const child = pendingChildProcess(false);
let deadline: ReturnType<typeof setTimeout> | undefined;