Skip to content

Commit 6df32aa

Browse files
fix(server): spawn through env, bound threadpool checks, and keep Claude off a hung cwd
- Linux commands now run as `/usr/bin/env [-C <cwd>] -- <command> <args...>`, which passes the environment through untouched (dash dropped BASH_FUNC_*%% entries and added PWD/OLDPWD). Hosts without `env -C`, and commands containing `=`, keep the /bin/sh trampoline. - Parent-side checks run at most one per directory, and checks of one path share the one in flight, so a hung directory holds one threadpool thread. - A cwd is resolved lexically and checked for search permission, failing PermissionDenied like a native spawn. - The Claude process-group shell enters the cwd itself instead of Node's spawn doing chdir in the parent's fork. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 80c39ae commit 6df32aa

4 files changed

Lines changed: 266 additions & 102 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,10 @@ const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
347347
const CLAUDE_ROOT_REFUSAL =
348348
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
349349

350+
// The shell enters the cwd: a native cwd blocks the server while a hung mount stalls chdir.
350351
const CLAUDE_GROUP_WATCH_SCRIPT = [
352+
'cd -- "$1" || exit 125',
353+
"shift",
351354
"{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
352355
'exec "$@" 3<&-',
353356
].join("\n");
@@ -363,11 +366,19 @@ export function spawnClaudeProcessGroup(
363366
onStderr: (text: string) => void = () => {},
364367
onStderrClose: () => void = () => {},
365368
): ClaudeSpawnedProcess {
369+
// Relative to the server's cwd, as a native cwd is; `./` keeps CDPATH out of it.
370+
const cwd = options.cwd ?? ".";
366371
const child = NodeChildProcess.spawn(
367372
"/bin/sh",
368-
["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
373+
[
374+
"-c",
375+
CLAUDE_GROUP_WATCH_SCRIPT,
376+
"t3-claude",
377+
cwd.startsWith("/") ? cwd : `./${cwd}`,
378+
options.command,
379+
...options.args,
380+
],
369381
{
370-
cwd: options.cwd,
371382
env: options.env,
372383
signal: options.signal,
373384
stdio: ["pipe", "pipe", "pipe", "pipe"],

‎apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,34 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
588588
}).pipe(Effect.provide(realQueryRunner)),
589589
);
590590

591+
it.effect("starts the CLI in its cwd, and fails a missing cwd from inside the child", () =>
592+
Effect.gen(function* () {
593+
const cli = fakeClaudeCli("pwd -P");
594+
const dir = NodeFS.realpathSync(NodePath.dirname(cli));
595+
yield* Effect.addFinalizer(() =>
596+
Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
597+
);
598+
const run = (cwd: string) =>
599+
Effect.promise(() => {
600+
const child = spawnClaudeProcessGroup({
601+
command: cli,
602+
args: [],
603+
cwd,
604+
env: process.env,
605+
signal: new AbortController().signal,
606+
}) as NodeChildProcess.ChildProcess;
607+
child.stdin?.end();
608+
let stdout = "";
609+
child.stdout?.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));
610+
return new Promise<{ code: number | null; stdout: string }>((resolve) =>
611+
child.once("close", (code) => resolve({ code, stdout })),
612+
);
613+
});
614+
assert.deepEqual(yield* run(dir), { code: 0, stdout: `${dir}\n` });
615+
assert.equal((yield* run(NodePath.join(dir, "missing"))).code, 125);
616+
}),
617+
);
618+
591619
// The CLI keeps running its turn after its pipes close, so a server that
592620
// crashed would leave it working next to the session it resumes.
593621
it.effect("stops the CLI when the server that started it goes away", () =>

‎apps/server/src/process/NonBlockingSpawner.test.ts‎

Lines changed: 125 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
// @effect-diagnostics-next-line nodeBuiltinImport:off - a skip condition must be known before the test runs.
2+
import * as NodeChildProcess from "node:child_process";
3+
14
import * as NodeServices from "@effect/platform-node/NodeServices";
25
import { describe, expect, it } from "@effect/vitest";
36
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -12,6 +15,26 @@ import * as NonBlockingSpawner from "./NonBlockingSpawner.ts";
1215

1316
const wrapped = NonBlockingSpawner.layer.pipe(Layer.provideMerge(NodeServices.layer));
1417

18+
// A host without /usr/bin/env, such as a minimal container, spawns through /bin/sh.
19+
const withoutEnv = NonBlockingSpawner.layer.pipe(
20+
Layer.provide(
21+
Layer.effect(
22+
ChildProcessSpawner.ChildProcessSpawner,
23+
Effect.gen(function* () {
24+
const native = yield* ChildProcessSpawner.ChildProcessSpawner;
25+
return ChildProcessSpawner.make((command) =>
26+
command._tag === "StandardCommand" && command.command === "/usr/bin/env"
27+
? Effect.fail(PlatformError.badArgument({ module: "Test", method: "spawn" }))
28+
: native.spawn(command),
29+
);
30+
}),
31+
),
32+
),
33+
Layer.provideMerge(NodeServices.layer),
34+
);
35+
36+
const bashAvailable = NodeChildProcess.spawnSync("bash", ["-c", ":"]).status === 0;
37+
1538
const run = (command: ChildProcess.Command) =>
1639
ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.string(command));
1740

