Skip to content

Commit 193216b

Browse files
committed
fix(claude): 隔离能力探测配置
- 能力探测固定使用中性临时目录,并将目标配置目录显式传递给 Claude CLI。\n- 相对配置路径按工作区解析;HOME 或 USERPROFILE 覆盖会形成独立缓存键。\n- 保留最新的维护能力缓存、二进制路径展开和跨平台临时目录清理。\n- 验证:Claude 定向测试 30/30、格式检查和服务端类型检查通过。
1 parent 6abdf37 commit 193216b

6 files changed

Lines changed: 186 additions & 50 deletions

File tree

‎apps/server/src/provider/Drivers/ClaudeDriver.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,11 @@ import {
5959
makeProviderSnapshotSettingsSource,
6060
type ProviderSnapshotSettings,
6161
} from "../providerUpdateSettings.ts";
62-
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
62+
import {
63+
makeClaudeCapabilitiesCacheKey,
64+
makeClaudeCapabilitiesProbeContext,
65+
makeClaudeContinuationGroupKey,
66+
} from "./ClaudeHome.ts";
6367
import { discoverClaudeSkills } from "./ClaudeSkills.ts";
6468
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
6569

@@ -125,6 +129,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
125129
enabled,
126130
binaryPath: expandHomePath(config.binaryPath),
127131
} satisfies ClaudeSettings;
132+
const capabilitiesProbeContext = yield* makeClaudeCapabilitiesProbeContext(
133+
effectiveConfig,
134+
processEnv,
135+
cwd,
136+
);
128137
const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
129138
resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
130139
binaryPath: effectiveConfig.binaryPath,
@@ -167,11 +176,18 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
167176
capacity: 1,
168177
timeToLive: CAPABILITIES_PROBE_TTL,
169178
lookup: () =>
170-
probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
171-
Effect.provideService(Path.Path, path),
172-
),
179+
probeClaudeCapabilities(
180+
effectiveConfig,
181+
capabilitiesProbeContext.environment,
182+
capabilitiesProbeContext.cwd,
183+
cwd,
184+
).pipe(Effect.provideService(Path.Path, path)),
173185
});
174-
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);
186+
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
187+
effectiveConfig,
188+
processEnv,
189+
cwd,
190+
);
175191

176192
// Start the TTL-gated refresh without delaying provider readiness. The
177193
// next check observes a remote manifest after the background fetch lands.

‎apps/server/src/provider/Drivers/ClaudeHome.test.ts‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@ import * as Path from "effect/Path";
88
import {
99
claudeSignedOutMessage,
1010
makeClaudeCapabilitiesCacheKey,
11+
makeClaudeCapabilitiesProbeContext,
1112
makeClaudeContinuationGroupKey,
1213
makeClaudeEnvironment,
14+
resolveClaudeConfigDirPath,
1315
resolveClaudeHomePath,
1416
} from "./ClaudeHome.ts";
1517

@@ -21,10 +23,68 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
2123
const resolved = path.resolve(NodeOS.homedir());
2224

2325
expect(yield* resolveClaudeHomePath({ homePath: "" })).toBe(resolved);
26+
expect(yield* resolveClaudeConfigDirPath({ homePath: "" })).toBe(
27+
path.join(resolved, ".claude"),
28+
);
29+
expect((yield* makeClaudeCapabilitiesProbeContext({ homePath: "" })).cwd).toBe(
30+
path.resolve(NodeOS.tmpdir()),
31+
);
2432
expect(yield* makeClaudeEnvironment({ homePath: "" })).toBe(process.env);
2533
}),
2634
);
2735

