Skip to content

Commit 98d67c1

Browse files
Jreevoclaude
andcommitted
fix(server): a Claude /goal no longer reads as complete while a background subagent runs
Claude Code skips a goal's Stop hook check while background work runs and checks again on a later turn. The adapter inferred completion from a normal turn end plus an empty roster, but the roster leaves subagents out, so a turn that ended while a background Agent ran marked the goal complete. The completion check now also requires that the live process runs no background work of the types Claude Code 2.1.292 waits on: local_agent, remote_agent, in_process_teammate and local_workflow on the subagent path (local_bash is already on the roster). Tasks of other types, such as mcp_task and monitor_ws, are exempt, as they are in Claude. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent c9b21b2 commit 98d67c1

2 files changed

Lines changed: 249 additions & 2 deletions

File tree

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

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8311,6 +8311,222 @@ describe("ClaudeAdapterV2 background wake turns", () => {
83118311
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
83128312
);
83138313

8314+
// Level entries from Claude Code 2.1.292 carry no ambient flag.
8315+
const backgroundTasksLevel = (
8316+
uuid: string,
8317+
tasks: ReadonlyArray<{ readonly taskId: string; readonly taskType: string }>,
8318+
) =>
8319+
claudeSdkFrame({
8320+
type: "system",
8321+
subtype: "background_tasks_changed",
8322+
tasks: tasks.map((task) => ({
8323+
task_id: task.taskId,
8324+
task_type: task.taskType,
8325+
description: "Background task",
8326+
})),
8327+
uuid,
8328+
session_id: WAKE_NATIVE_SESSION,
8329+
} as unknown as SDKMessage);
8330+
// Frame order captured from Claude Code 2.1.292: the Agent call, the
8331+
// level, the backgrounded task_started, its async ack, the model's reply,
8332+
// then the result while the subagent still runs.
8333+
const backgroundAgentLaunchFrames = (input: {
8334+
readonly prefix: string;
8335+
readonly taskId: string;
8336+
}) => {
8337+
const toolUseId = `toolu-${input.prefix}`;
8338+
return [
8339+
claudeSdkFrame({
8340+
type: "assistant",
8341+
message: {
8342+
model: "claude-sonnet-4-6",
8343+
id: `msg-${input.prefix}-launch`,
8344+
type: "message",
8345+
role: "assistant",
8346+
content: [
8347+
{
8348+
type: "tool_use",
8349+
id: toolUseId,
8350+
name: "Agent",
8351+
input: {
8352+
description: "Implement the fix",
8353+
subagent_type: "general-purpose",
8354+
run_in_background: true,
8355+
prompt: "Implement the fix.",
8356+
},
8357+
},
8358+
],
8359+
},
8360+
parent_tool_use_id: null,
8361+
uuid: `${input.prefix}-launch`,
8362+
session_id: WAKE_NATIVE_SESSION,
8363+
}),
8364+
backgroundTasksLevel(`${input.prefix}-level`, [
8365+
{ taskId: input.taskId, taskType: "local_agent" },
8366+
]),
8367+
claudeSdkFrame({
8368+
type: "system",
8369+
subtype: "task_started",
8370+
task_id: input.taskId,
8371+
tool_use_id: toolUseId,
8372+
description: "Implement the fix",
8373+
subagent_type: "general-purpose",
8374+
is_backgrounded: true,
8375+
task_type: "local_agent",
8376+
prompt: "Implement the fix.",
8377+
uuid: `${input.prefix}-task-started`,
8378+
session_id: WAKE_NATIVE_SESSION,
8379+
}),
8380+
claudeSdkFrame({
8381+
type: "user",
8382+
message: {
8383+
role: "user",
8384+
content: [
8385+
{
8386+
type: "tool_result",
8387+
tool_use_id: toolUseId,
8388+
content: [{ type: "text", text: "Async agent launched successfully." }],
8389+
},
8390+
],
8391+
},
8392+
parent_tool_use_id: null,
8393+
uuid: `${input.prefix}-ack`,
8394+
session_id: WAKE_NATIVE_SESSION,
8395+
}),
8396+
];
8397+
};
8398+
8399+
it.effect("defers goal completion while a background subagent runs", () =>
8400+
Effect.gen(function* () {
8401+
const harness = yield* makeWakeHarness;
8402+
const condition = "both reviewers find no bugs";
8403+
const taskId = "task-goal-background-subagent";
8404+
const now = yield* DateTime.now;
8405+
yield* harness.runtime.startTurn(
8406+
makeClaudeTestTurnInput({
8407+
threadId: harness.threadId,
8408+
providerThread: harness.providerThread,
8409+
now,
8410+
attemptId: RunAttemptId.make("goal-background-attempt"),
8411+
text: `/goal ${condition}`,
8412+
attachments: [],
8413+
}),
8414+
);
8415+
for (const frame of [
8416+
syntheticFrame("goal-background-set", `Goal set: ${condition}`),
8417+
...backgroundAgentLaunchFrames({ prefix: "goal-background", taskId }),
8418+
makeAssistantTextFrame({
8419+
uuid: "goal-background-wait",
8420+
text: "Waiting for the background subagent before round 1.",
8421+
}),
8422+
makeResultFrame({
8423+
uuid: "goal-background-result",
8424+
result: "Waiting for the background subagent before round 1.",
8425+
}),
8426+
]) {
8427+
yield* Queue.offer(harness.sdkMessages, frame);
8428+
}
8429+
yield* Queue.take(harness.terminalReceipts);
8430+
// Claude skips the goal check while the subagent runs.
8431+
assert.equal(goalStatuses(harness.events).at(-1)?.status, "active");
8432+
8433+
// The subagent ends; Claude opens a turn on its own, and the goal
8434+
// check at its end passes.
8435+
yield* harness.offerAndWait(
8436+
claudeSdkFrame({
8437+
type: "system",
8438+
subtype: "task_notification",
8439+
task_id: taskId,
8440+
tool_use_id: "toolu-goal-background",
8441+
status: "completed",
8442+
output_file: `/tmp/${taskId}.output`,
8443+
summary: "Fix implemented.",
8444+
uuid: "goal-background-notification",
8445+
session_id: WAKE_NATIVE_SESSION,
8446+
}),
8447+
);
8448+
yield* harness.offerAndWait(backgroundTasksLevel("goal-background-level-empty", []));
8449+
yield* harness.offerAndWait(wakeTurnInit);
8450+
assert.lengthOf(harness.continuationRequests, 1);
8451+
yield* harness.runtime.startTurn(
8452+
makeClaudeTestTurnInput({
8453+
threadId: harness.threadId,
8454+
providerThread: harness.providerThread,
8455+
now,
8456+
attemptId: RunAttemptId.make("goal-background-wake"),
8457+
text: "Background task completed.",
8458+
attachments: [],
8459+
providerTurnOrdinal: 2,
8460+
messageCreatedBy: "agent",
8461+
messageCreationSource: "provider",
8462+
}),
8463+
);
8464+
yield* harness.offerAndWait(
8465+
makeAssistantTextFrame({ uuid: "goal-background-wake-work", text: "No bugs found." }),
8466+
);
8467+
yield* harness.offerAndWait(
8468+
makeResultFrame({
8469+
uuid: "goal-background-wake-result",
8470+
result: "No bugs found.",
8471+
origin: { kind: "task-notification" },
8472+
}),
8473+
);
8474+
yield* Queue.take(harness.terminalReceipts);
8475+
assert.deepEqual(goalStatuses(harness.events).at(-1), {
8476+
objective: condition,
8477+
status: "complete",
8478+
checks: 0,
8479+
});
8480+
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
8481+
);
8482+
8483+
// Claude's goal check waits on agents, workflows and shells by task type,
8484+
// ambient or not, and never on mcp_task or monitor_mcp/monitor_ws tasks.
8485+
// A task with no type is treated as one Claude waits on.
8486+
it.effect.each([
8487+
{ taskType: "mcp_task", ambient: false, status: "complete" },
8488+
{ taskType: "local_agent", ambient: true, status: "active" },
8489+
{ taskType: undefined, ambient: false, status: "active" },
8490+
] as const)("treats a running $taskType (ambient $ambient) as goal $status", (input) =>
8491+
Effect.gen(function* () {
8492+
const harness = yield* makeWakeHarness;
8493+
const condition = "the docs build";
8494+
const taskId = `task-goal-${input.taskType}`;
8495+
yield* harness.runtime.startTurn(
8496+
makeClaudeTestTurnInput({
8497+
threadId: harness.threadId,
8498+
providerThread: harness.providerThread,
8499+
now: yield* DateTime.now,
8500+
attemptId: RunAttemptId.make(`goal-${input.taskType}-attempt`),
8501+
text: `/goal ${condition}`,
8502+
attachments: [],
8503+
}),
8504+
);
8505+
for (const frame of [
8506+
syntheticFrame(`goal-${input.taskType}-set`, `Goal set: ${condition}`),
8507+
backgroundTasksLevel(`goal-${input.taskType}-level`, [
8508+
{ taskId, taskType: input.taskType ?? "local_agent" },
8509+
]),
8510+
claudeSdkFrame({
8511+
type: "system",
8512+
subtype: "task_started",
8513+
task_id: taskId,
8514+
description: "Watch the docs",
8515+
...(input.taskType === undefined ? {} : { task_type: input.taskType }),
8516+
...(input.ambient ? { skip_transcript: true, ambient: true } : {}),
8517+
uuid: `goal-${input.taskType}-task-started`,
8518+
session_id: WAKE_NATIVE_SESSION,
8519+
}),
8520+
makeAssistantTextFrame({ uuid: `goal-${input.taskType}-work`, text: "The docs build." }),
8521+
makeResultFrame({ uuid: `goal-${input.taskType}-result`, result: "The docs build." }),
8522+
]) {
8523+
yield* Queue.offer(harness.sdkMessages, frame);
8524+
}
8525+
yield* Queue.take(harness.terminalReceipts);
8526+
assert.equal(goalStatuses(harness.events).at(-1)?.status, input.status);
8527+
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
8528+
);
8529+
83148530
it.effect("keeps a goal active after a command turn with no model output", () =>
83158531
Effect.gen(function* () {
83168532
const harness = yield* makeWakeHarness;

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

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1788,6 +1788,17 @@ const CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS: ReadonlyMap<
17881788
Exclude<OrchestrationV2PendingBackgroundTask["kind"], "subagent">
17891789
> = new Map([["local_bash", "command"]]);
17901790

1791+
// Task types whose running tasks make Claude skip a goal's Stop hook check,
1792+
// as Claude Code 2.1.292 decides it. local_bash (Monitor tool runs included)
1793+
// is the roster's; the rest run on the subagent path. mcp_task, monitor_mcp
1794+
// and monitor_ws tasks do not defer the check.
1795+
const CLAUDE_GOAL_DEFERRING_TASK_TYPES: ReadonlySet<string> = new Set([
1796+
"local_agent",
1797+
"remote_agent",
1798+
"in_process_teammate",
1799+
"local_workflow",
1800+
]);
1801+
17911802
function isClaudeOpaqueBackgroundTaskType(taskType: string | null | undefined): boolean {
17921803
return typeof taskType === "string" && CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS.has(taskType);
17931804
}
@@ -3157,6 +3168,8 @@ export function makeClaudeAdapterV2(
31573168
}>({ userTurns: new Map(), reports: new Map() });
31583169
// Subagents Claude started in the background. Only their ends wake the root.
31593170
const backgroundedSubagentTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
3171+
// Subagent-path tasks whose type Claude's goal check does not wait for.
3172+
const goalExemptTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
31603173
// Subagents another subagent started (spawn_depth above 1). Claude
31613174
// reports their end to the owning subagent, so it never wakes the root.
31623175
const nestedSubagentTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
@@ -5082,20 +5095,27 @@ export function makeClaudeAdapterV2(
50825095
input.context.input.providerThread.nativeConversationHeadRef !== null;
50835096
// While a goal is set, Claude ends a turn on its own only after the
50845097
// goal's Stop hook passes. It defers that check while background
5085-
// work runs, and a hook that stops the turn reports another reason.
5098+
// work of the types it waits on runs (subagents stay off the roster;
5099+
// see CLAUDE_GOAL_DEFERRING_TASK_TYPES), and a hook that stops the
5100+
// turn reports another reason.
50865101
// SDK mode does not report an evaluator timeout or an impossible
50875102
// verdict, so those still read as complete.
50885103
const goal =
50895104
nativeThreadId === null ? undefined : goalsByNativeThread.get(nativeThreadId);
50905105
const goalChecked = goalCheckedTurns.delete(input.context.providerTurnId);
50915106
const terminalReason = input.result?.terminal_reason;
5107+
const liveQuery = yield* Ref.get(queryContext);
50925108
if (
50935109
nativeThreadId !== null &&
50945110
goal?.status === "active" &&
50955111
goalChecked &&
50965112
input.status === "completed" &&
50975113
(terminalReason === undefined || terminalReason === "completed") &&
5098-
roster.size === 0
5114+
roster.size === 0 &&
5115+
!(
5116+
liveQuery?.nativeThreadId === nativeThreadId &&
5117+
(yield* liveProcessRunsBackgroundWork(liveQuery, { forGoalCheck: true }))
5118+
)
50995119
) {
51005120
goalsByNativeThread.set(nativeThreadId, {
51015121
objective: goal.objective,
@@ -6024,6 +6044,14 @@ export function makeClaudeAdapterV2(
60246044
activeContext: context,
60256045
});
60266046
} else {
6047+
if (
6048+
message.task_type !== undefined &&
6049+
!CLAUDE_GOAL_DEFERRING_TASK_TYPES.has(message.task_type)
6050+
) {
6051+
yield* Ref.update(goalExemptTaskIds, (current) =>
6052+
new Set(current).add(message.task_id),
6053+
);
6054+
}
60276055
const launch =
60286056
message.tool_use_id === undefined
60296057
? undefined
@@ -7011,6 +7039,7 @@ export function makeClaudeAdapterV2(
70117039
// already buffered is done: the buffer outlives the process.
70127040
const liveProcessRunsBackgroundWork = Effect.fnUntraced(function* (
70137041
live: ClaudeLiveQueryContext,
7042+
options?: { readonly forGoalCheck?: boolean },
70147043
) {
70157044
if (
70167045
rosterForNativeThread(
@@ -7021,10 +7050,12 @@ export function makeClaudeAdapterV2(
70217050
return true;
70227051
}
70237052
const buffered = (yield* Ref.get(wakeBuffers)).get(live.nativeThreadId)?.messages ?? [];
7053+
const ignored = options?.forGoalCheck === true ? yield* Ref.get(goalExemptTaskIds) : null;
70247054
for (const [taskId, subagent] of yield* Ref.get(sessionSubagentsByTaskId)) {
70257055
if (
70267056
subagent.task.status === "running" &&
70277057
!live.subagentsFromEarlierProcesses.has(subagent) &&
7058+
!(ignored?.has(taskId) ?? false) &&
70287059
!buffered.some(
70297060
(message) =>
70307061
message.type === "system" &&

0 commit comments

Comments
 (0)