@@ -5775,6 +5775,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
57755775 const scheduledWakeupsByNativeThread = new Map<string, number>();
57765776 // Native threads whose current turn Claude started by itself inside the early-fire margin.
57775777 const possibleEarlyWakeNativeThreads = new Set<string>();
5778+ // Turn starts a due or nearly due ScheduleWakeup may have caused.
5779+ const possibleScheduledWakeStarts = new WeakSet<SDKMessage>();
5780+ // A Monitor event wakes Claude with a bare turn and no task_notification frame, so the
5781+ // only evidence is a turn start while a Monitor runs that no ScheduleWakeup explains.
5782+ const monitorEventWakeStarts = new WeakSet<SDKMessage>();
57785783 const trackClaudeScheduledWakeup = Effect.fnUntraced(function* (
57795784 nativeThreadId: string,
57805785 message: SDKMessage,
@@ -5783,6 +5788,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
57835788 const scheduledFor = scheduledWakeupsByNativeThread.get(nativeThreadId);
57845789 if (scheduledFor === undefined) return;
57855790 const now = DateTime.toEpochMillis(yield* DateTime.now);
5791+ if (now >= scheduledFor - CLAUDE_SCHEDULED_WAKEUP_EARLY_FIRE_MARGIN_MS) {
5792+ possibleScheduledWakeStarts.add(message);
5793+ }
57865794 if (now >= scheduledFor) {
57875795 scheduledWakeupsByNativeThread.delete(nativeThreadId);
57885796 } else if (
@@ -5864,6 +5872,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
58645872 for (const [taskId] of endedIds) tasks.delete(taskId);
58655873 return [tasks, { ...current, tasks }] as const;
58665874 });
5875+ const hasRunningClaudeMonitor = (nativeThreadId: string) =>
5876+ Ref.get(claudeMonitors).pipe(
5877+ Effect.map((current) =>
5878+ [...current.tasks.values()].some((task) => task.nativeThreadId === nativeThreadId),
5879+ ),
5880+ );
5881+ // The buffer's first wake is a Monitor event: its result, once known, is a task notification's.
5882+ const isClaudeMonitorEventWake = (messages: ReadonlyArray<SDKMessage>) => {
5883+ const startIndex = messages.findIndex(isClaudeTurnStartMessage);
5884+ const start = messages[startIndex];
5885+ if (start === undefined || !monitorEventWakeStarts.has(start)) return false;
5886+ const result = messages
5887+ .slice(startIndex + 1)
5888+ .find(
5889+ (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
5890+ );
5891+ return result === undefined || isClaudeTaskNotificationOriginResult(result);
5892+ };
58675893 const claudeTaskOutcome = (status: "completed" | "failed" | "stopped") =>
58685894 status === "completed" ? "completed" : status === "stopped" ? "cancelled" : "failed";
58695895 // Reads the roster, so call it before the notification clears the task from it.
@@ -5905,6 +5931,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
59055931 readonly token: symbol;
59065932 readonly end: SDKMessage | undefined;
59075933 readonly retired: "unopened" | "opened" | null;
5934+ // Offered as Monitor progress, which starts no delegated follow-up.
5935+ readonly monitorEvent: boolean;
59085936 }
59095937 >(),
59105938 );
@@ -9379,6 +9407,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
93799407 if (isClaudeRootTurnFrame(message)) {
93809408 yield* forgetAbsorbedWake(wakeInput.nativeThreadId);
93819409 }
9410+ if (
9411+ isWakeTurnStart &&
9412+ !possibleScheduledWakeStarts.has(message) &&
9413+ (yield* hasRunningClaudeMonitor(wakeInput.nativeThreadId))
9414+ ) {
9415+ monitorEventWakeStarts.add(message);
9416+ }
93829417 yield* Ref.update(wakeBuffers, (current) => {
93839418 const existing = current.get(wakeInput.nativeThreadId);
93849419 const updated = new Map(current);
@@ -9435,6 +9470,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
94359470 }
94369471 const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId);
94379472 const token = Symbol(nativeThreadId);
9473+ // A recorded report names finished work, which outranks Monitor progress.
9474+ const monitorEvent =
9475+ ((yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId)?.size ?? 0) ===
9476+ 0 && isClaudeMonitorEventWake(buffered?.messages ?? []);
94389477 const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => {
94399478 if (current.has(nativeThreadId)) {
94409479 return [false, current] as const;
@@ -9446,6 +9485,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
94469485 (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
94479486 ),
94489487 retired: null,
9488+ monitorEvent,
94499489 });
94509490 return [true, updated] as const;
94519491 });
@@ -9454,7 +9494,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
94549494 }
94559495 const reports = yield* takeWakeReports(nativeThreadId);
94569496 const notification = backgroundWorkNotification(
9457- [...(reports?.values() ?? [])].map((entry) => entry.report),
9497+ monitorEvent
9498+ ? [{ kind: "monitor", outcome: "updated" }]
9499+ : [...(reports?.values() ?? [])].map((entry) => entry.report),
94589500 );
94599501 yield* Effect.logInfo("orchestration-v2.claude-wake-turn-detected", {
94609502 providerSessionId: input.providerSessionId,
@@ -9610,9 +9652,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
96109652 // After a retired wake releases its latch, a wake buffered behind it has had no offer of its own.
96119653 const offerBufferedWake = Effect.fnUntraced(function* (nativeThreadId: string) {
96129654 const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
9655+ if (yield* holdsBufferedWake(nativeThreadId, messages))
9656+ yield* offerWakeContinuation(nativeThreadId);
9657+ });
9658+
9659+ const holdsBufferedWake = Effect.fnUntraced(function* (
9660+ nativeThreadId: string,
9661+ messages: ReadonlyArray<SDKMessage>,
9662+ ) {
96139663 const reports = (yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId);
96149664 // A lifecycle result ends no turn, and closes the root frames before it.
9615- const hasWake =
9665+ return (
96169666 messages
96179667 .slice(messages.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1)
96189668 .some(isClaudeRootTurnFrame) ||
@@ -9622,8 +9672,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
96229672 (entry.type === "system" &&
96239673 entry.subtype === "task_notification" &&
96249674 reports?.get(entry.task_id)?.report.kind === "subagent"),
9625- );
9626- if (hasWake) yield* offerWakeContinuation(nativeThreadId );
9675+ )
9676+ );
96279677 });
96289678
96299679 // Untraced like the roster message handling: it runs for every streamed roster change.
@@ -12615,13 +12665,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1261512665 yield* sdkMessageLock.withPermits(1)(
1261612666 Effect.gen(function* () {
1261712667 yield* attachTurn;
12618- const drained = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
12668+ const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
12669+ const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId);
12670+ // This run carries the Monitor tag, which starts no delegated follow-up, so a wake
12671+ // buffered behind the Monitor event is left for a continuation of its own.
12672+ const ownEndIndex =
12673+ latch?.monitorEvent === true && latch.end !== undefined
12674+ ? buffered.indexOf(latch.end)
12675+ : -1;
12676+ const leavesLaterWake =
12677+ ownEndIndex !== -1 &&
12678+ (yield* holdsBufferedWake(nativeThreadId, buffered.slice(ownEndIndex + 1)));
12679+ const drained = leavesLaterWake ? buffered.slice(0, ownEndIndex + 1) : buffered;
1261912680 yield* Ref.update(requestedContinuations, (current) => {
1262012681 const updated = new Map(current);
1262112682 updated.delete(nativeThreadId);
1262212683 return updated;
1262312684 });
12624- const wakeAbsorbed = (yield* Ref.get(absorbedWakes)).has(nativeThreadId);
12685+ // A split wake that a user turn ended gets no result of its own.
12686+ const wakeAbsorbed =
12687+ (yield* Ref.get(absorbedWakes)).has(nativeThreadId) ||
12688+ (leavesLaterWake && latch?.end?.type !== "result");
1262512689 yield* forgetAbsorbedWake(nativeThreadId);
1262612690 if (drained.length === 0) {
1262712691 const completedAt = yield* DateTime.now;
@@ -12683,11 +12747,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1268312747 }
1268412748 if (lastResult !== undefined && !emptyTurnBeforeNextTurn) {
1268512749 yield* handleSdkMessage({ query: querySession.query, message: lastResult });
12750+ if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId);
1268612751 return;
1268712752 }
1268812753 if (wakeAbsorbed || (hasOpaqueTaskNotification && !context.nativeWakeStarted)) {
1268912754 const completedAt = yield* DateTime.now;
1269012755 yield* finalizeActiveTurn({ context, status: "completed", completedAt });
12756+ if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId);
1269112757 } else if (!context.nativeWakeStarted) {
1269212758 yield* Effect.sleep(CLAUDE_WAKE_TURN_START_DEADLINE).pipe(
1269312759 Effect.andThen(
0 commit comments