36+
it.effect("resolves an environment config directory against the workspace cwd", () =>
37+
Effect.gen(function* () {
38+
const path = yield* Path.Path;
39+
const workspaceCwd = path.join(NodeOS.tmpdir(), "t3-claude-workspace");
40+
const environment = { CLAUDE_CONFIG_DIR: "profile" };
41+
42+
expect(yield* resolveClaudeConfigDirPath({ homePath: "" }, environment, workspaceCwd)).toBe(
43+
path.join(workspaceCwd, "profile"),
44+
);
45+
const context = yield* makeClaudeCapabilitiesProbeContext(
46+
{ homePath: "" },
47+
environment,
48+
workspaceCwd,
49+
);
50+
expect(context.cwd).toBe(path.resolve(NodeOS.tmpdir()));
51+
expect(context.environment.CLAUDE_CONFIG_DIR).toBe(path.join(workspaceCwd, "profile"));
52+
expect(
53+
yield* makeClaudeCapabilitiesCacheKey(
54+
{ binaryPath: "claude", homePath: "" },
55+
environment,
56+
workspaceCwd,
57+
),
58+
).toBe(`claude\0${path.join(workspaceCwd, "profile")}`);
59+
}),
60+
);
61+
62+
it.effect("uses inherited HOME or USERPROFILE for the default config directory", () =>
63+
Effect.gen(function* () {
64+
const path = yield* Path.Path;
65+
const homeEnvironment = { HOME: path.join(NodeOS.tmpdir(), "claude-home-a") };
66+
const userProfileEnvironment = { USERPROFILE: path.join(NodeOS.tmpdir(), "claude-home-b") };
67+
68+
expect(yield* resolveClaudeConfigDirPath({ homePath: "" }, homeEnvironment)).toBe(
69+
path.join(homeEnvironment.HOME, ".claude"),
70+
);
71+
expect(yield* resolveClaudeConfigDirPath({ homePath: "" }, userProfileEnvironment)).toBe(
72+
path.join(userProfileEnvironment.USERPROFILE, ".claude"),
73+
);
74+
expect(
75+
yield* makeClaudeCapabilitiesCacheKey(
76+
{ binaryPath: "claude", homePath: "" },
77+
homeEnvironment,
78+
),
79+
).not.toBe(
80+
yield* makeClaudeCapabilitiesCacheKey(
81+
{ binaryPath: "claude", homePath: "" },
82+
userProfileEnvironment,
83+
),
84+
);
85+
}),
86+
);
87+
2888
it.effect("resolves configured Claude HOME and stamps continuation/cache keys with it", () =>
2989
Effect.gen(function* () {
3090
const path = yield* Path.Path;
@@ -35,7 +95,7 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
3595
expect((yield* makeClaudeEnvironment({ homePath })).CLAUDE_CONFIG_DIR).toBe(resolved);
3696
expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`);
3797
expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe(
38-
`claude\0${resolved}\0`,
98+
`claude\0${resolved}`,
3999
);
40100
}),
41101
);
@@ -51,11 +111,12 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
51111
expect(message).toContain("then start a new thread");
52112
});
53113

54-
it.effect("separates capability probes by cwd", () =>
114+
it.effect("separates capability probes by their resolved configuration directories", () =>
55115
Effect.gen(function* () {
56-
const config = { binaryPath: "claude", homePath: "" };
57-
const first = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-a");
58-
const second = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-b");
116+
const firstConfig = { binaryPath: "claude", homePath: "~/.claude-first" };
117+
const secondConfig = { binaryPath: "claude", homePath: "~/.claude-second" };
118+
const first = yield* makeClaudeCapabilitiesCacheKey(firstConfig);
119+
const second = yield* makeClaudeCapabilitiesCacheKey(secondConfig);
59120
expect(first).not.toBe(second);
60121
}),
61122
);

‎apps/server/src/provider/Drivers/ClaudeHome.ts‎

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,66 @@ export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function
1717
return path.resolve(homePath.length > 0 ? expandHomePath(homePath) : NodeOS.homedir());
1818
});
1919

20+
/**
21+
* Resolve the Claude config directory the spawned CLI uses. An explicit
22+
* provider override wins, followed by the instance environment, then
23+
* Claude's default `$HOME/.claude` location.
24+
*/
25+
export const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
26+
config: Pick<ClaudeSettings, "homePath">,
27+
environment?: NodeJS.ProcessEnv,
28+
cwd?: string,
29+
): Effect.fn.Return<string, never, Path.Path> {
30+
const path = yield* Path.Path;
31+
const homePath = config.homePath.trim();
32+
if (homePath.length > 0) {
33+
return yield* resolveClaudeHomePath(config);
34+
}
35+
36+
const resolvedEnvironment = environment ?? process.env;
37+
// No tilde expansion here: the spawned CLI receives this env var verbatim
38+
// (env vars are never shell-expanded), so a literal `~` must stay literal
39+
// for discovery to scan the same directory the runtime would. A relative
40+
// value is resolved against the workspace cwd — the subprocess's own cwd —
41+
// for the same reason.
42+
const environmentConfigDir = resolvedEnvironment.CLAUDE_CONFIG_DIR?.trim() ?? "";
43+
if (environmentConfigDir.length > 0) {
44+
return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
45+
}
46+
const inheritedHome =
47+
resolvedEnvironment.HOME?.trim() || resolvedEnvironment.USERPROFILE?.trim() || NodeOS.homedir();
48+
return path.join(path.resolve(inheritedHome), ".claude");
49+
});
50+
51+
/**
52+
* Capability probes run from an existing neutral cwd because Claude treats
53+
* `<cwd>/.claude/settings.json` as project settings. The intended config dir
54+
* remains available through CLAUDE_CONFIG_DIR, including when it does not yet
55+
* exist or arrived as a relative inherited environment variable.
56+
*/
57+
export const makeClaudeCapabilitiesProbeContext = Effect.fn("makeClaudeCapabilitiesProbeContext")(
58+
function* (
59+
config: Pick<ClaudeSettings, "homePath">,
60+
environment?: NodeJS.ProcessEnv,
61+
workspaceCwd?: string,
62+
): Effect.fn.Return<
63+
{ readonly cwd: string; readonly environment: NodeJS.ProcessEnv },
64+
never,
65+
Path.Path
66+
> {
67+
const path = yield* Path.Path;
68+
const resolvedEnvironment = environment ?? process.env;
69+
const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, workspaceCwd);
70+
return {
71+
cwd: path.resolve(NodeOS.tmpdir()),
72+
environment: {
73+
...resolvedEnvironment,
74+
CLAUDE_CONFIG_DIR: configDirPath,
75+
},
76+
};
77+
},
78+
);
79+
2080
export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function* (
2181
config: Pick<ClaudeSettings, "homePath">,
2282
baseEnv?: NodeJS.ProcessEnv,
@@ -47,10 +107,11 @@ export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationG
47107
export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")(
48108
function* (
49109
config: Pick<ClaudeSettings, "binaryPath" | "homePath">,
50-
cwd?: string,
110+
environment?: NodeJS.ProcessEnv,
111+
workspaceCwd?: string,
51112
): Effect.fn.Return<string, never, Path.Path> {
52-
const resolvedHomePath = yield* resolveClaudeHomePath(config);
53-
return `${config.binaryPath}\0${resolvedHomePath}\0${cwd ?? ""}`;
113+
const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, workspaceCwd);
114+
return `${config.binaryPath}\0${configDirPath}`;
54115
},
55116
);
56117

‎apps/server/src/provider/Drivers/ClaudeSkills.ts‎

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
*
1414
* @module provider/Drivers/ClaudeSkills
1515
*/
16-
import * as NodeOS from "node:os";
17-
1816
import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
1917
import * as Effect from "effect/Effect";
2018
import * as FileSystem from "effect/FileSystem";
@@ -24,7 +22,7 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
2422
import { fromLenientJson } from "@t3tools/shared/schemaJson";
2523
import { parse as parseYamlDocument } from "yaml";
2624

27-
import { expandHomePath } from "../../pathExpansion.ts";
25+
import { resolveClaudeConfigDirPath } from "./ClaudeHome.ts";
2826

2927
type ClaudeSkillScope = "user" | "project";
3028

@@ -267,34 +265,6 @@ const readSkillOverrides = Effect.fn("readSkillOverrides")(function* (
267265
return overridesByName;
268266
});
269267

270-
/**
271-
* Resolve the Claude config directory the CLI would use, matching the
272-
* precedence the spawned CLI sees: the instance's `homePath` (exported as
273-
* `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
274-
* already present in the process environment, then `~/.claude`.
275-
*/
276-
const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
277-
config: Pick<ClaudeSettings, "homePath">,
278-
environment: NodeJS.ProcessEnv,
279-
cwd?: string,
280-
): Effect.fn.Return<string, never, Path.Path> {
281-
const path = yield* Path.Path;
282-
const homePath = config.homePath.trim();
283-
if (homePath.length > 0) {
284-
return path.resolve(expandHomePath(homePath));
285-
}
286-
// No tilde expansion here: the spawned CLI receives this env var verbatim
287-
// (env vars are never shell-expanded), so a literal `~` must stay literal
288-
// for discovery to scan the same directory the runtime would. A relative
289-
// value is resolved against the workspace cwd — the subprocess's own cwd —
290-
// for the same reason.
291-
const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
292-
if (environmentConfigDir.length > 0) {
293-
return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
294-
}
295-
return path.join(NodeOS.homedir(), ".claude");
296-
});
297-
298268
/**
299269
* Enumerate Claude Code skills from the user config dir and the workspace
300270
* `.claude/skills`. Discovery is best-effort: unreadable roots and malformed

‎apps/server/src/provider/Layers/ClaudeCapabilitiesProbe.test.ts‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { vi } from "vite-plus/test";
44
import * as Deferred from "effect/Deferred";
55
import * as Fiber from "effect/Fiber";
66
import * as TestClock from "effect/testing/TestClock";
7+
import * as NodeOS from "node:os";
78
import { ClaudeSettings } from "@t3tools/contracts";
89
import * as NodeFSP from "node:fs/promises";
910
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -13,6 +14,7 @@ import * as FileSystem from "effect/FileSystem";
1314
import * as Path from "effect/Path";
1415
import * as Schema from "effect/Schema";
1516

17+
import { makeClaudeCapabilitiesProbeContext } from "../Drivers/ClaudeHome.ts";
1618
import {
1719
buildClaudeCapabilitiesProbeQueryOptions,
1820
CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
@@ -33,12 +35,14 @@ it("isolates Claude capability probes without dropping workspace setting sources
3335
ENABLE_CLAUDEAI_MCP_SERVERS: "true",
3436
FORCE_CODE_TERMINAL: "1",
3537
},
36-
cwd: "/workspace/project",
38+
cwd: "/config/claude",
39+
workspaceCwd: "/workspace/project",
3740
});
3841

3942
assert.deepEqual(options.mcpServers, {});
4043
assert.equal(options.strictMcpConfig, true);
41-
assert.equal(options.cwd, "/workspace/project");
44+
assert.equal(options.cwd, "/config/claude");
45+
assert.deepEqual(options.additionalDirectories, ["/workspace/project"]);
4246
assert.deepEqual(options.settingSources, [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES]);
4347
assert.deepEqual(options.settings, { disableAllHooks: true });
4448
assert.deepEqual(options.allowedTools, []);
@@ -53,13 +57,14 @@ it("isolates Claude capability probes without dropping workspace setting sources
5357
});
5458

5559
it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
56-
it.effect("serializes strict no-MCP options and still resolves account capabilities", () =>
60+
it.effect("runs from an existing neutral cwd when the Claude config dir is missing", () =>
5761
Effect.gen(function* () {
5862
const fs = yield* FileSystem.FileSystem;
5963
const path = yield* Path.Path;
6064
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" });
6165
const executablePath = path.join(tempDir, "fake-claude.mjs");
6266
const invocationPath = path.join(tempDir, "invocation.json");
67+
const claudeConfigDir = path.join(tempDir, "missing-claude-config");
6368
// The probe aborts the SDK without awaiting the child's exit, and on
6469
// Windows a directory that is still some process's cwd cannot be
6570
// removed. Keep the workspace outside the scoped directory and let it
@@ -97,6 +102,7 @@ it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
97102
"writeFileSync(process.env.T3_PROBE_INVOCATION_PATH, JSON.stringify({",
98103
" args,",
99104
" cwd: process.cwd(),",
105+
" configDir: process.env.CLAUDE_CONFIG_DIR,",
100106
" connectorEnv: process.env.ENABLE_CLAUDEAI_MCP_SERVERS,",
101107
" mcpConfig,",
102108
"}));",
@@ -135,15 +141,25 @@ it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
135141
);
136142
yield* fs.chmod(executablePath, 0o755);
137143

138-
const capabilities = yield* probeClaudeCapabilities(
139-
decodeClaudeSettings({ binaryPath: executablePath }),
144+
const settings = decodeClaudeSettings({
145+
binaryPath: executablePath,
146+
homePath: claudeConfigDir,
147+
});
148+
const context = yield* makeClaudeCapabilitiesProbeContext(
149+
settings,
140150
{
141151
...process.env,
142152
T3_PROBE_INVOCATION_PATH: invocationPath,
143153
ENABLE_CLAUDEAI_MCP_SERVERS: "true",
144154
},
145155
workspaceCwd,
146156
);
157+
const capabilities = yield* probeClaudeCapabilities(
158+
settings,
159+
context.environment,
160+
context.cwd,
161+
workspaceCwd,
162+
);
147163

148164
assert.deepEqual(capabilities, {
149165
@@ -167,16 +183,22 @@ it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
167183
const invocation = JSON.parse(yield* fs.readFileString(invocationPath)) as {
168184
readonly args: ReadonlyArray<string>;
169185
readonly cwd: string;
186+
readonly configDir: string;
170187
readonly connectorEnv: string;
171188
readonly mcpConfig: unknown;
172189
};
173-
assert.equal(invocation.cwd, yield* fs.realPath(workspaceCwd));
190+
assert.equal(invocation.cwd, yield* fs.realPath(NodeOS.tmpdir()));
191+
assert.notEqual(invocation.cwd, yield* fs.realPath(workspaceCwd));
192+
assert.equal(invocation.configDir, path.resolve(claudeConfigDir));
174193
assert.equal(invocation.connectorEnv, "false");
175194
assert.equal(invocation.args.includes("--strict-mcp-config"), true);
176195
assert.equal(invocation.args.includes("--mcp-config"), false);
177196
assert.equal(invocation.mcpConfig, undefined);
178197

179198
assert.equal(invocation.args.includes("--setting-sources=user,project,local"), true);
199+
const addDirectoryFlagIndex = invocation.args.indexOf("--add-dir");
200+
assert.notEqual(addDirectoryFlagIndex, -1);
201+
assert.equal(invocation.args[addDirectoryFlagIndex + 1], workspaceCwd);
180202

181203
const settingsFlagIndex = invocation.args.indexOf("--settings");
182204
assert.notEqual(settingsFlagIndex, -1);

0 commit comments

Comments
 (0)