@@ -25,26 +48,82 @@ const spawnError = (command: ChildProcess.Command) =>
2548
ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.spawn(command)),
2649
).pipe(Effect.flip);
2750

51+
const trampolines = [
52+
["env", wrapped],
53+
["sh", withoutEnv],
54+
] as const;
55+
2856
describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("NonBlockingSpawner", () => {
29-
it.live("runs a command in the requested cwd", () =>
57+
describe.each(trampolines)("through %s", (_trampoline, spawner) => {
58+
it.live("runs a command in the requested cwd", () =>
59+
Effect.gen(function* () {
60+
const fileSystem = yield* FileSystem.FileSystem;
61+
const directory = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
62+
const result = yield* run(ChildProcess.make("pwd", ["-P"], { cwd: directory }));
63+
expect(result).toBe(`${directory}\n`);
64+
}).pipe(Effect.scoped, Effect.provide(spawner)),
65+
);
66+
67+
it.live("delivers argv with spaces, quotes, leading dashes and `=` intact", () =>
68+
Effect.gen(function* () {
69+
const fileSystem = yield* FileSystem.FileSystem;
70+
const directory = yield* fileSystem.makeTempDirectoryScoped();
71+
const args = ["-n", "--", "a b", `it's "quoted"`, "$HOME", "; exit 3", "", "A=b"];
72+
const result = yield* run(
73+
ChildProcess.make("printf", ["%s\\n", ...args], { cwd: directory }),
74+
);
75+
expect(result).toBe(args.map((arg) => `${arg}\n`).join(""));
76+
}).pipe(Effect.scoped, Effect.provide(spawner)),
77+
);
78+
79+
it.live("searches PATH the way the native spawner does", () =>
80+
Effect.gen(function* () {
81+
const fileSystem = yield* FileSystem.FileSystem;
82+
const root = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
83+
const scripts = {
84+
stale: "#!/t3code-missing-interpreter\n",
85+
fresh: "#!/bin/sh\necho fresh\n",
86+
"target/bin": "#!/bin/sh\necho target\n",
87+
};
88+
for (const [directory, body] of Object.entries(scripts)) {
89+
yield* fileSystem.makeDirectory(`${root}/${directory}`, { recursive: true });
90+
yield* fileSystem.writeFileString(`${root}/${directory}/tool`, body);
91+
yield* fileSystem.chmod(`${root}/${directory}/tool`, 0o755);
92+
}
93+
yield* fileSystem.makeDirectory(`${root}/target/subdir`);
94+
yield* fileSystem.symlink(`${root}/target/subdir`, `${root}/link`);
95+
for (const PATH of [`${root}/stale:${root}/fresh`, `${root}/link/../bin`]) {
96+
const command = ChildProcess.make("tool", [], { env: { PATH }, cwd: root });
97+
const native = yield* run(command).pipe(Effect.provide(NodeServices.layer));
98+
expect(yield* run(command).pipe(Effect.provide(spawner))).toBe(native);
99+
}
100+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
101+
);
102+
});
103+
104+
// GNU env passes it through; dash would drop `BASH_FUNC_*%%` and add PWD and OLDPWD.
105+
it.live("hands the child exactly the environment it was given", () =>
30106
Effect.gen(function* () {
31107
const fileSystem = yield* FileSystem.FileSystem;
32-
const directory = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
33-
const result = yield* run(ChildProcess.make("pwd", ["-P"], { cwd: directory }));
34-
expect(result).toBe(`${directory}\n`);
35-
}).pipe(Effect.scoped, Effect.provide(wrapped)),
108+
const directory = yield* fileSystem.makeTempDirectoryScoped();
109+
const command = ChildProcess.make("env", [], {
110+
cwd: directory,
111+
env: { PATH: process.env.PATH, A: "1", "BASH_FUNC_x%%": "() { echo exported\n}" },
112+
});
113+
const native = yield* run(command).pipe(Effect.provide(NodeServices.layer));
114+
expect(yield* run(command).pipe(Effect.provide(wrapped))).toBe(native);
115+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
36116
);
37117

38-
it.live("delivers argv with spaces, quotes and leading dashes intact", () =>
118+
it.live.skipIf(!bashAvailable)("keeps a function exported by bash callable in a bash child", () =>
39119
Effect.gen(function* () {
40-
const fileSystem = yield* FileSystem.FileSystem;
41-
const directory = yield* fileSystem.makeTempDirectoryScoped();
42-
const args = ["-n", "--", "a b", `it's "quoted"`, "$HOME", "; exit 3", ""];
43120
const result = yield* run(
44-
ChildProcess.make("printf", ["%s\\n", ...args], { cwd: directory }),
121+
ChildProcess.make("bash", ["-c", "x"], {
122+
env: { PATH: process.env.PATH, "BASH_FUNC_x%%": "() { echo exported\n}" },
123+
}),
45124
);
46-
expect(result).toBe(args.map((arg) => `${arg}\n`).join(""));
47-
}).pipe(Effect.scoped, Effect.provide(wrapped)),
125+
expect(result).toBe("exported\n");
126+
}).pipe(Effect.provide(wrapped)),
48127
);
49128

50129
it.live("fails a missing command with NotFound, with or without cwd", () =>
@@ -74,6 +153,21 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("NonBlockingSpa
74153
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
75154
);
76155

156+
it.live.skipIf(process.getuid?.() === 0)(
157+
"fails a cwd it cannot enter the way the native spawner does",
158+
() =>
159+
Effect.gen(function* () {
160+
const fileSystem = yield* FileSystem.FileSystem;
161+
const directory = `${yield* fileSystem.makeTempDirectoryScoped()}/locked`;
162+
yield* fileSystem.makeDirectory(directory, { mode: 0o600 });
163+
const command = ChildProcess.make("true", [], { cwd: directory });
164+
const native = yield* spawnError(command).pipe(Effect.provide(NodeServices.layer));
165+
const error = yield* spawnError(command).pipe(Effect.provide(wrapped));
166+
expect(error.reason._tag).toBe("PermissionDenied");
167+
expect(error.message).toBe(native.message);
168+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
169+
);
170+
77171
it.live("fails a missing or non-executable explicit path like the native spawner", () =>
78172
Effect.gen(function* () {
79173
const fileSystem = yield* FileSystem.FileSystem;
@@ -91,60 +185,42 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("NonBlockingSpa
91185
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
92186
);
93187

94-
it.live("searches PATH the way the native spawner does", () =>
95-
Effect.gen(function* () {
96-
const fileSystem = yield* FileSystem.FileSystem;
97-
const root = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
98-
const scripts = {
99-
stale: "#!/t3code-missing-interpreter\n",
100-
fresh: "#!/bin/sh\necho fresh\n",
101-
"target/bin": "#!/bin/sh\necho target\n",
102-
};
103-
for (const [directory, body] of Object.entries(scripts)) {
104-
yield* fileSystem.makeDirectory(`${root}/${directory}`, { recursive: true });
105-
yield* fileSystem.writeFileString(`${root}/${directory}/tool`, body);
106-
yield* fileSystem.chmod(`${root}/${directory}/tool`, 0o755);
107-
}
108-
yield* fileSystem.makeDirectory(`${root}/target/subdir`);
109-
yield* fileSystem.symlink(`${root}/target/subdir`, `${root}/link`);
110-
for (const PATH of [`${root}/stale:${root}/fresh`, `${root}/link/../bin`]) {
111-
const command = ChildProcess.make("tool", [], { env: { PATH }, cwd: root });
112-
const native = yield* run(command).pipe(Effect.provide(NodeServices.layer));
113-
expect(yield* run(command).pipe(Effect.provide(wrapped))).toBe(native);
114-
}
115-
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
116-
);
117-
118-
it.effect("only ever hands the native spawner /bin/sh, without a cwd", () =>
188+
it.live("only ever hands the native spawner a trampoline, without a cwd", () =>
119189
Effect.gen(function* () {
120190
const fileSystem = yield* FileSystem.FileSystem;
121191
const directory = yield* fileSystem.makeTempDirectoryScoped();
122192
const received: Array<ChildProcess.Command> = [];
123-
const recording = Layer.succeed(
193+
const recording = Layer.effect(
124194
ChildProcessSpawner.ChildProcessSpawner,
125-
ChildProcessSpawner.make((command) => {
126-
received.push(command);
127-
return Effect.fail(PlatformError.badArgument({ module: "Test", method: "spawn" }));
195+
Effect.gen(function* () {
196+
const native = yield* ChildProcessSpawner.ChildProcessSpawner;
197+
return ChildProcessSpawner.make((command) => {
198+
received.push(command);
199+
return native.spawn(command);
200+
});
128201
}),
129-
);
130-
const piped = ChildProcess.make("true", [], { cwd: directory }).pipe(
202+
).pipe(Layer.provide(NodeServices.layer));
203+
const piped = ChildProcess.make("printf", ["a"], { cwd: directory }).pipe(
131204
ChildProcess.pipeTo(ChildProcess.make("cat", [], { cwd: directory })),
132205
);
133206
for (const command of [
134-
ChildProcess.make("git", ["status"], { cwd: directory }),
135-
ChildProcess.make("git", ["status"]),
207+
ChildProcess.make("true", [], { cwd: directory }),
208+
ChildProcess.make("true", []),
136209
ChildProcess.make("/bin/true", []),
210+
ChildProcess.make("t3code-missing-command-30183", []),
137211
piped,
138212
]) {
139-
yield* spawnError(command).pipe(
140-
Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provide(recording))),
213+
yield* Effect.exit(
214+
ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.exitCode(command)).pipe(
215+
Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provide(recording))),
216+
),
141217
);
142218
}
143219

144220
const legs = received.flatMap(standardCommands);
145-
expect(legs).toHaveLength(5);
221+
expect(legs.length).toBeGreaterThanOrEqual(5);
146222
for (const leg of legs) {
147-
expect(leg.command).toBe("/bin/sh");
223+
expect(["/usr/bin/env", "/bin/sh"]).toContain(leg.command);
148224
expect(leg.options.cwd).toBeUndefined();
149225
}
150226
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),

0 commit comments

Comments
 (0)