From 6a444a0273370b5811ac3b1d4ac3e8ac9dc50eca Mon Sep 17 00:00:00 2001 From: Morgan Allen Date: Sun, 22 Nov 2026 17:49:38 -0800 Subject: [PATCH 1/5] fix(shared): macOS bare spawns no longer allocate ghost PIDs for each PATH miss --- packages/shared/src/shell.test.ts | 290 ++++++++++++++++++++++++++++-- packages/shared/src/shell.ts | 109 +++++++++-- 2 files changed, 377 insertions(+), 22 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 8f81723486f55..9a63fde2fbb0b 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -1200,25 +1200,85 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); - it.effect("keeps git when PATH has another git or the host is not macOS", () => - Effect.gen(function* () { - const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT }); - expect(yield* homebrew.resolve).toBe("git"); - expect(homebrew.host.xcrunCalls).toBe(0); + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "distinguishes symlink/.. custom git from /usr/bin/git using realpath", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-git-shim-" }); + const customDir = path.join(root, "custom"); + const customSub = path.join(customDir, "sub"); + const link = path.join(root, "link"); + yield* fs.makeDirectory(customSub, { recursive: true }); + yield* fs.symlink(customSub, link); + + const customGit = path.join(customDir, "git"); + yield* fs.writeFileString(customGit, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(customGit, 0o755); + + let xcrunCalls = 0; + const resolved = yield* resolveSpawnCommand("git", ["status"], { + env: { PATH: `${link}/..` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(XcodeGitLocation, () => { + xcrunCalls += 1; + return XCODE_GIT; + }), + ); + expect(resolved).toBe(`${link}/../git`); + expect(xcrunCalls).toBe(0); - const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); - expect(yield* linux.resolve).toBe("git"); - }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + const hasDirectUsrBinGit = yield* fs.realPath("/usr/bin/git").pipe( + Effect.map((resolvedPath) => resolvedPath === "/usr/bin/git"), + Effect.orElseSucceed(() => false), + ); + if (hasDirectUsrBinGit) { + const shimLink = path.join(root, "usr-bin-link"); + yield* fs.symlink("/usr/bin", shimLink); + const shimResolved = yield* resolveSpawnCommand("git", ["status"], { + env: { PATH: `${shimLink}/.` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(XcodeGitLocation, () => { + xcrunCalls += 1; + return customGit; + }), + ); + expect(shimResolved).toBe(customGit); + expect(xcrunCalls).toBe(1); + } + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); - it.effect("keeps git when xcrun fails or names a missing file", () => + it.effect( + "uses PATH git without xcrun when PATH has another git, and keeps bare git on Linux", + () => + Effect.gen(function* () { + const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT }); + expect(yield* homebrew.resolve).toBe("/opt/homebrew/bin/git"); + expect(homebrew.host.xcrunCalls).toBe(0); + + const linux = setup({ + platform: "linux", + gitOnPath: "/usr/bin/git", + xcrunGit: XCODE_GIT, + }); + expect(yield* linux.resolve).toBe("git"); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect("falls back to /usr/bin/git when xcrun fails or names a missing file", () => Effect.gen(function* () { const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined }); - expect(yield* failed.resolve).toBe("git"); + expect(yield* failed.resolve).toBe("/usr/bin/git"); const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT }); missing.files.delete(XCODE_GIT); - expect(yield* missing.resolve).toBe("git"); + expect(yield* missing.resolve).toBe("/usr/bin/git"); }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); @@ -1237,6 +1297,214 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { ); }); + describe("macOS bare commands", () => { + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "yields while resolving bare commands on macOS and honors earlier PATH additions immediately", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-path-" }); + const first = path.join(root, "first"); + const second = path.join(root, "second"); + yield* fs.makeDirectory(first); + yield* fs.makeDirectory(second); + + const laterTool = path.join(second, "mytool"); + yield* fs.writeFileString(laterTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(laterTool, 0o755); + + const resolve = resolveSpawnCommand("mytool", ["--flag"], { + env: { PATH: `${first}:${second}` }, + }).pipe(Effect.provideService(HostProcess.Platform, "darwin")); + + let completed = false; + const [resolved, completedBeforeScanReturned] = yield* Effect.all( + [ + resolve.pipe( + Effect.tap(() => + Effect.sync(() => { + completed = true; + }), + ), + ), + Effect.sync(() => completed), + ], + { concurrency: 2 }, + ); + expect(completedBeforeScanReturned).toBe(false); + expect(resolved).toEqual({ + command: laterTool, + args: ["--flag"], + shell: false, + }); + + // Adding an executable to an earlier PATH entry must take precedence immediately. + const earlierTool = path.join(first, "mytool"); + yield* fs.writeFileString(earlierTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(earlierTool, 0o755); + + expect(yield* resolve).toEqual({ + command: earlierTool, + args: ["--flag"], + shell: false, + }); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "skips directories and non-executable files in earlier PATH entries, but stops on ELOOP", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-errno-path-" }); + const dirEntry = path.join(root, "has-dir"); + const nonExecEntry = path.join(root, "has-non-exec"); + const loopEntry = path.join(root, "has-loop"); + const validEntry = path.join(root, "valid"); + yield* fs.makeDirectory(path.join(dirEntry, "mytool"), { recursive: true }); + yield* fs.makeDirectory(nonExecEntry); + yield* fs.makeDirectory(loopEntry); + yield* fs.makeDirectory(validEntry); + + const nonExecTool = path.join(nonExecEntry, "mytool"); + yield* fs.writeFileString(nonExecTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(nonExecTool, 0o644); + + const validTool = path.join(validEntry, "mytool"); + yield* fs.writeFileString(validTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(validTool, 0o755); + + // Directory and non-executable file (EACCES) are skipped so validTool wins. + const skipped = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${dirEntry}:${nonExecEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(skipped).toBe(validTool); + + // Symlink loop (ELOOP) stops the scan and defers to native spawn instead of skipping to validTool. + const loopA = path.join(loopEntry, "loop-a"); + const loopB = path.join(loopEntry, "loop-b"); + yield* fs.symlink(loopB, loopA); + yield* fs.symlink(loopA, loopB); + yield* fs.symlink(loopA, path.join(loopEntry, "mytool")); + + const deferredOnLoop = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${loopEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(deferredOnLoop).toBe("mytool"); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "preserves symlink/.. traversal in macOS PATH entries instead of normalizing textually", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-symlink-path-" }); + const targetParent = path.join(root, "real"); + const targetChild = path.join(targetParent, "child"); + const linkDir = path.join(root, "link"); + yield* fs.makeDirectory(targetChild, { recursive: true }); + yield* fs.symlink(targetChild, linkDir); + + // Real executable lives in real/mytool (reached via link/..), while root/mytool does not exist. + const realTool = path.join(targetParent, "mytool"); + yield* fs.writeFileString(realTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(realTool, 0o755); + + const symlinkParentEntry = `${linkDir}/..`; + const resolved = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: symlinkParentEntry }, + }).pipe(Effect.provideService(HostProcess.Platform, "darwin")); + + expect(resolved).toEqual({ + command: `${symlinkParentEntry}/mytool`, + args: [], + shell: false, + }); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( + "uses uppercase PATH, defaults to /usr/bin:/bin when unset, and defers on empty or relative entries", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-macos-env-path-" }); + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin); + const tool = path.join(bin, "mytool"); + yield* fs.writeFileString(tool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(tool, 0o755); + + const resolveWithEnv = (command: string, env: NodeJS.ProcessEnv) => + resolveSpawnCommand(command, [], { env }).pipe( + Effect.map((resolved) => resolved.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + + // Explicitly empty PATH or leading empty/relative entries defer to native lookup. + expect(yield* resolveWithEnv("mytool", { PATH: "" })).toBe("mytool"); + expect(yield* resolveWithEnv("mytool", { PATH: `:${bin}` })).toBe("mytool"); + expect(yield* resolveWithEnv("mytool", { PATH: `.:${bin}` })).toBe("mytool"); + expect(yield* resolveWithEnv("mytool", { PATH: `rel/bin:${bin}` })).toBe("mytool"); + + // Trailing empty or relative entries after a match still resolve cleanly. + expect(yield* resolveWithEnv("mytool", { PATH: `${bin}:` })).toBe(tool); + expect(yield* resolveWithEnv("mytool", { PATH: `${bin}/:.` })).toBe(`${bin}/mytool`); + + // Lowercase Path is ignored on macOS; unset PATH falls back to /usr/bin:/bin. + expect(yield* resolveWithEnv("mytool", { Path: bin })).toBe("mytool"); + const expectedDefaultSh = ["/usr/bin/sh", "/bin/sh"].find((candidate) => { + try { + NodeFS.accessSync(candidate, NodeFS.constants.X_OK); + return NodeFS.statSync(candidate).isFile(); + } catch { + return false; + } + }); + if (expectedDefaultSh !== undefined) { + expect(yield* resolveWithEnv("sh", {})).toBe(expectedDefaultSh); + } + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + + it.effect("skips resolution for explicit paths on macOS and for bare commands on Linux", () => + Effect.gen(function* () { + let resolverCalls = 0; + const resolver = () => { + resolverCalls += 1; + return "/bin/ps"; + }; + + expect( + yield* resolveSpawnCommand("/bin/ps", ["-A"], { env: { PATH: "/bin" } }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(SpawnExecutableResolution, resolver), + ), + ).toEqual({ command: "/bin/ps", args: ["-A"], shell: false }); + + expect( + yield* resolveSpawnCommand("ps", ["-A"], { env: { PATH: "/bin" } }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(SpawnExecutableResolution, resolver), + ), + ).toEqual({ command: "ps", args: ["-A"], shell: false }); + + expect(resolverCalls).toBe(0); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + }); + it.effect("does not fall back to a shell for unresolved Windows commands", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 0ba42dc3078d6..5150546edf33c 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -985,22 +985,104 @@ export const XcodeGitLocation = Context.Reference( ); const MACOS_GIT_SHIM = "/usr/bin/git"; +// POSIX default search path (_PATH_DEFPATH) when PATH is unset. +const POSIX_DEFAULT_PATH = "/usr/bin:/bin"; +const POSIX_PATH_SCAN_CONTINUE_ERRORS = new Set(["ENOENT", "ENOTDIR", "EACCES"]); + +function isPosixPathScanContinueError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | null)?.code; + return typeof code === "string" && POSIX_PATH_SCAN_CONTINUE_ERRORS.has(code); +} + +async function isMacosGitShim(candidate: string): Promise { + if (candidate === MACOS_GIT_SHIM) return true; + try { + return (await NodeFS.promises.realpath(candidate)) === MACOS_GIT_SHIM; + } catch { + return false; + } +} + +// An empty or relative POSIX PATH entry depends on the child's cwd, which resolveSpawnCommand does not take. +function hasRelativePosixPathEntryBefore( + pathValue: string | undefined, + resolvedPath: string, +): boolean { + if (pathValue === undefined) return false; + const resolvedDir = NodePath.posix.resolve(NodePath.posix.dirname(resolvedPath)); + for (const entry of pathValue.split(POSIX_PATH_DELIMITER)) { + if (entry.length === 0 || !entry.startsWith("/")) return true; + if (NodePath.posix.resolve(entry) === resolvedDir) return false; + } + return false; +} + +// Scan macOS PATH entries literally so the kernel resolves `..` after symlinks as native spawn does. +// Only continue past ENOENT/ENOTDIR/EACCES; other errors (such as ELOOP or EIO) defer to native spawn. +async function resolveMacosPathExecutable( + command: string, + env: NodeJS.ProcessEnv, +): Promise { + const pathValue = env.PATH ?? POSIX_DEFAULT_PATH; + for (const entry of pathValue.split(POSIX_PATH_DELIMITER)) { + if (entry.length === 0 || !entry.startsWith("/")) return undefined; + const candidate = entry.endsWith("/") ? `${entry}${command}` : `${entry}/${command}`; + try { + if (!(await NodeFS.promises.stat(candidate)).isFile()) continue; + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return candidate; + } catch (error) { + if (!isPosixPathScanContinueError(error)) return undefined; + } + } + return undefined; +} + +/** + * Resolve bare commands to absolute paths on macOS before spawning. + * libuv's macOS posix_spawn walks PATH by calling posix_spawn on each directory; every ENOENT miss + * still allocates a kernel PID and triggers syspolicyd provenance errors and Endpoint Security hooks. + * Rescans PATH on each spawn (async stat/access only, zero PIDs) so earlier PATH additions take effect immediately. + */ +const resolveMacosBareCommand = Effect.fnUntraced(function* ( + command: string, + env: NodeJS.ProcessEnv, + resolveExecutable: SpawnExecutableResolver, +): Effect.fn.Return { + if (resolveExecutable === resolveSpawnExecutableWithNode) { + return yield* Effect.promise(() => resolveMacosPathExecutable(command, env)); + } + const found = yield* Effect.promise(async () => resolveExecutable(command, "darwin", env)); + if ( + found === undefined || + !NodePath.posix.isAbsolute(found) || + hasRelativePosixPathEntryBefore(env.PATH, found) + ) { + return undefined; + } + return found; +}); /** * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git. - * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`. + * User-selected git on PATH still wins, children keep PATH, and lookup failures fall back to gitOnPath. */ const resolveMacosGit = Effect.fnUntraced(function* ( env: NodeJS.ProcessEnv, resolveExecutable: SpawnExecutableResolver, ) { + const gitOnPath = yield* resolveMacosBareCommand("git", env, resolveExecutable); + if (gitOnPath === undefined || !(yield* Effect.promise(() => isMacosGitShim(gitOnPath)))) { + return gitOnPath ?? "git"; + } + const locateXcodeGit = yield* XcodeGitLocation; const cache = yield* CommandResolutionCache; const cacheKey = [ "xcode-git", String(spawnResolverCacheId(resolveExecutable)), String(spawnResolverCacheId(locateXcodeGit)), - resolvePathEnvironmentVariable(env), + env.PATH ?? POSIX_DEFAULT_PATH, env.DEVELOPER_DIR ?? "", ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR); const nowNanos = yield* Clock.currentTimeNanos; @@ -1013,18 +1095,17 @@ const resolveMacosGit = Effect.fnUntraced(function* ( (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== undefined ) { - return cachedPath ?? "git"; + return cachedPath ?? gitOnPath; } } - const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); - const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const located = locateXcodeGit(env); const realGit = located !== undefined && (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); - return realGit ?? "git"; + return realGit ?? gitOnPath; }); export interface SpawnCommandOptions extends CommandAvailabilityOptions { @@ -1080,8 +1161,11 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( options: SpawnCommandOptions = {}, ): Effect.fn.Return { const platform = yield* HostProcess.Platform; - const isMacosGit = platform === "darwin" && command === "git"; - if (platform !== "win32" && !isMacosGit) { + if (platform !== "win32" && platform !== "darwin") { + return { command, args: [...args], shell: false }; + } + const explicitPath = command.includes("/") || (platform === "win32" && command.includes("\\")); + if (platform === "darwin" && (command.length === 0 || explicitPath)) { return { command, args: [...args], shell: false }; } @@ -1093,16 +1177,19 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( ? { ...hostEnvironment, ...options.env } : options.env; const resolveExecutable = yield* SpawnExecutableResolution; - if (isMacosGit) { + if (platform === "darwin") { + const resolved = + command === "git" + ? yield* resolveMacosGit(env, resolveExecutable) + : ((yield* resolveMacosBareCommand(command, env, resolveExecutable)) ?? command); return { - command: yield* resolveMacosGit(env, resolveExecutable), + command: resolved, args: [...args], shell: false, }; } // Cache successful PATH lookups. Explicit paths and misses stay uncached so // newly installed executables are discoverable immediately. - const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ "spawn", From 65c52cd73648e0bbaecba467ff1a9a270dc5039d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 11:08:53 +0000 Subject: [PATCH 2/5] fix(shared): defer macOS PATH resolution at empty or relative entries Native spawn searches empty and relative PATH entries from the child's cwd, which resolveSpawnCommand does not know, so stop resolving there instead of skipping misses in the server's cwd. Git falls back to main's lookup in that case. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/shell.test.ts | 23 ++++----- packages/shared/src/shell.ts | 85 ++++++++++++++++++++----------- 2 files changed, 65 insertions(+), 43 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 507216290a4fe..818fd67b94b73 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -881,13 +881,8 @@ console.log(JSON.stringify({ resolved, resolvedGit })); { PATH, cwd: empty, cacheGroup: `local-first-${entry}`, expected: xcodeGit }, ]; }); - // A match from an absolute entry launches that file, even when PATH also has a relative entry. - gitEntries.push({ - PATH: `.:${cwd}`, - cwd: empty, - cacheGroup: "absolute", - expected: path.join(cwd, "git"), - }); + // A match from an absolute entry stays bare `git`, even when PATH also has a relative entry. + gitEntries.push({ PATH: `.:${cwd}`, cwd: empty, cacheGroup: "absolute", expected: "git" }); const stdout = NodeChildProcess.execFileSync( process.execPath, [ @@ -1043,8 +1038,7 @@ console.log(JSON.stringify({ ...result, cached: cache.size })); { cwd: parent, encoding: "utf8", env: {} }, ); - // Only the Xcode location is cached; it does not depend on the cwd, and PATH is rescanned per spawn. - expect(JSON.parse(stdout)).toEqual({ effect: inListed, git: xcodeGit, cached: 1 }); + expect(JSON.parse(stdout)).toEqual({ effect: inListed, git: xcodeGit, cached: 0 }); }), ); @@ -1727,7 +1721,7 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { ); it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( - "uses uppercase PATH, defaults to /usr/bin:/bin when unset, and walks past missing relative entries", + "uses uppercase PATH, defaults to /usr/bin:/bin when unset, and defers on empty or relative entries", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -1745,10 +1739,13 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { Effect.provideService(HostProcess.Platform, "darwin"), ); - // An explicitly empty PATH defers to native lookup; empty or relative entries that miss are skipped. + // Empty or relative entries are searched from the child's cwd, so they defer to native lookup. expect(yield* resolveWithEnv("mytool", { PATH: "" })).toBe("mytool"); - expect(yield* resolveWithEnv("mytool", { PATH: `:${bin}` })).toBe(tool); - expect(yield* resolveWithEnv("mytool", { PATH: `rel/bin:${bin}/` })).toBe(tool); + expect(yield* resolveWithEnv("mytool", { PATH: `:${bin}` })).toBe("mytool"); + expect(yield* resolveWithEnv("mytool", { PATH: `rel/bin:${bin}` })).toBe("mytool"); + + // Empty or relative entries after a match do not change it. + expect(yield* resolveWithEnv("mytool", { PATH: `${bin}/:.` })).toBe(`${bin}/mytool`); // Lowercase Path is ignored on macOS; unset PATH falls back to /usr/bin:/bin. expect(yield* resolveWithEnv("mytool", { Path: bin })).toBe("mytool"); diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 6efa43a664432..a837deace3a66 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -1065,32 +1065,34 @@ async function isMacosGitShim(candidate: string): Promise { } } -// Walk macOS PATH entries literally so the kernel resolves `..` after symlinks as native spawn does. -// An empty component is the cwd, anchored as the default resolver does. A match in a relative -// entry defers to native spawn, which searches it from the child's cwd. Only ENOENT/ENOTDIR/EACCES -// continue the walk; other errors (such as ELOOP or EIO) defer to native spawn. +// An empty or relative POSIX PATH entry depends on the child's cwd, which resolveSpawnCommand does not take. +function hasRelativePosixPathEntryBefore( + pathValue: string | undefined, + resolvedPath: string, +): boolean { + if (pathValue === undefined) return false; + const resolvedDir = NodePath.posix.resolve(NodePath.posix.dirname(resolvedPath)); + for (const entry of pathValue.split(POSIX_PATH_DELIMITER)) { + if (entry.length === 0 || !entry.startsWith("/")) return true; + if (NodePath.posix.resolve(entry) === resolvedDir) return false; + } + return false; +} + +// Scan macOS PATH entries literally so the kernel resolves `..` after symlinks as native spawn does. +// Only continue past ENOENT/ENOTDIR/EACCES; other errors (such as ELOOP or EIO) defer to native spawn. async function resolveMacosPathExecutable( command: string, env: NodeJS.ProcessEnv, ): Promise { const pathValue = env.PATH ?? POSIX_DEFAULT_PATH; - if (pathValue === "") return undefined; for (const entry of pathValue.split(POSIX_PATH_DELIMITER)) { - let directory = entry; - if (entry === "") { - try { - directory = process.cwd(); - } catch { - continue; - } - } - const candidate = directory.endsWith("/") - ? `${directory}${command}` - : `${directory}/${command}`; + if (entry.length === 0 || !entry.startsWith("/")) return undefined; + const candidate = entry.endsWith("/") ? `${entry}${command}` : `${entry}/${command}`; try { if (!(await NodeFS.promises.stat(candidate)).isFile()) continue; await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); - return NodePath.posix.isAbsolute(candidate) ? candidate : undefined; + return candidate; } catch (error) { if (!isPosixPathScanContinueError(error)) return undefined; } @@ -1113,33 +1115,46 @@ const resolveMacosBareCommand = Effect.fnUntraced(function* ( return yield* Effect.promise(() => resolveMacosPathExecutable(command, env)); } const found = yield* Effect.promise(async () => resolveExecutable(command, "darwin", env)); - return found !== undefined && NodePath.posix.isAbsolute(found) ? found : undefined; + if ( + found === undefined || + !NodePath.posix.isAbsolute(found) || + hasRelativePosixPathEntryBefore(env.PATH, found) + ) { + return undefined; + } + return found; }); /** * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git. - * User-selected git on PATH still wins, children keep PATH, and lookup failures fall back to gitOnPath. + * User-selected git on PATH still wins and children keep PATH. When the PATH walk defers to native + * spawn, git falls back to the default resolver's lookup. */ const resolveMacosGit = Effect.fnUntraced(function* ( env: NodeJS.ProcessEnv, resolveExecutable: SpawnExecutableResolver, ) { const gitOnPath = yield* resolveMacosBareCommand("git", env, resolveExecutable); - if (gitOnPath === undefined || !(yield* Effect.promise(() => isMacosGitShim(gitOnPath)))) { - return gitOnPath ?? "git"; - } + const isShim = + gitOnPath !== undefined && (yield* Effect.promise(() => isMacosGitShim(gitOnPath))); + if (gitOnPath !== undefined && !isShim) return gitOnPath; + const fallback = isShim ? gitOnPath : "git"; const locateXcodeGit = yield* XcodeGitLocation; const cache = yield* CommandResolutionCache; + const pathValue = resolvePathEnvironmentVariable(env); + const nowNanos = yield* Clock.currentTimeNanos; + // Read after the clock, so the lookup below starts in the directory the key names. + const cwd = pathSearchCwd(pathValue, "darwin"); const cacheKey = [ "xcode-git", String(spawnResolverCacheId(resolveExecutable)), String(spawnResolverCacheId(locateXcodeGit)), - env.PATH ?? POSIX_DEFAULT_PATH, + pathValue, env.DEVELOPER_DIR ?? "", + ...(cwd === undefined ? [] : [cwd]), ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR); - const nowNanos = yield* Clock.currentTimeNanos; - const cached = cache.get(cacheKey); + const cached = cwd === null ? undefined : cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. if (cached !== undefined && cached.expiresAtNanos > nowNanos) { const cachedPath = cached.resolvedPath; @@ -1148,17 +1163,27 @@ const resolveMacosGit = Effect.fnUntraced(function* ( (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== undefined ) { - return cachedPath ?? gitOnPath; + return cachedPath ?? fallback; } } - const located = locateXcodeGit(env); + const pathGit = isShim + ? MACOS_GIT_SHIM + : yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = pathGit === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = located !== undefined && (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located - : null; - cacheCommandResolution(cache, cacheKey, realGit, nowNanos); - return realGit ?? gitOnPath; + : // A match anchored to the cwd came through an empty PATH entry, which a child would search + // again from its own cwd; launch the file that was checked instead of bare `git`. + typeof cwd === "string" && pathGit === NodePath.posix.join(cwd, "git") + ? pathGit + : null; + // The lookups above await and the cwd can move meanwhile; cache only what the key's cwd found. + if (cwd !== null && pathSearchCwd(pathValue, "darwin") === cwd) { + cacheCommandResolution(cache, cacheKey, realGit, nowNanos); + } + return realGit ?? fallback; }); export interface SpawnCommandOptions extends CommandAvailabilityOptions { From 134d46a0ad07299540916bb86bf60568b739c346 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 11:42:08 +0000 Subject: [PATCH 3/5] fix(shared): defer macOS PATH resolution when a script's interpreter is missing posix_spawn fails such a script with ENOENT and native PATH lookup continues to later entries, so pinning its absolute path broke a working later install. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/shell.test.ts | 17 +++++++++++++- packages/shared/src/shell.ts | 38 +++++++++++++++++++++++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 818fd67b94b73..0a0d1f6125d08 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -1671,7 +1671,7 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { ); it.effect.runIf(HostProcess.Platform.defaultValue() !== "win32")( - "skips directories and non-executable files in earlier PATH entries, but stops on ELOOP", + "skips directories and non-executable files in earlier PATH entries, but defers on ELOOP or a missing interpreter", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -1703,6 +1703,21 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { ); expect(skipped).toBe(validTool); + // A script whose interpreter is missing fails posix_spawn with ENOENT, after which native + // PATH lookup continues to validTool, so resolution defers instead of pinning it. + const staleEntry = path.join(root, "stale"); + yield* fs.makeDirectory(staleEntry); + const staleTool = path.join(staleEntry, "mytool"); + yield* fs.writeFileString(staleTool, "#!/missing/interpreter\nexit 0\n"); + yield* fs.chmod(staleTool, 0o755); + const deferredOnStale = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${staleEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(deferredOnStale).toBe("mytool"); + // Symlink loop (ELOOP) stops the scan and defers to native spawn instead of skipping to validTool. const loopA = path.join(loopEntry, "loop-a"); const loopB = path.join(loopEntry, "loop-b"); diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index a837deace3a66..090f13d15ba25 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -1079,6 +1079,33 @@ function hasRelativePosixPathEntryBefore( return false; } +// posix_spawn fails a script with ENOENT when its interpreter is missing, and native PATH lookup then +// moves on to later entries, so such a candidate defers to native spawn. +async function hasLaunchableInterpreter(candidate: string): Promise { + let header: string; + try { + const handle = await NodeFS.promises.open(candidate, "r"); + try { + const { buffer, bytesRead } = await handle.read(Buffer.alloc(512), 0, 512, 0); + header = buffer.toString("latin1", 0, bytesRead); + } finally { + await handle.close(); + } + } catch { + return true; + } + if (!header.startsWith("#!")) return true; + const interpreter = /^#![ \t]*([^ \t\r\n]+)/.exec(header)?.[1]; + if (interpreter === undefined || !interpreter.startsWith("/")) return false; + try { + if (!(await NodeFS.promises.stat(interpreter)).isFile()) return false; + await NodeFS.promises.access(interpreter, NodeFS.constants.X_OK); + return true; + } catch { + return false; + } +} + // Scan macOS PATH entries literally so the kernel resolves `..` after symlinks as native spawn does. // Only continue past ENOENT/ENOTDIR/EACCES; other errors (such as ELOOP or EIO) defer to native spawn. async function resolveMacosPathExecutable( @@ -1111,14 +1138,15 @@ const resolveMacosBareCommand = Effect.fnUntraced(function* ( env: NodeJS.ProcessEnv, resolveExecutable: SpawnExecutableResolver, ): Effect.fn.Return { - if (resolveExecutable === resolveSpawnExecutableWithNode) { - return yield* Effect.promise(() => resolveMacosPathExecutable(command, env)); - } - const found = yield* Effect.promise(async () => resolveExecutable(command, "darwin", env)); + const found = + resolveExecutable === resolveSpawnExecutableWithNode + ? yield* Effect.promise(() => resolveMacosPathExecutable(command, env)) + : yield* Effect.promise(async () => resolveExecutable(command, "darwin", env)); if ( found === undefined || !NodePath.posix.isAbsolute(found) || - hasRelativePosixPathEntryBefore(env.PATH, found) + hasRelativePosixPathEntryBefore(env.PATH, found) || + !(yield* Effect.promise(() => hasLaunchableInterpreter(found))) ) { return undefined; } From 409e98ec1ae46a09d6710a2b5135546d3509525a Mon Sep 17 00:00:00 2001 From: Morgana Allen Date: Mon, 23 Nov 2026 06:44:09 -0800 Subject: [PATCH 4/5] fix(shared): key macOS git cache on effective PATH and preserve CR in shebangs - Key resolveMacosGit's cache on env.PATH ?? POSIX_DEFAULT_PATH so an unset-PATH lookup (/usr/bin:/bin) cannot collide with an explicit empty PATH="" lookup. - Preserve CR in hasLaunchableInterpreter's shebang regex because macOS XNU's exec_shell_imgact only splits on space, tab, or newline (not CR), so a CRLF shebang like #!/bin/sh\r\n fails posix_spawn with ENOENT and must defer to native PATH lookup. - Add regression tests for both cases. Co-authored-by: Gemini 4 Neon Agent-Harness: Antigravity Agent-ADE: T3Code --- packages/shared/src/shell.test.ts | 48 +++++++++++++++++++++++++++++++ packages/shared/src/shell.ts | 6 ++-- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 0a0d1f6125d08..b68fdfed14eff 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -1628,6 +1628,39 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { expect(host.xcrunCalls).toBe(2); }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); + + it.effect("does not reuse an unset-PATH Xcode git cache entry for an explicit empty PATH", () => + Effect.gen(function* () { + const files = new Set(["/usr/bin/git", XCODE_GIT]); + let xcrunCalls = 0; + const resolveExecutable = ( + command: string, + _platform: NodeJS.Platform, + lookupEnv: NodeJS.ProcessEnv, + ) => { + if (command !== "git") return files.has(command) ? command : undefined; + return lookupEnv.PATH === "" ? undefined : "/usr/bin/git"; + }; + const locateXcodeGit = () => { + xcrunCalls += 1; + return XCODE_GIT; + }; + const resolveWithEnv = (env: NodeJS.ProcessEnv) => + resolveSpawnCommand("git", ["status"], { env }).pipe( + Effect.map((resolved) => resolved.command), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(SpawnExecutableResolution, resolveExecutable), + Effect.provideService(XcodeGitLocation, locateXcodeGit), + ); + + expect(yield* resolveWithEnv({})).toBe(XCODE_GIT); + expect(yield* resolveWithEnv({})).toBe(XCODE_GIT); + expect(xcrunCalls).toBe(1); + + expect(yield* resolveWithEnv({ PATH: "" })).toBe("git"); + expect(xcrunCalls).toBe(1); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); }); describe("macOS bare commands", () => { @@ -1718,6 +1751,21 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { ); expect(deferredOnStale).toBe("mytool"); + // macOS treats CR as part of the interpreter path (not whitespace/EOL), so `#!/bin/sh\r\n` + // fails posix_spawn with ENOENT and native PATH lookup continues to validTool. + const crlfEntry = path.join(root, "crlf"); + yield* fs.makeDirectory(crlfEntry); + const crlfTool = path.join(crlfEntry, "mytool"); + yield* fs.writeFileString(crlfTool, "#!/bin/sh\r\nexit 0\n"); + yield* fs.chmod(crlfTool, 0o755); + const deferredOnCrlf = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${crlfEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(deferredOnCrlf).toBe("mytool"); + // Symlink loop (ELOOP) stops the scan and defers to native spawn instead of skipping to validTool. const loopA = path.join(loopEntry, "loop-a"); const loopB = path.join(loopEntry, "loop-b"); diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 090f13d15ba25..9e7d0cb134888 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -1095,7 +1095,9 @@ async function hasLaunchableInterpreter(candidate: string): Promise { return true; } if (!header.startsWith("#!")) return true; - const interpreter = /^#![ \t]*([^ \t\r\n]+)/.exec(header)?.[1]; + // macOS XNU's exec_shell_imgact only splits on space, tab, or newline (not CR), so a CRLF + // shebang like `#!/bin/sh\r\n` looks up `/bin/sh\r` (ENOENT) and must defer to native spawn. + const interpreter = header.match(/^#![ \t]*([^ \t\n]+)/)?.[1]; if (interpreter === undefined || !interpreter.startsWith("/")) return false; try { if (!(await NodeFS.promises.stat(interpreter)).isFile()) return false; @@ -1170,7 +1172,7 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const locateXcodeGit = yield* XcodeGitLocation; const cache = yield* CommandResolutionCache; - const pathValue = resolvePathEnvironmentVariable(env); + const pathValue = env.PATH ?? POSIX_DEFAULT_PATH; const nowNanos = yield* Clock.currentTimeNanos; // Read after the clock, so the lookup below starts in the directory the key names. const cwd = pathSearchCwd(pathValue, "darwin"); From 433bd4bc48f26669522e48a644e9cf3bcfdbd45b Mon Sep 17 00:00:00 2001 From: Morgana Allen Date: Mon, 23 Nov 2026 22:29:45 -0800 Subject: [PATCH 5/5] fix(shared): defer unreadable macOS executables to native PATH lookup - Return false from hasLaunchableInterpreter when the candidate header cannot be opened/read (e.g. mode 0111 execute-only scripts) so native PATH lookup can still continue past a broken script. - Run hasLaunchableInterpreter inside resolveMacosPathExecutable so injected virtual SpawnExecutableResolution mocks in tests do not hit the host filesystem. - Add a mode 0111 regression test in packages/shared/src/shell.test.ts. Co-authored-by: Gemini 4 Neon Agent-Harness: Antigravity Agent-ADE: T3Code --- packages/shared/src/shell.test.ts | 17 +++++++++++++++++ packages/shared/src/shell.ts | 18 +++++++++--------- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index b68fdfed14eff..30c7cd829f8be 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -1766,6 +1766,23 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { ); expect(deferredOnCrlf).toBe("mytool"); + // An execute-only file (0111) cannot have its header inspected, so defer to native + // lookup rather than pinning a script whose interpreter may be missing. + if (process.getuid?.() !== 0) { + const execOnlyEntry = path.join(root, "exec-only"); + yield* fs.makeDirectory(execOnlyEntry); + const execOnlyTool = path.join(execOnlyEntry, "mytool"); + yield* fs.writeFileString(execOnlyTool, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(execOnlyTool, 0o111); + const deferredOnExecOnly = yield* resolveSpawnCommand("mytool", [], { + env: { PATH: `${execOnlyEntry}:${validEntry}` }, + }).pipe( + Effect.map((r) => r.command), + Effect.provideService(HostProcess.Platform, "darwin"), + ); + expect(deferredOnExecOnly).toBe("mytool"); + } + // Symlink loop (ELOOP) stops the scan and defers to native spawn instead of skipping to validTool. const loopA = path.join(loopEntry, "loop-a"); const loopB = path.join(loopEntry, "loop-b"); diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 9e7d0cb134888..994cf25bcc92e 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -1080,7 +1080,7 @@ function hasRelativePosixPathEntryBefore( } // posix_spawn fails a script with ENOENT when its interpreter is missing, and native PATH lookup then -// moves on to later entries, so such a candidate defers to native spawn. +// moves on to later entries, so any candidate whose header cannot be verified defers to native spawn. async function hasLaunchableInterpreter(candidate: string): Promise { let header: string; try { @@ -1092,7 +1092,7 @@ async function hasLaunchableInterpreter(candidate: string): Promise { await handle.close(); } } catch { - return true; + return false; } if (!header.startsWith("#!")) return true; // macOS XNU's exec_shell_imgact only splits on space, tab, or newline (not CR), so a CRLF @@ -1121,10 +1121,11 @@ async function resolveMacosPathExecutable( try { if (!(await NodeFS.promises.stat(candidate)).isFile()) continue; await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); - return candidate; } catch (error) { if (!isPosixPathScanContinueError(error)) return undefined; + continue; } + return (await hasLaunchableInterpreter(candidate)) ? candidate : undefined; } return undefined; } @@ -1140,15 +1141,14 @@ const resolveMacosBareCommand = Effect.fnUntraced(function* ( env: NodeJS.ProcessEnv, resolveExecutable: SpawnExecutableResolver, ): Effect.fn.Return { - const found = - resolveExecutable === resolveSpawnExecutableWithNode - ? yield* Effect.promise(() => resolveMacosPathExecutable(command, env)) - : yield* Effect.promise(async () => resolveExecutable(command, "darwin", env)); + if (resolveExecutable === resolveSpawnExecutableWithNode) { + return yield* Effect.promise(() => resolveMacosPathExecutable(command, env)); + } + const found = yield* Effect.promise(async () => resolveExecutable(command, "darwin", env)); if ( found === undefined || !NodePath.posix.isAbsolute(found) || - hasRelativePosixPathEntryBefore(env.PATH, found) || - !(yield* Effect.promise(() => hasLaunchableInterpreter(found))) + hasRelativePosixPathEntryBefore(env.PATH, found) ) { return undefined; }