Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 106 additions & 3 deletions apps/server/src/fork/claudeMcpProfile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
ClaudeMcpProfileError,
EVERY_MCP_SERVER,
type FindThread,
__testing as ClaudeMcpProfileTesting,
type LineageThread,
checkClaudeSession,
claudeMcpCallOutsideProfile,
Expand Down Expand Up @@ -232,6 +233,7 @@ describe("makeClaudeMcpProfiles", () => {
() =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
ClaudeMcpProfileTesting.clearOpenedPlanKeys();
const lean = (t3Tools: unknown) => ({
mcpProfile: "lean",
mcpProfiles: { lean: { servers: "all", t3Tools } },
Expand Down Expand Up @@ -279,6 +281,7 @@ describe("makeClaudeMcpProfiles", () => {
() =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
ClaudeMcpProfileTesting.clearOpenedPlanKeys();
const lean = { mcpProfile: "lean", mcpProfiles: { lean: { servers: "all", t3Tools: [] } } };
const service = yield* ServerSettingsService.ServerSettingsService;
const plan = yield* makeClaudeMcpProfiles.pipe(
Expand All @@ -288,7 +291,7 @@ describe("makeClaudeMcpProfiles", () => {
}),
);
const before: T3ToolSets.T3ToolSet = { _tag: "Groups", name: "all", groups: "all" };
T3ToolSets.fixT3ToolSet("t", before);
T3ToolSets.fixT3ToolSet("t", before, T3ToolSets.nextT3ToolSetTurn());
const planned = yield* plan(thread("t"), {});
// Planned, not opened (a continuation, or background work blocks the replacement).
assert.strictEqual(planned.name, "lean");
Expand All @@ -315,10 +318,106 @@ describe("makeClaudeMcpProfiles", () => {
),
);

/** A planner over settings the test changes between turns, from no opened process. */
const planner = Effect.gen(function* () {
T3ToolSets.__testing.clear();
ClaudeMcpProfileTesting.clearOpenedPlanKeys();
const service = yield* ServerSettingsService.ServerSettingsService;
const settings: { current: object } = { current: {} };
const plan = yield* makeClaudeMcpProfiles.pipe(
Effect.provideService(ServerSettingsService.ServerSettingsService, {
...service,
getSettings: Effect.suspend(() => Effect.succeed(fromFile(settings.current))),
}),
);
return { plan, settings };
});
const lean = (t3Tools: unknown) => ({
mcpProfile: "lean",
mcpProfiles: { lean: { servers: "all", t3Tools } },
});
const groupsOf = (threadId: string) => {
const set = T3ToolSets.t3ToolSetFor(threadId);
return set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set?._tag;
};
const withSettings = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.provide(
Layer.mergeAll(
ServerSettingsService.ServerSettingsService.layerTest(),
ManagedPolicy.layerTest(),
Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-mcp-profile-" })),
).pipe(Layer.provideMerge(NodeServices.layer)),
),
);

it.effect(
"never wider: a process opened with one plan meets a different, wider one (fork issue #986)",
() =>
withSettings(
Effect.gen(function* () {
const { plan, settings } = yield* planner;
const self = thread("t");
// Empty state (as after a restart): no process opened, so a plan fixes nothing yet.
settings.current = lean(["threads"]);
const first = yield* plan(self, {});
assert.isUndefined(T3ToolSets.t3ToolSetFor(self.id));
void first.options;
assert.deepStrictEqual(groupsOf(self.id), ["threads"]);
// A refused turn keeps the process, and only the ungrouped tools.
settings.current = { mcpProfile: "gone" };
assert.isTrue(isRefusal(yield* Effect.flip(plan(self, {}))));
assert.strictEqual(groupsOf(self.id), "Refused");
// The profile is widened: a different plan, and its process has not opened, so the
// thread keeps the refusal, never the wider set on the narrower process.
settings.current = lean(["threads", "orchestration"]);
yield* plan(self, {});
assert.strictEqual(groupsOf(self.id), "Refused");
// Runs again: the same plan as the process opened with gets that process's set back.
settings.current = lean(["threads"]);
yield* plan(self, {});
assert.deepStrictEqual(groupsOf(self.id), ["threads"]);
}),
),
);

it.effect(
"the cap drops the thread whose process was used longest ago, not the first opened (#986)",
() =>
withSettings(
Effect.gen(function* () {
const { plan, settings } = yield* planner;
settings.current = lean(["threads"]);
const first = thread("first");
void (yield* plan(first, {})).options;
for (let index = 1; index < T3ToolSets.MAX_T3_TOOL_SETS; index += 1) {
ClaudeMcpProfileTesting.keepOpenedPlanKey(ThreadId.make(`other-${index}`), "other-key");
}
// The first thread's process is used again (the same plan, no new process).
yield* plan(first, {});
// One more thread opens a process: the cap drops the one used longest ago.
void (yield* plan(thread("last"), {})).options;
assert.isTrue(ClaudeMcpProfileTesting.hasOpenedPlanKey(first.id));
assert.isFalse(ClaudeMcpProfileTesting.hasOpenedPlanKey(ThreadId.make("other-1")));
// So a turn after a refused one still gets the first thread's set back.
settings.current = { mcpProfile: "gone" };
yield* Effect.flip(plan(first, {}));
assert.strictEqual(groupsOf(first.id), "Refused");
settings.current = lean(["threads"]);
yield* plan(first, {});
assert.deepStrictEqual(groupsOf(first.id), ["threads"]);
}),
),
);

it.effect("a profile that cannot be worked out fixes no T3 tool but the ungrouped ones", () =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
T3ToolSets.fixT3ToolSet("t", { _tag: "Groups", name: "all", groups: "all" });
T3ToolSets.fixT3ToolSet(
"t",
{ _tag: "Groups", name: "all", groups: "all" },
T3ToolSets.nextT3ToolSetTurn(),
);
// The thread names a profile that is gone: the turn refuses, and the old `all` set is gone.
assert.include(
(yield* plansFor([{ mcpProfile: "gone" }]))[0],
Expand All @@ -333,7 +432,11 @@ describe("makeClaudeMcpProfiles", () => {
() =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
T3ToolSets.fixT3ToolSet("t", { _tag: "Groups", name: "all", groups: "all" });
T3ToolSets.fixT3ToolSet(
"t",
{ _tag: "Groups", name: "all", groups: "all" },
T3ToolSets.nextT3ToolSetTurn(),
);
const reading = yield* Deferred.make<void>();
const service = yield* ServerSettingsService.ServerSettingsService;
const plan = yield* makeClaudeMcpProfiles.pipe(
Expand Down
29 changes: 23 additions & 6 deletions apps/server/src/fork/claudeMcpProfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
MAX_T3_TOOL_SETS,
type T3ToolSet,
fixT3ToolSet,
nextT3ToolSetTurn,
refusedT3ToolSet,
t3ToolSetOf,
} from "./mcpT3ToolSets.ts";
Expand Down Expand Up @@ -728,6 +729,7 @@ const withAgentModelPolicy = (
*/
const openedPlanKeys = new Map<ThreadId, string | undefined>();

/** Keeps the thread's key as its most recently used; beyond the cap, the least recently used goes. */
const keepOpenedPlanKey = (threadId: ThreadId, key: string | undefined) => {
openedPlanKeys.delete(threadId);
openedPlanKeys.set(threadId, key);
Expand All @@ -737,6 +739,15 @@ const keepOpenedPlanKey = (threadId: ThreadId, key: string | undefined) => {
}
};

export const __testing = {
/** Forgets every process's plan key, as after a restart. */
clearOpenedPlanKeys: () => openedPlanKeys.clear(),
/** Records that the thread's process opened with `key`, as its options read does. */
keepOpenedPlanKey,
/** True while the thread's opened plan key is kept. */
hasOpenedPlanKey: (threadId: ThreadId) => openedPlanKeys.has(threadId),
};

/**
* The plan with its T3 tool set fixed when its `options` are first read: ClaudeAdapterV2 reads
* them only to open a new process, after the old one closed. A turn that keeps the live process (a
Expand All @@ -747,12 +758,13 @@ const fixedWhenOpened = (
plan: ClaudeMcpProfilePlan,
threadId: ThreadId,
set: T3ToolSet,
turn: number,
): ClaudeMcpProfilePlan => {
const { options, ...rest } = plan;
return Object.defineProperty({ ...rest }, "options", {
enumerable: true,
get: () => {
fixT3ToolSet(threadId, set);
fixT3ToolSet(threadId, set, turn);
keepOpenedPlanKey(threadId, planKey(plan));
return options;
},
Expand All @@ -768,28 +780,33 @@ export const makeClaudeMcpProfiles = Effect.gen(function* () {
thread: LineageThread,
overrides: McpOverrides,
) {
// Drawn before the read: a later turn's set stands over this one's, whichever finishes first.
const turn = nextT3ToolSetTurn();
// A profile that cannot apply refuses the turn and keeps only the tools every profile keeps,
// at once: narrowing never waits. A profile that applies is fixed as its process opens.
const resolved: McpProfileResolved = yield* profileFor(thread).pipe(
Effect.tapError((refusal) =>
Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason))),
Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason), turn)),
),
);
const t3ServerNames = Object.keys(overrides.mcpServers ?? {});
const plan = claudeMcpProfilePlan(resolved.name, resolved.profile, t3ServerNames);
if (isRefusal(plan)) {
fixT3ToolSet(thread.id, refusedT3ToolSet(plan.reason));
fixT3ToolSet(thread.id, refusedT3ToolSet(plan.reason), turn);
return yield* plan;
}
const set = t3ToolSetOf(resolved);
// The same plan as the thread's process opened with: the adapter keeps that process without
// reading the options, so its set is fixed here, the one that process has (never wider). This
// is how a good turn after a refused one gets its set back on the process the refusal kept.
if (openedPlanKeys.has(thread.id) && openedPlanKeys.get(thread.id) === planKey(plan)) {
fixT3ToolSet(thread.id, set);
// The thread counts as just used, so the cap drops threads not used for longest first.
const key = planKey(plan);
if (openedPlanKeys.has(thread.id) && openedPlanKeys.get(thread.id) === key) {
keepOpenedPlanKey(thread.id, key);
fixT3ToolSet(thread.id, set, turn);
}
// The policy hook goes in before the options are made lazy, so adding it reads nothing early.
return fixedWhenOpened(withAgentModelPolicy(plan, yield* agentPolicy), thread.id, set);
return fixedWhenOpened(withAgentModelPolicy(plan, yield* agentPolicy), thread.id, set, turn);
});

return Effect.fn("ClaudeMcpProfile.plan")(function* (
Expand Down
144 changes: 144 additions & 0 deletions apps/server/src/fork/codexMcpProfile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1478,6 +1478,150 @@ describe("follow-ups: holds, sub-agents, unknown threads, per-call checks (fork
const drive = <A, E>(fiber: Fiber.Fiber<A, E>, millis: number) =>
TestClock.adjust(millis).pipe(Effect.andThen(Fiber.join(fiber)));

describe("a newer turn's T3 tool set is never overwritten by an older one (fork issue #986)", () => {
/**
* The thread's profile reads, in order: each is `all` once the queue is empty, or waits for its
* gate and then gives its profile.
*/
const scripted = () => {
const queue: Array<Effect.Effect<McpProfileResolved>> = [];
const profileFor: ProfileById = () => queue.shift() ?? Effect.succeed(ALL);
const gated = (profile: McpProfileResolved) =>
Effect.gen(function* () {
const reached = yield* Deferred.make<void>();
const open = yield* Deferred.make<void>();
queue.push(
Deferred.succeed(reached, undefined).pipe(
Effect.andThen(Deferred.await(open)),
Effect.as(profile),
),
);
return { reached, open };
});
const next = (profile: McpProfileResolved) => void queue.push(Effect.succeed(profile));
return { profileFor, gated, next };
};
/**
* The thread's hold, for its `done`: done once every check holding it has released, which each
* does after fixing (or not) its set. A check whose profile read is not gated runs inside `emit`
* (forked to start at once, nothing to wait on), so only a gated read's end needs awaiting.
*/
const holdOf = (threadId: string) => T3ToolSets.t3ToolSetHold(threadId, 0)!.done;
const TIMED_OUT = T3ToolSets.refusedT3ToolSet("timed out");
/** What the T3 tool rule does as a request's wait on the hold reaches its bound. */
const dropAtBound = (threadId: string) =>
T3ToolSets.dropT3ToolSetHold(
threadId,
T3ToolSets.t3ToolSetHold(threadId, Number.MAX_SAFE_INTEGER)!,
TIMED_OUT,
);
const LEAN = resolved("lean", "all", ["waits"]);

it.effect("two checks finishing out of order: the later turn's set stands", () =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
const fake = makeFakeCodex({ servers: ["alpha"] });
const { profileFor, gated, next } = scripted();
const client = yield* withCodexMcpProfiles(fake.client, profileFor);
const id = (yield* start(client, "t")).thread.id;
// goal-2's check reads `all` slowly; the profile is narrowed; goal-3's check reads lean.
const slow = yield* gated(ALL);
next(LEAN);
yield* fake.emit("turn/started", turnStarted(id, "goal-2"));
yield* Deferred.await(slow.reached);
yield* fake.emit("turn/started", turnStarted(id, "goal-3"));
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
// goal-2's check finishes last: it must not widen the thread back to `all`.
const done = holdOf("t");
yield* Deferred.succeed(slow.open, undefined);
yield* Deferred.await(done);
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
assert.isUndefined(T3ToolSets.__testing.asked("t"));
// Runs again: the thread's next turn fixes its set as usual.
next(resolved("threads", "all", ["threads"]));
yield* fake.emit("turn/started", turnStarted(id, "goal-4"));
assert.deepStrictEqual(groupsOf("t"), ["threads"]);
}),
);

it.effect("a joining turn fixed its set while the first is stuck: the drop keeps it", () =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
const fake = makeFakeCodex({ servers: ["alpha"] });
const { profileFor, gated, next } = scripted();
const client = yield* withCodexMcpProfiles(fake.client, profileFor);
const id = (yield* start(client, "t")).thread.id;
const stuck = yield* gated(ALL);
next(LEAN);
yield* fake.emit("turn/started", turnStarted(id, "goal-2"));
yield* Deferred.await(stuck.reached);
// goal-3 joins goal-2's hold (and its bound), and fixes its set; goal-2's check still runs.
yield* fake.emit("turn/started", turnStarted(id, "goal-3"));
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
assert.isDefined(T3ToolSets.__testing.asked("t"));
// The bound passes: the hold goes, but goal-3's set stands (not Refused over it).
const done = holdOf("t");
assert.isFalse(dropAtBound("t"));
assert.isUndefined(T3ToolSets.__testing.asked("t"));
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
// goal-2's late check gives nothing either.
yield* Deferred.succeed(stuck.open, undefined);
yield* Deferred.await(done);
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
}),
);

it.effect(
"a turn T3 starts itself while a Codex turn's hold is stuck: the drop keeps its set",
() =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
const fake = makeFakeCodex({ servers: ["alpha"] });
const { profileFor, gated, next } = scripted();
const client = yield* withCodexMcpProfiles(fake.client, profileFor);
const id = (yield* start(client, "t")).thread.id;
const stuck = yield* gated(ALL);
yield* fake.emit("turn/started", turnStarted(id, "goal-2"));
yield* Deferred.await(stuck.reached);
// T3's own turn does not touch the hold, but it is later than goal-2: its set stands.
next(LEAN);
assert.strictEqual(yield* outcome(turn(client, id)), "ok");
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
const done = holdOf("t");
assert.isFalse(dropAtBound("t"));
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
yield* Deferred.succeed(stuck.open, undefined);
yield* Deferred.await(done);
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
}),
);

it.effect("a hold whose check never fixes a set: the drop still refuses (fails closed)", () =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
const fake = makeFakeCodex({ servers: ["alpha"] });
const { profileFor, gated } = scripted();
const client = yield* withCodexMcpProfiles(fake.client, profileFor);
const id = (yield* start(client, "t")).thread.id;
T3ToolSets.fixT3ToolSet(
"t",
{ _tag: "Groups", name: "all", groups: "all" },
T3ToolSets.nextT3ToolSetTurn(),
);
const stuck = yield* gated(LEAN);
yield* fake.emit("turn/started", turnStarted(id, "goal-2"));
yield* Deferred.await(stuck.reached);
const done = holdOf("t");
assert.isTrue(dropAtBound("t"));
assert.strictEqual(groupsOf("t"), "Refused");
// The stuck check is that turn's: when it finishes late, its set replaces the refusal.
yield* Deferred.succeed(stuck.open, undefined);
yield* Deferred.await(done);
assert.deepStrictEqual(groupsOf("t"), ["waits"]);
}),
);
});

describe("profiledClientFactory (settings and thread store)", () => {
const NOW = DateTime.makeUnsafe("2026-11-21T00:00:00.000Z");
const PROJECT = ProjectId.make("project");
Expand Down
Loading
Loading