From 686e7f12f69980c1aaf85f9b457944f88e90c8a1 Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Sat, 31 Oct 2026 07:24:22 +0100 Subject: [PATCH 01/11] fix(shared): search cwd for empty POSIX PATH components --- packages/shared/src/shell.test.ts | 87 +++++++++++++++++++++++++++++++ packages/shared/src/shell.ts | 15 ++++-- 2 files changed, 99 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index ac587dd1b5cda..14cf269900c60 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -659,6 +659,93 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { Effect.provideService(CommandResolutionCache, new Map()), ), ); + + // 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] = 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 = {}; +for (const [label, PATH] of Object.entries(JSON.parse(rawPaths))) { + resolved[label] = { + effect: await Effect.runPromise( + Shell.resolveCommandPath(command, { env: { PATH } }).pipe( + Effect.provideService(HostProcess.Platform, process.platform), + Effect.provideService(Shell.CommandResolutionCache, new Map()), + Effect.provide(layer), + ), + ), + spawn: Shell.SpawnExecutableResolution.defaultValue()(command, process.platform, { PATH }) ?? null, + }; +} +console.log(JSON.stringify(resolved)); +`; + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "searches the current directory for empty components of a nonempty POSIX PATH", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-cwd-" }); + const listed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-listed-" }); + const command = "t3-empty-path-cli"; + const inCwd = path.join(cwd, command); + const inListed = path.join(listed, command); + yield* fs.writeFileString(inCwd, "#!/bin/sh\n", { mode: 0o755 }); + yield* fs.writeFileString(inListed, "#!/bin/sh\n", { mode: 0o755 }); + 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 }, + entirelyEmpty: { PATH: "", expected: null }, + whitespaceOnly: { PATH: `${missing}: `, expected: null }, + quotedEmpty: { PATH: `${missing}:""`, expected: null }, + }; + + const entries = Object.entries(searches); + 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, row.PATH]))), + ], + { cwd, encoding: "utf8", env: {} }, + ); + const resolved: Record = + JSON.parse(stdout); + + // A relative result is relative to the child's cwd. + const anchored = (found: string | null) => + found === null ? null : path.resolve(cwd, found); + expect( + Object.fromEntries( + Object.entries(resolved).map(([label, found]) => [ + label, + { effect: anchored(found.effect), spawn: anchored(found.spawn) }, + ]), + ), + ).toEqual( + Object.fromEntries( + entries.map(([label, row]) => [label, { effect: row.expected, spawn: row.expected }]), + ), + ); + }), + ); }); describe("runsGitWithoutConsole", () => { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index d9343fce09fef..01b3e7217cd16 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -105,8 +105,13 @@ function resolveSpawnExecutableWithNode( return candidates.find(isExecutable); } - 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 normalizedPathEntry = + pathEntry === "" && pathValue !== "" && platform !== "win32" + ? "." + : normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; for (const candidate of candidates) { const candidatePath = path.join(normalizedPathEntry, candidate); @@ -676,7 +681,11 @@ const findOnPath = Effect.fnUntraced(function* ( const pathEntries: string[] = []; const seenPathEntries = new Set(); for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) { - const pathEntry = normalizePathEntry(entry, 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); From 4b1f3c594c83d01e2607da0630b95b7932693100 Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Sat, 31 Oct 2026 12:56:27 +0100 Subject: [PATCH 02/11] fix(shared): scope relative PATH caches to the working directory --- packages/shared/src/shell.test.ts | 83 ++++++++++++++++++++++++------- packages/shared/src/shell.ts | 59 ++++++++++++++++------ 2 files changed, 107 insertions(+), 35 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 14cf269900c60..c4ca8dbd6da93 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -670,34 +670,40 @@ const { layer } = await import(requireFromShell.resolve("@effect/platform-node/N const HostProcess = await import(shellPath.replace(/shell\\.ts$/, "HostProcess.ts")); const Shell = await import(shellPath); const resolved = {}; -for (const [label, PATH] of Object.entries(JSON.parse(rawPaths))) { - resolved[label] = { - effect: await Effect.runPromise( - Shell.resolveCommandPath(command, { env: { PATH } }).pipe( +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, new Map()), - Effect.provide(layer), + Effect.provideService(Shell.CommandResolutionCache, cache), ), - ), - spawn: Shell.SpawnExecutableResolution.defaultValue()(command, process.platform, { PATH }) ?? null, - }; -} + spawn: Shell.SpawnExecutableResolution.defaultValue()(command, process.platform, { PATH }) ?? null, + }; + } +}).pipe(Shell.withPathDirectoryListings, Effect.provide(layer))); console.log(JSON.stringify(resolved)); `; it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( - "searches the current directory for empty components of a nonempty POSIX PATH", + "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; const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-cwd-" }); const listed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-listed-" }); + const empty = 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); yield* fs.writeFileString(inCwd, "#!/bin/sh\n", { mode: 0o755 }); yield* fs.writeFileString(inListed, "#!/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 = { @@ -713,7 +719,27 @@ console.log(JSON.stringify(resolved)); quotedEmpty: { PATH: `${missing}:""`, expected: null }, }; - const entries = Object.entries(searches); + 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 stdout = NodeChildProcess.execFileSync( process.execPath, [ @@ -722,7 +748,18 @@ console.log(JSON.stringify(resolved)); resolveInChild, path.join(import.meta.dirname, "shell.ts"), command, - JSON.stringify(Object.fromEntries(entries.map(([label, row]) => [label, row.PATH]))), + JSON.stringify( + Object.fromEntries( + entries.map(([label, row]) => [ + label, + { + PATH: row.PATH, + cwd: row.cwd, + cacheGroup: row.cacheGroup, + }, + ]), + ), + ), ], { cwd, encoding: "utf8", env: {} }, ); @@ -730,14 +767,22 @@ console.log(JSON.stringify(resolved)); JSON.parse(stdout); // A relative result is relative to the child's cwd. - const anchored = (found: string | null) => - found === null ? null : path.resolve(cwd, found); + 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]) => [ - label, - { effect: anchored(found.effect), spawn: anchored(found.spawn) }, - ]), + 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( diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 01b3e7217cd16..1721692f62ad6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -668,16 +668,8 @@ const isExecutableFile = Effect.fnUntraced(function* ( return canExecuteFile(filePath); }); -// Called within the traced command resolvers. -const findOnPath = Effect.fnUntraced(function* ( - pathValue: string, - commandCandidates: ReadonlyArray, - platform: NodeJS.Platform, - windowsPathExtensions: ReadonlyArray, - isLast: (match: string) => boolean, -): Effect.fn.Return, never, FileSystem.FileSystem | Path.Path> { - const path = yield* Path.Path; - // Keep case variants: Windows can make PATH directories case-sensitive. +// 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))) { @@ -691,14 +683,40 @@ const findOnPath = Effect.fnUntraced(function* ( seenPathEntries.add(pathEntry); pathEntries.push(pathEntry); } + return pathEntries; +} + +// Relative POSIX PATH entries resolve against the working directory, so caches keyed by them include it. +function relativePathEntriesCwd( + pathEntries: ReadonlyArray, + platform: NodeJS.Platform, + isAbsolute: (pathEntry: string) => boolean, +): string | undefined { + return platform !== "win32" && pathEntries.some((entry) => !isAbsolute(entry)) + ? process.cwd() + : undefined; +} + +// Called within the traced command resolvers. +const findOnPath = Effect.fnUntraced(function* ( + pathValue: string, + commandCandidates: ReadonlyArray, + platform: NodeJS.Platform, + windowsPathExtensions: ReadonlyArray, + isLast: (match: string) => boolean, +): Effect.fn.Return, never, FileSystem.FileSystem | Path.Path> { + const path = yield* Path.Path; + const pathEntries = pathEntriesForPlatform(pathValue, platform); + const cwd = relativePathEntriesCwd(pathEntries, platform, path.isAbsolute); const listings = yield* PathDirectoryListings; 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 ? pathEntry : path.resolve(cwd, pathEntry); + let listing = listings && (yield* Cache.get(listings, directory)); + 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 (listing?.names && !listing.names.has(candidate.toLowerCase())) continue; @@ -742,9 +760,18 @@ const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlat return null; } - const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join( - COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR, + const cwd = relativePathEntriesCwd( + pathEntriesForPlatform(pathValue, platform), + platform, + path.isAbsolute, ); + 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); From 4255544d4dec15441f1750af7084bee41567519f Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Sat, 31 Oct 2026 13:05:48 +0100 Subject: [PATCH 03/11] no-mistakes(review): Scope macOS Git caches to relative PATH cwd --- packages/shared/src/shell.test.ts | 53 ++++++++++++++++++++++++++++--- packages/shared/src/shell.ts | 24 +++++++------- 2 files changed, 60 insertions(+), 17 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index c4ca8dbd6da93..92dfbfc199352 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -663,13 +663,20 @@ 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] = process.argv.slice(1); +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 = (...args) => { + const found = 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))) { @@ -684,8 +691,19 @@ await Effect.runPromise(Effect.gen(function* () { spawn: 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(Shell.withPathDirectoryListings, Effect.provide(layer))); -console.log(JSON.stringify(resolved)); +console.log(JSON.stringify({ resolved, resolvedGit })); `; it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( @@ -700,8 +718,13 @@ console.log(JSON.stringify(resolved)); 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"); @@ -740,6 +763,15 @@ console.log(JSON.stringify(resolved)); ([label, row]) => [label, { ...row, cwd, cacheGroup: label }] as const, ), ]; + const gitEntries = ["", "."].flatMap((entry) => { + const PATH = `${entry}:${listed}`; + return [ + { PATH, cwd: empty, cacheGroup: `xcode-first-${entry}`, expected: xcodeGit }, + { PATH, cwd, cacheGroup: `xcode-first-${entry}`, expected: "git" }, + { PATH, cwd, cacheGroup: `local-first-${entry}`, expected: "git" }, + { PATH, cwd: empty, cacheGroup: `local-first-${entry}`, expected: xcodeGit }, + ]; + }); const stdout = NodeChildProcess.execFileSync( process.execPath, [ @@ -760,11 +792,16 @@ console.log(JSON.stringify(resolved)); ]), ), ), + JSON.stringify(gitEntries), + gitShim, + xcodeGit, ], { cwd, encoding: "utf8", env: {} }, ); - const resolved: Record = - JSON.parse(stdout); + 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) => @@ -789,6 +826,14 @@ console.log(JSON.stringify(resolved)); entries.map(([label, row]) => [label, { effect: row.expected, spawn: row.expected }]), ), ); + expect(resolvedGit).toEqual( + Object.fromEntries( + gitEntries.map((row, index) => [ + String(index), + { command: row.expected, args: ["status"], shell: false }, + ]), + ), + ); }), ); }); diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 1721692f62ad6..925c8f2115858 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -687,12 +687,11 @@ function pathEntriesForPlatform(pathValue: string, platform: NodeJS.Platform): s } // Relative POSIX PATH entries resolve against the working directory, so caches keyed by them include it. -function relativePathEntriesCwd( - pathEntries: ReadonlyArray, - platform: NodeJS.Platform, - isAbsolute: (pathEntry: string) => boolean, -): string | undefined { - return platform !== "win32" && pathEntries.some((entry) => !isAbsolute(entry)) +function pathSearchCwd(pathValue: string, platform: NodeJS.Platform): string | undefined { + if (platform === "win32") return undefined; + return pathEntriesForPlatform(pathValue, platform).some( + (entry) => !NodePath.posix.isAbsolute(entry), + ) ? process.cwd() : undefined; } @@ -707,7 +706,7 @@ const findOnPath = Effect.fnUntraced(function* ( ): Effect.fn.Return, never, FileSystem.FileSystem | Path.Path> { const path = yield* Path.Path; const pathEntries = pathEntriesForPlatform(pathValue, platform); - const cwd = relativePathEntriesCwd(pathEntries, platform, path.isAbsolute); + const cwd = pathSearchCwd(pathValue, platform); const listings = yield* PathDirectoryListings; const matches: string[] = []; @@ -760,11 +759,7 @@ const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlat return null; } - const cwd = relativePathEntriesCwd( - pathEntriesForPlatform(pathValue, platform), - platform, - path.isAbsolute, - ); + const cwd = pathSearchCwd(pathValue, platform); const cacheKey = [ platform, pathValue, @@ -926,12 +921,15 @@ const resolveMacosGit = Effect.fnUntraced(function* ( ) { const locateXcodeGit = yield* XcodeGitLocation; const cache = yield* CommandResolutionCache; + const pathValue = resolvePathEnvironmentVariable(env); + 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); From f838d618af1fe343d6f203104ff65b9a3f569bab Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Sat, 31 Oct 2026 13:12:48 +0100 Subject: [PATCH 04/11] no-mistakes(lint): Format shell regression test destructuring --- packages/shared/src/shell.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 92dfbfc199352..fa69d613097d8 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -798,7 +798,10 @@ console.log(JSON.stringify({ resolved, resolvedGit })); ], { cwd, encoding: "utf8", env: {} }, ); - const { resolved, resolvedGit }: { + const { + resolved, + resolvedGit, + }: { resolved: Record; resolvedGit: Record; } = JSON.parse(stdout); From 29c7cd2e8d3dc9a30634d48643f6daa65834f5ea Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Tue, 17 Nov 2026 23:44:21 +0100 Subject: [PATCH 05/11] fix(shared): keep absolute PATH lookup working when cwd cannot be read process.cwd() throws when the working directory was removed. pathSearchCwd now reports that case as null: relative entries then skip the directory listing cache, and the command caches are neither read nor written, so absolute entries are still searched and nothing is cached under a key without cwd. --- packages/shared/src/shell.test.ts | 74 +++++++++++++++++++++++++++++++ packages/shared/src/shell.ts | 32 ++++++++----- 2 files changed, 94 insertions(+), 12 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index fa69d613097d8..0b52e7c1e5595 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -839,6 +839,80 @@ console.log(JSON.stringify({ resolved, resolvedGit })); ); }), ); + + // 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 = (...args) => { + const found = 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), + Shell.withPathDirectoryListings, + 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 925c8f2115858..2a183cca24385 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -687,13 +687,19 @@ function pathEntriesForPlatform(pathValue: string, platform: NodeJS.Platform): s } // Relative POSIX PATH entries resolve against the working directory, so caches keyed by them include it. -function pathSearchCwd(pathValue: string, platform: NodeJS.Platform): string | undefined { +// 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; - return pathEntriesForPlatform(pathValue, platform).some( - (entry) => !NodePath.posix.isAbsolute(entry), - ) - ? process.cwd() - : 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. @@ -711,8 +717,10 @@ const findOnPath = Effect.fnUntraced(function* ( const listings = yield* PathDirectoryListings; const matches: string[] = []; for (const pathEntry of pathEntries) { - const directory = cwd === undefined ? pathEntry : path.resolve(cwd, pathEntry); - let listing = listings && (yield* Cache.get(listings, directory)); + 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); @@ -769,7 +777,7 @@ const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlat ].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; } @@ -781,7 +789,7 @@ const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlat windowsPathExtensions, () => true, ); - cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos); + if (cwd !== null) cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos); return resolvedPath; }); @@ -932,7 +940,7 @@ const resolveMacosGit = Effect.fnUntraced(function* ( ...(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 && @@ -948,7 +956,7 @@ const resolveMacosGit = Effect.fnUntraced(function* ( located !== undefined && resolveExecutable(located, "darwin", env) !== undefined ? located : null; - cacheCommandResolution(cache, cacheKey, realGit, nowNanos); + if (cwd !== null) cacheCommandResolution(cache, cacheKey, realGit, nowNanos); return realGit ?? "git"; }); From aebdce84ef3bc4cf9b6a3293c5ab66b6286756ef Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 18 Nov 2026 11:22:44 +0000 Subject: [PATCH 06/11] fix(server): anchor cwd provider executables before scoped launch --- apps/server/src/process/agentScope.test.ts | 14 +++++++++++--- apps/server/src/process/agentScope.ts | 6 +++++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 49674354b2532..afc34953e13e6 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -184,8 +184,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) => { @@ -225,7 +229,11 @@ 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)), + }); + expect(codex.args.at(-2)).toBe(executable); expect(codex.args).toContain("--property=OOMPolicy=continue"); expect(codex.args).not.toContain("--property=OOMPolicy=stop"); expect(codex.args).toContain("--property=TimeoutStopSec=10s"); diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index 1e52e680b6f8d..ffba5d098ef31 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -452,7 +452,11 @@ 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 for an empty PATH component. + return { + ...agentScopeCommand({ command: path.resolve(resolved), args, scope: systemdScope }), + unit, + }; }), oomKilled, stop, From 08811880256b2803155963f7b51967e73994c9d6 Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Wed, 18 Nov 2026 13:21:58 +0100 Subject: [PATCH 07/11] fix(shared): anchor executables found through empty PATH components A match through an empty POSIX PATH component came back relative to the working directory, so callers that launch it from another cwd or through a wrapper lost the selected executable. Both resolvers now return an absolute path for such a match. A literal "." entry keeps its relative spelling, and the first of the two in PATH decides. --- packages/shared/src/shell.test.ts | 29 +++++++++++++++++++++++++++-- packages/shared/src/shell.ts | 30 +++++++++++++++++++++++------- 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 0b52e7c1e5595..ae7f37c2cf866 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -712,9 +712,14 @@ console.log(JSON.stringify({ resolved, resolvedGit })); Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-empty-path-cwd-" }); + // 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.makeTempDirectoryScoped({ prefix: "t3-empty-path-absent-" }); + 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); @@ -737,6 +742,8 @@ console.log(JSON.stringify({ resolved, resolvedGit })); 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 }, @@ -829,6 +836,24 @@ console.log(JSON.stringify({ resolved, resolvedGit })); 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) => [ diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 2a183cca24385..06a2923d83387 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -108,14 +108,19 @@ function resolveSpawnExecutableWithNode( 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 normalizedPathEntry = - pathEntry === "" && pathValue !== "" && platform !== "win32" - ? "." - : normalizePathEntry(pathEntry, platform); + const emptyComponent = pathEntry === "" && pathValue !== "" && platform !== "win32"; + const normalizedPathEntry = emptyComponent ? "." : normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; for (const candidate of candidates) { const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (!isExecutable(candidatePath)) continue; + if (!emptyComponent) return candidatePath; + // Anchored, because callers may launch it from another cwd or through a wrapper. + try { + return path.resolve(candidatePath); + } catch { + continue; + } } } return undefined; @@ -714,6 +719,15 @@ const findOnPath = Effect.fnUntraced(function* ( const pathEntries = pathEntriesForPlatform(pathValue, platform); const cwd = pathSearchCwd(pathValue, platform); + // 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 === ".") === ""; + const listings = yield* PathDirectoryListings; const matches: string[] = []; for (const pathEntry of pathEntries) { @@ -729,8 +743,10 @@ const findOnPath = Effect.fnUntraced(function* ( if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue; const candidatePath = path.join(pathEntry, candidate); if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) { - matches.push(candidatePath); - if (isLast(candidatePath)) return matches; + const match = + anchorsCwd && pathEntry === "." ? path.join(directory, candidate) : candidatePath; + matches.push(match); + if (isLast(match)) return matches; break; } } From 78aec4c52f366a3f46dc410fce7f4c4c21d6083b Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Thu, 19 Nov 2026 13:18:13 +0100 Subject: [PATCH 08/11] fix(shared,server): keep absolute agent paths as spelled and probe the searched directory AgentScope resolved every executable before systemd-run, which collapses ".." lexically: an absolute /srv/link/../agent through a symlinked parent became /srv/agent. An absolute path now stays as spelled; a relative one is still anchored. findOnPath listed a relative PATH entry in the directory recorded for the search but probed its executables through the relative path, so a directory change mid-search could probe somewhere else. The probe now uses the recorded directory; returned spellings and cache keys are unchanged. --- apps/server/src/process/agentScope.test.ts | 16 +++++++++++++ apps/server/src/process/agentScope.ts | 6 +++-- packages/shared/src/shell.test.ts | 28 ++++++++++++++++++++++ packages/shared/src/shell.ts | 4 +++- 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index afc34953e13e6..8f2288f60b82b 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -249,6 +249,22 @@ describe("AgentScope service", () => { ), ); + it.effect("keeps a symlinked parent in an absolute executable path", () => + 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); + }), + ), + ); + 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 ffba5d098ef31..03521b7ca944b 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -452,9 +452,11 @@ export const make = Effect.gen(function* () { ...(owned ? [] : ["--collect"]), ], }; - // systemd-run does not search the caller's cwd for an empty PATH component. + // systemd-run does not search the caller's cwd for an empty PATH component. An absolute + // path stays as spelled: collapsing ".." would skip a symlinked parent directory. + const executable = path.isAbsolute(resolved) ? resolved : path.resolve(resolved); return { - ...agentScopeCommand({ command: path.resolve(resolved), args, scope: systemdScope }), + ...agentScopeCommand({ command: executable, args, scope: systemdScope }), unit, }; }), diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 07d2093f577ac..450f18134d923 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -627,6 +627,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([]); + }), + ); + it.effect("probes only listed PATH names and relists a directory that changes", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index f2b2ec76a0e33..509b3a2552e6d 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -742,7 +742,9 @@ const findOnPath = Effect.fnUntraced(function* ( for (const candidate of commandCandidates) { if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue; const candidatePath = path.join(pathEntry, candidate); - if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) { + // 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); From 22aef07aa5288d31f24d27525eefa1e79098500b Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Thu, 19 Nov 2026 13:32:19 +0100 Subject: [PATCH 09/11] test(server): skip the symlinked-parent agentScope case where symlinks are unsupported --- apps/server/src/process/agentScope.test.ts | 31 ++++++++++++---------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 8f2288f60b82b..3f7506cf69324 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"; @@ -249,20 +250,22 @@ describe("AgentScope service", () => { ), ); - it.effect("keeps a symlinked parent in an absolute executable path", () => - 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); - }), - ), + it.effect.skipIf(!symlinksSupported)( + "keeps a symlinked parent in an absolute executable path", + () => + 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); + }), + ), ); it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])( From 6e62d1cf924056d759c8601e438407f2077d0664 Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Thu, 19 Nov 2026 13:35:01 +0100 Subject: [PATCH 10/11] fix(server): anchor relative agent paths for systemd-run without collapsing ".." A relative executable was passed through path.resolve, which collapses ".." lexically: with cwd /srv and link pointing elsewhere, link/../agent became /srv/agent. It is now anchored to the working directory as spelled, so the kernel resolves the symlinked parent the same way the lookup did. --- apps/server/src/process/agentScope.test.ts | 16 ++++++++++++++-- apps/server/src/process/agentScope.ts | 8 +++++--- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 3f7506cf69324..5d3ed2689cf89 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -234,7 +234,10 @@ describe("AgentScope service", () => { const codex = yield* launchCodex(scope, "a", { PATH: NodePath.relative(process.cwd(), NodePath.dirname(executable)), }); - expect(codex.args.at(-2)).toBe(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"); @@ -251,7 +254,7 @@ describe("AgentScope service", () => { ); it.effect.skipIf(!symlinksSupported)( - "keeps a symlinked parent in an absolute executable path", + "keeps a symlinked parent in absolute and relative executable paths", () => withFakeSystemd(({ scope }) => Effect.gen(function* () { @@ -264,6 +267,15 @@ describe("AgentScope service", () => { 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}`); }), ), ); diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index 03521b7ca944b..9cdb74896af9e 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -452,9 +452,11 @@ export const make = Effect.gen(function* () { ...(owned ? [] : ["--collect"]), ], }; - // systemd-run does not search the caller's cwd for an empty PATH component. An absolute - // path stays as spelled: collapsing ".." would skip a symlinked parent directory. - const executable = path.isAbsolute(resolved) ? resolved : path.resolve(resolved); + // 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, From 81e9154c50eb4448564b2822eb3c554345d5788d Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Sun, 22 Nov 2026 04:49:59 +0100 Subject: [PATCH 11/11] fix(shared): share the cwd snapshot with PATH searches and launch the anchored git findOnPath now takes the cwd its caller keyed the cache with, and the macOS git lookup reads the clock before the cwd, so a directory change in between cannot store one directory's result under another. A git found in the cwd through an empty PATH entry is launched by its absolute path, because a child started elsewhere would search that entry again from its own cwd. --- packages/shared/src/shell.test.ts | 8 ++++++-- packages/shared/src/shell.ts | 21 +++++++++++++++------ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index bd10c42f11a60..c0c0e90d457b8 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -894,13 +894,17 @@ console.log(JSON.stringify({ resolved, resolvedGit })); ]; 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: "git" }, - { PATH, cwd, cacheGroup: `local-first-${entry}`, expected: "git" }, + { 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, [ diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index ac244221b85f9..ede215d17f478 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -801,10 +801,11 @@ 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; const pathEntries = pathEntriesForPlatform(pathValue, platform); - const cwd = pathSearchCwd(pathValue, platform); // 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 @@ -894,6 +895,7 @@ const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlat platform, windowsPathExtensions, () => true, + cwd, ); if (cwd !== null) cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos); return resolvedPath; @@ -918,12 +920,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), ); }); @@ -1050,6 +1054,8 @@ 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 synchronous lookup below searches the directory the key names. const cwd = pathSearchCwd(pathValue, "darwin"); const cacheKey = [ "xcode-git", @@ -1059,7 +1065,6 @@ const resolveMacosGit = Effect.fnUntraced(function* ( env.DEVELOPER_DIR ?? "", ...(cwd === undefined ? [] : [cwd]), ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR); - const nowNanos = yield* Clock.currentTimeNanos; const cached = cwd === null ? undefined : cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. if ( @@ -1070,12 +1075,16 @@ const resolveMacosGit = Effect.fnUntraced(function* ( ) { return cached.resolvedPath ?? "git"; } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const pathGit = resolveExecutable("git", "darwin", env); + const located = pathGit === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = located !== undefined && resolveExecutable(located, "darwin", env) !== undefined ? located - : null; + : // 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; if (cwd !== null) cacheCommandResolution(cache, cacheKey, realGit, nowNanos); return realGit ?? "git"; });