diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 033d83bc5f5c0..a637051ece58b 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -7,6 +7,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, expect, it } from "@effect/vitest"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -186,8 +187,12 @@ const exitedAgent = ( const stopsOf = (calls: ReadonlyArray>) => calls.filter(([, verb]) => verb === "stop"); -const launchCodex = (scope: Effect.Success, threadId: string) => - makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe( +const launchCodex = ( + scope: Effect.Success, + threadId: string, + env?: NodeJS.ProcessEnv, +) => + makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId, env }).pipe( Effect.provideService(AgentScope, scope), Effect.provideService(HostProcess.Platform, "linux"), Effect.map((command) => { @@ -227,7 +232,14 @@ describe("AgentScope service", () => { units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" }); expect(yield* scope.oomKilled("a")).toBe(true); - const codex = yield* launchCodex(scope, "a"); + const executable = String(agent.args.at(-1)); + const codex = yield* launchCodex(scope, "a", { + PATH: NodePath.relative(process.cwd(), NodePath.dirname(executable)), + }); + // Anchored to the cwd for systemd-run, with its ".." kept; it names the same file. + const anchored = String(codex.args.at(-2)); + expect(NodePath.isAbsolute(anchored)).toBe(true); + expect(NodePath.resolve(anchored)).toBe(executable); expect(codex.args).toContain("--property=OOMPolicy=continue"); expect(codex.args).not.toContain("--property=OOMPolicy=stop"); expect(codex.args).toContain("--property=TimeoutStopSec=10s"); @@ -243,6 +255,33 @@ describe("AgentScope service", () => { ), ); + it.effect.skipIf(!symlinksSupported)( + "keeps a symlinked parent in absolute and relative executable paths", + () => + withFakeSystemd(({ scope }) => + Effect.gen(function* () { + const plain = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "s" }); + const bin = NodePath.dirname(String(plain.args.at(-1))); + NodeFS.mkdirSync(NodePath.join(bin, "real", "sub"), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(bin, "real", "agent"), "", { mode: 0o755 }); + NodeFS.symlinkSync(NodePath.join(bin, "real", "sub"), NodePath.join(bin, "link")); + // The kernel follows the link before "..", so this names real/agent, not bin/agent. + const command = `${NodePath.join(bin, "link")}/../agent`; + const wrapped = yield* scope.wrap({ command, args: [], name: "t", threadId: "s" }); + expect(wrapped.args.at(-1)).toBe(command); + // A relative path is anchored to the cwd the same way, without collapsing "..". + const relative = `${NodePath.relative(process.cwd(), NodePath.join(bin, "link"))}/../agent`; + const anchored = yield* scope.wrap({ + command: relative, + args: [], + name: "t", + threadId: "s", + }); + expect(anchored.args.at(-1)).toBe(`${process.cwd()}${NodePath.sep}${relative}`); + }), + ), + ); + it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])( "Force stop kills a thread's own scope but never a shared Codex scope (OOM policy $oomPolicy)", ({ oomPolicy }) => diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index 4bbb7d159cf0b..8a62f538cdee2 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -459,7 +459,15 @@ export const make = Effect.gen(function* () { ...(owned ? [] : ["--collect"]), ], }; - return { ...agentScopeCommand({ command: resolved, args, scope: systemdScope }), unit }; + // systemd-run does not search the caller's cwd, so anchor a relative path to it. Keep ".." + // as spelled: collapsing it would skip a symlinked parent directory. + const executable = path.isAbsolute(resolved) + ? resolved + : `${process.cwd()}${path.sep}${resolved}`; + return { + ...agentScopeCommand({ command: executable, args, scope: systemdScope }), + unit, + }; }), oomKilled, stop, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 8f81723486f55..9da565c9b7012 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -650,6 +650,34 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }), ); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "probes a relative PATH entry in the directory its search recorded", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-relative-probe-" }); + const command = "t3-relative-probe-cli"; + yield* fs.writeFileString(path.join(dir, command), "#!/bin/sh\n", { mode: 0o755 }); + const relative = path.relative(process.cwd(), dir); + const probed: Array = []; + const resolved = yield* resolveCommandPath(command, { env: { PATH: relative } }).pipe( + Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideService(FileSystem.FileSystem, { + ...fs, + stat: (file) => { + probed.push(file); + return fs.stat(file); + }, + }), + ); + // The result keeps its PATH spelling; the probe is absolute, so a later chdir can't move it. + expect(resolved).toBe(path.join(relative, command)); + expect(probed).toContain(path.join(path.resolve(relative), command)); + expect(probed.filter((file) => !path.isAbsolute(file))).toEqual([]); + }), + ); + // Seconds; the tests below run their clock a minute later, past the window in which a listing is not kept. const AGED_MTIME = 4_102_444_800; const afterAgedMtime = TestClock.setTime((AGED_MTIME + 60) * 1000); @@ -761,6 +789,288 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ); }), ); + + // Candidates are checked against the process cwd, so the lookup runs in a child with a temp cwd. + const resolveInChild = ` +import { createRequire } from "node:module"; +const [shellPath, command, rawPaths, rawGitPaths, gitShim, xcodeGit] = process.argv.slice(1); +const requireFromShell = createRequire(shellPath); +const Effect = await import(requireFromShell.resolve("effect/Effect")); +const { layer } = await import(requireFromShell.resolve("@effect/platform-node/NodeServices")); +const HostProcess = await import(shellPath.replace(/shell\\.ts$/, "HostProcess.ts")); +const Shell = await import(shellPath); +const resolved = {}; +const resolvedGit = {}; +const defaultResolver = Shell.SpawnExecutableResolution.defaultValue(); +const resolveExecutable = async (...args) => { + const found = await defaultResolver(...args); + return found === gitShim ? "/usr/bin/git" : found; +}; +const locateXcodeGit = () => xcodeGit; +await Effect.runPromise(Effect.gen(function* () { + const caches = new Map(); + for (const [label, { PATH, cwd, cacheGroup }] of Object.entries(JSON.parse(rawPaths))) { + process.chdir(cwd); + let cache = caches.get(cacheGroup); + if (!cache) caches.set(cacheGroup, cache = new Map()); + resolved[label] = { + effect: yield* Shell.resolveCommandPath(command, { env: { PATH } }).pipe( + Effect.provideService(HostProcess.Platform, process.platform), + Effect.provideService(Shell.CommandResolutionCache, cache), + ), + spawn: (yield* Effect.promise(async () => Shell.SpawnExecutableResolution.defaultValue()(command, process.platform, { PATH }))) ?? null, + }; + } + for (const [label, { PATH, cwd, cacheGroup }] of Object.entries(JSON.parse(rawGitPaths))) { + process.chdir(cwd); + let cache = caches.get(cacheGroup); + if (!cache) caches.set(cacheGroup, cache = new Map()); + resolvedGit[label] = yield* Shell.resolveSpawnCommand("git", ["status"], { env: { PATH } }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(Shell.SpawnExecutableResolution, resolveExecutable), + Effect.provideService(Shell.XcodeGitLocation, locateXcodeGit), + Effect.provideService(Shell.CommandResolutionCache, cache), + ); + } +}).pipe(Effect.provide(layer))); +console.log(JSON.stringify({ resolved, resolvedGit })); +`; + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "searches the current directory for empty POSIX PATH components across cached lookups", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // Real paths: the child's process.cwd() reports them, and anchored matches start with it. + const cwd = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-cwd-" }), + ); + const listed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-listed-" }); + const empty = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-absent-" }), + ); + const command = "t3-empty-path-cli"; + const inCwd = path.join(cwd, command); + const inListed = path.join(listed, command); + const gitShim = path.join(listed, "git"); + const xcodeGit = path.join(listed, "xcode-git"); + yield* fs.writeFileString(inCwd, "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.writeFileString(inListed, "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.writeFileString(path.join(cwd, "git"), "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.writeFileString(gitShim, "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.writeFileString(xcodeGit, "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.utimes(cwd, 4_102_444_800, 4_102_444_800); + yield* fs.utimes(empty, 4_102_444_800, 4_102_444_800); + const missing = path.join(cwd, "missing"); + + const searches = { + dot: { PATH: ".", expected: inCwd }, + absolute: { PATH: listed, expected: inListed }, + leading: { PATH: `:${missing}`, expected: inCwd }, + trailing: { PATH: `${missing}:`, expected: inCwd }, + interior: { PATH: `${missing}::${missing}-2`, expected: inCwd }, + leadingBeforeListed: { PATH: `:${listed}`, expected: inCwd }, + listedBeforeTrailing: { PATH: `${listed}:`, expected: inListed }, + dotBeforeEmpty: { PATH: `.:${missing}:`, expected: inCwd }, + emptyBeforeDot: { PATH: `:.:${missing}`, expected: inCwd }, + entirelyEmpty: { PATH: "", expected: null }, + whitespaceOnly: { PATH: `${missing}: `, expected: null }, + quotedEmpty: { PATH: `${missing}:""`, expected: null }, + }; + + const cachedSearches = { + cachedMiss: { PATH: `:${missing}`, cwd: empty, cacheGroup: "miss", expected: null }, + afterMiss: { PATH: `:${missing}`, cwd, cacheGroup: "miss", expected: inCwd }, + cachedHit: { PATH: `:${missing}`, cwd, cacheGroup: "hit", expected: inCwd }, + afterHit: { PATH: `:${missing}`, cwd: empty, cacheGroup: "hit", expected: null }, + cachedListed: { + PATH: `:${listed}`, + cwd: empty, + cacheGroup: "listed", + expected: inListed, + }, + beforeListed: { PATH: `:${listed}`, cwd, cacheGroup: "listed", expected: inCwd }, + cachedLocal: { PATH: `:${listed}`, cwd, cacheGroup: "local", expected: inCwd }, + afterLocal: { PATH: `:${listed}`, cwd: empty, cacheGroup: "local", expected: inListed }, + }; + const entries = [ + ...Object.entries(cachedSearches), + ...Object.entries(searches).map( + ([label, row]) => [label, { ...row, cwd, cacheGroup: label }] as const, + ), + ]; + const gitEntries = ["", "."].flatMap((entry) => { + const PATH = `${entry}:${listed}`; + // An empty entry launches the local git it found; "." keeps its relative spelling. + const localGit = entry === "" ? path.join(cwd, "git") : "git"; + return [ + { PATH, cwd: empty, cacheGroup: `xcode-first-${entry}`, expected: xcodeGit }, + { PATH, cwd, cacheGroup: `xcode-first-${entry}`, expected: localGit }, + { PATH, cwd, cacheGroup: `local-first-${entry}`, expected: localGit }, + { PATH, cwd: empty, cacheGroup: `local-first-${entry}`, expected: xcodeGit }, + ]; + }); + // 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, + [ + "--input-type=module", + "-e", + resolveInChild, + path.join(import.meta.dirname, "shell.ts"), + command, + JSON.stringify( + Object.fromEntries( + entries.map(([label, row]) => [ + label, + { + PATH: row.PATH, + cwd: row.cwd, + cacheGroup: row.cacheGroup, + }, + ]), + ), + ), + JSON.stringify(gitEntries), + gitShim, + xcodeGit, + ], + { cwd, encoding: "utf8", env: {} }, + ); + const { + resolved, + resolvedGit, + }: { + resolved: Record; + resolvedGit: Record; + } = JSON.parse(stdout); + + // A relative result is relative to the child's cwd. + const anchored = (found: string | null, directory: string) => + found === null ? null : path.resolve(directory, found); + const directories = Object.fromEntries(entries.map(([label, row]) => [label, row.cwd])); + expect( + Object.fromEntries( + Object.entries(resolved).map(([label, found]) => { + const directory = directories[label]; + if (directory === undefined) throw new Error(`Unexpected resolver case: ${label}`); + return [ + label, + { + effect: anchored(found.effect, directory), + spawn: anchored(found.spawn, directory), + }, + ]; + }), + ), + ).toEqual( + Object.fromEntries( + entries.map(([label, row]) => [label, { effect: row.expected, spawn: row.expected }]), + ), + ); + // A match through an empty component comes back absolute, so callers can launch it from + // another cwd or through a wrapper; a literal "." keeps main's relative spelling. + for (const label of [ + "leading", + "trailing", + "interior", + "leadingBeforeListed", + "afterMiss", + "cachedHit", + "beforeListed", + "cachedLocal", + "emptyBeforeDot", + ]) { + expect(resolved[label], label).toEqual({ effect: inCwd, spawn: inCwd }); + } + for (const label of ["dot", "dotBeforeEmpty"]) { + expect(resolved[label], label).toEqual({ effect: command, spawn: command }); + } + expect(resolvedGit).toEqual( + Object.fromEntries( + gitEntries.map((row, index) => [ + String(index), + { command: row.expected, args: ["status"], shell: false }, + ]), + ), + ); + }), + ); + + // Deleting the working directory makes process.cwd() throw, so this also runs in a child. + const resolveWithoutCwd = ` +import { createRequire } from "node:module"; +import * as NodeFS from "node:fs"; +const [shellPath, command, PATH, removed, gitShim, xcodeGit] = process.argv.slice(1); +const requireFromShell = createRequire(shellPath); +const Effect = await import(requireFromShell.resolve("effect/Effect")); +const { layer } = await import(requireFromShell.resolve("@effect/platform-node/NodeServices")); +const HostProcess = await import(shellPath.replace(/shell\\.ts$/, "HostProcess.ts")); +const Shell = await import(shellPath); +const defaultResolver = Shell.SpawnExecutableResolution.defaultValue(); +const resolveExecutable = async (...args) => { + const found = await defaultResolver(...args); + return found === gitShim ? "/usr/bin/git" : found; +}; +process.chdir(removed); +NodeFS.rmdirSync(removed); +const cache = new Map(); +const result = await Effect.runPromise(Effect.gen(function* () { + const effect = yield* Shell.resolveCommandPath(command, { env: { PATH } }).pipe( + Effect.provideService(HostProcess.Platform, process.platform), + ); + const git = yield* Shell.resolveSpawnCommand("git", ["status"], { env: { PATH } }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(Shell.SpawnExecutableResolution, resolveExecutable), + Effect.provideService(Shell.XcodeGitLocation, () => xcodeGit), + ); + return { effect, git: git.command }; +}).pipe( + Effect.provideService(Shell.CommandResolutionCache, cache), + Effect.provide(layer), +)); +console.log(JSON.stringify({ ...result, cached: cache.size })); +`; + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "searches absolute PATH entries and caches nothing when the working directory is gone", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const listed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-gone-cwd-listed-" }); + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-gone-cwd-parent-" }); + const removed = path.join(parent, "removed"); + yield* fs.makeDirectory(removed); + const command = "t3-gone-cwd-cli"; + const inListed = path.join(listed, command); + const gitShim = path.join(listed, "git"); + const xcodeGit = path.join(listed, "xcode-git"); + yield* fs.writeFileString(inListed, "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.writeFileString(gitShim, "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.writeFileString(xcodeGit, "#!/bin/sh\n", { mode: 0o755 }); + + const stdout = NodeChildProcess.execFileSync( + process.execPath, + [ + "--input-type=module", + "-e", + resolveWithoutCwd, + path.join(import.meta.dirname, "shell.ts"), + command, + `:${listed}`, + removed, + gitShim, + xcodeGit, + ], + { cwd: parent, encoding: "utf8", env: {} }, + ); + + expect(JSON.parse(stdout)).toEqual({ effect: inListed, git: xcodeGit, cached: 0 }); + }), + ); }); describe("runsGitWithoutConsole", () => { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 0ba42dc3078d6..7d874f6cfb443 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -110,8 +110,11 @@ async function resolveSpawnExecutableWithNode( return undefined; } - for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { - const normalizedPathEntry = normalizePathEntry(pathEntry, platform); + const pathValue = readEnvPath(env) ?? ""; + for (const pathEntry of pathValue.split(pathDelimiterForPlatform(platform))) { + // A raw empty component of a nonempty POSIX PATH is the current directory. + const emptyComponent = pathEntry === "" && pathValue !== "" && platform !== "win32"; + const normalizedPathEntry = emptyComponent ? "." : normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; const names = platform === "win32" @@ -120,7 +123,17 @@ async function resolveSpawnExecutableWithNode( for (const candidate of candidates) { if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (await isExecutable(candidatePath)) return candidatePath; + // Anchored before the probe: callers may launch it from another cwd or through a wrapper, + // and the cwd can change while the probe waits. + let probePath = candidatePath; + if (emptyComponent) { + try { + probePath = path.resolve(candidatePath); + } catch { + continue; + } + } + if (await isExecutable(probePath)) return probePath; } } return undefined; @@ -754,6 +767,40 @@ const isExecutableFile = Effect.fnUntraced(function* ( return canExecuteFile(filePath); }); +// Keep case variants: Windows can make PATH directories case-sensitive. +function pathEntriesForPlatform(pathValue: string, platform: NodeJS.Platform): string[] { + const pathEntries: string[] = []; + const seenPathEntries = new Set(); + for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) { + // A raw empty component of a nonempty POSIX PATH is the current directory. + const pathEntry = + entry === "" && pathValue !== "" && platform !== "win32" + ? "." + : normalizePathEntry(entry, platform); + if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue; + + seenPathEntries.add(pathEntry); + pathEntries.push(pathEntry); + } + return pathEntries; +} + +// Relative POSIX PATH entries resolve against the working directory, so caches keyed by them include it. +// null: a relative entry is present but the working directory cannot be read, so nothing is cached. +function pathSearchCwd(pathValue: string, platform: NodeJS.Platform): string | null | undefined { + if (platform === "win32") return undefined; + if ( + pathEntriesForPlatform(pathValue, platform).every((entry) => NodePath.posix.isAbsolute(entry)) + ) { + return undefined; + } + try { + return process.cwd(); + } catch { + return null; + } +} + // Called within the traced command resolvers. const findOnPath = Effect.fnUntraced(function* ( pathValue: string, @@ -761,34 +808,43 @@ const findOnPath = Effect.fnUntraced(function* ( platform: NodeJS.Platform, windowsPathExtensions: ReadonlyArray, isLast: (match: string) => boolean, + // The caller's snapshot, so a cache key and the search it stores agree on the directory. + cwd: string | null | undefined, ): Effect.fn.Return, never, FileSystem.FileSystem | Path.Path> { const path = yield* Path.Path; - // Keep case variants: Windows can make PATH directories case-sensitive. - const pathEntries: string[] = []; - const seenPathEntries = new Set(); - for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) { - const pathEntry = normalizePathEntry(entry, platform); - if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue; + const pathEntries = pathEntriesForPlatform(pathValue, platform); - seenPathEntries.add(pathEntry); - pathEntries.push(pathEntry); - } + // A match through an empty component is anchored: callers may launch it from another cwd or + // through a wrapper. A literal "." keeps its relative spelling; the first of the two wins, as + // in the deduplicated walk. + const anchorsCwd = + typeof cwd === "string" && + pathValue + .split(pathDelimiterForPlatform(platform)) + .find((entry) => entry === "" || entry === ".") === ""; // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe. const listings = platform === "win32" ? yield* PathDirectoryListings : undefined; const matches: string[] = []; for (const pathEntry of pathEntries) { - let listing = listings && (yield* Cache.get(listings, pathEntry)); - if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) { - yield* Cache.invalidate(listings, pathEntry); - listing = yield* Cache.get(listings, pathEntry); + const directory = cwd === undefined || cwd === null ? pathEntry : path.resolve(cwd, pathEntry); + // Without a readable cwd a relative entry has no stable directory, so it skips the listing cache. + const uncached = cwd === null && !NodePath.posix.isAbsolute(pathEntry); + let listing = listings && !uncached ? yield* Cache.get(listings, directory) : undefined; + if (listings && listing?.names && listing.modified !== (yield* directoryMtime(directory))) { + yield* Cache.invalidate(listings, directory); + listing = yield* Cache.get(listings, directory); } for (const candidate of commandCandidates) { if (isAbsentFromListing(listing?.names, candidate)) continue; const candidatePath = path.join(pathEntry, candidate); - if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) { - matches.push(candidatePath); - if (isLast(candidatePath)) return matches; + // Probe where the listing looked, even if the process changes directory meanwhile. + const probePath = typeof cwd === "string" ? path.join(directory, candidate) : candidatePath; + if (yield* isExecutableFile(probePath, platform, windowsPathExtensions)) { + const match = + anchorsCwd && pathEntry === "." ? path.join(directory, candidate) : candidatePath; + matches.push(match); + if (isLast(match)) return matches; break; } } @@ -825,12 +881,17 @@ const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlat return null; } - const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join( - COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR, - ); + const cwd = pathSearchCwd(pathValue, platform); + const cacheKey = [ + platform, + pathValue, + windowsPathExtensions.join(";"), + command, + ...(cwd === undefined ? [] : [cwd]), + ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR); const cache = yield* CommandResolutionCache; const nowNanos = yield* Clock.monotonicTimeNanos; - const cached = cache.get(cacheKey); + const cached = cwd === null ? undefined : cache.get(cacheKey); if (cached !== undefined && cached.expiresAtNanos > nowNanos) { return cached.resolvedPath; } @@ -841,8 +902,9 @@ const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlat platform, windowsPathExtensions, () => true, + cwd, ); - cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos); + if (cwd !== null) cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos); return resolvedPath; }); @@ -865,12 +927,14 @@ export const resolveCommandPaths = Effect.fn("shell.resolveCommandPaths")(functi const platform = yield* HostProcess.Platform; const env = options.env ?? (yield* HostProcess.Environment); const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; + const pathValue = resolvePathEnvironmentVariable(env); return yield* findOnPath( - resolvePathEnvironmentVariable(env), + pathValue, resolveCommandCandidates(command, platform, windowsPathExtensions, path.extname), platform, windowsPathExtensions, options.until, + pathSearchCwd(pathValue, platform), ); }); @@ -996,15 +1060,19 @@ const resolveMacosGit = Effect.fnUntraced(function* ( ) { 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)), - resolvePathEnvironmentVariable(env), + 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; @@ -1016,14 +1084,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( return cachedPath ?? "git"; } } - const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); - const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const pathGit = 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); + : // 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 ?? "git"; });