sailfork / t3code-github / apps/ server/ src/ orchestration-v2/ Adapters/ ClaudeAdapterV2.testkit.ts

import { ClaudeSettings } from "@t3tools/contracts";
import {
  forkSession,
  query,
  type CanUseTool,
  type PermissionResult,
  type SDKAssistantMessage,
  type SDKMessage,
  type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import {
  ProviderReplayEntry,
  type ModelSelection,
  type ProviderApprovalDecision,
  type ProviderReplayTranscript,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";

import * as ServerConfig from "../../config.ts";
import {
  isWindowsClaudeLauncherShimPath,
  resolveClaudeSdkExecutablePath,
} from "../../provider/Drivers/ClaudeExecutable.ts";
import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts";
import { claudeTaskOutputRoot } from "./ClaudeTaskOutputTail.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver";
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
import {
  makeReplayServerConfig,
  type OrchestratorV2ProviderReplayHarness,
} from "../testkit/ProviderReplayHarness.ts";
import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";

export const CLAUDE_AGENT_SDK_REPLAY_PROTOCOL = "claude-agent-sdk.query" as const;
export const claudeBackgroundWakeResultLabel = (wakeNumber: number) =>
  `result:background-wake:${wakeNumber}`;

const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({});

const ClaudeAgentSdkReplayTranscript = Schema.Struct({
  provider: Schema.Literal(ClaudeAdapterV2.CLAUDE_PROVIDER),
  protocol: Schema.Literal(CLAUDE_AGENT_SDK_REPLAY_PROTOCOL),
  version: Schema.String,
  scenario: Schema.String,
  metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  entries: Schema.Array(ProviderReplayEntry),
});
type ClaudeAgentSdkReplayTranscript = typeof ClaudeAgentSdkReplayTranscript.Type;

export class ClaudeReplayTranscriptDecodeError extends Schema.TaggedError<ClaudeReplayTranscriptDecodeError>()(
  "ClaudeReplayTranscriptDecodeError",
  {
    driver: Schema.optional(Schema.String),
    protocol: Schema.optional(Schema.String),
    scenario: Schema.optional(Schema.String),
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return `Failed to decode Claude Agent SDK replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
  }
}

export class ClaudeReplayExhaustedError extends Schema.TaggedError<ClaudeReplayExhaustedError>()(
  "ClaudeReplayExhaustedError",
  {
    scenario: Schema.String,
    cursor: Schema.Number,
    actual: Schema.Unknown,
  },
) {
  override get message(): string {
    return `Claude Agent SDK replay transcript exhausted before outbound frame ${this.cursor} in scenario ${this.scenario}.`;
  }
}

export class ClaudeReplayUnexpectedOutboundError extends Schema.TaggedError<ClaudeReplayUnexpectedOutboundError>()(
  "ClaudeReplayUnexpectedOutboundError",
  {
    scenario: Schema.String,
    cursor: Schema.Number,
    expectedType: Schema.String,
    actual: Schema.Unknown,
  },
) {
  override get message(): string {
    return `Unexpected outbound Claude Agent SDK frame at replay cursor ${this.cursor} in scenario ${this.scenario}.`;
  }
}

export class ClaudeReplayFrameMismatchError extends Schema.TaggedError<ClaudeReplayFrameMismatchError>()(
  "ClaudeReplayFrameMismatchError",
  {
    scenario: Schema.String,
    cursor: Schema.Number,
    label: Schema.optional(Schema.String),
    expected: Schema.Unknown,
    actual: Schema.Unknown,
  },
) {
  override get message(): string {
    return `Outbound Claude Agent SDK frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}.`;
  }
}

export class ClaudeReplayRuntimeExitError extends Schema.TaggedError<ClaudeReplayRuntimeExitError>()(
  "ClaudeReplayRuntimeExitError",
  {
    scenario: Schema.String,
    cursor: Schema.Number,
    status: Schema.Literals(["error", "cancelled"]),
    error: Schema.optional(Schema.Unknown),
  },
) {
  override get message(): string {
    return `Claude Agent SDK replay exited with status ${this.status} at cursor ${this.cursor} in scenario ${this.scenario}.`;
  }
}

export class ClaudeReplayIncompleteError extends Schema.TaggedError<ClaudeReplayIncompleteError>()(
  "ClaudeReplayIncompleteError",
  {
    scenario: Schema.String,
    cursor: Schema.Number,
    remaining: Schema.Number,
  },
) {
  override get message(): string {
    return `Claude Agent SDK replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`;
  }
}

export class ClaudeReplayDriverError extends Schema.TaggedError<ClaudeReplayDriverError>()(
  "ClaudeReplayDriverError",
  {
    scenario: Schema.String,
    cause: Schema.Defect(),
  },
) {
  override get message(): string {
    return `Claude Agent SDK replay driver failed in scenario ${this.scenario}.`;
  }
}

export const ClaudeAgentSdkReplayError = Schema.Union([
  ClaudeReplayTranscriptDecodeError,
  ClaudeReplayExhaustedError,
  ClaudeReplayUnexpectedOutboundError,
  ClaudeReplayFrameMismatchError,
  ClaudeReplayRuntimeExitError,
  ClaudeReplayIncompleteError,
  ClaudeReplayDriverError,
]);
export type ClaudeAgentSdkReplayError = typeof ClaudeAgentSdkReplayError.Type;
export const ClaudeOrchestratorReplayHarnessError = Schema.Union([
  ClaudeAgentSdkReplayError,
  ProviderAdapterDriverCreateError,
]);
export type ClaudeOrchestratorReplayHarnessError = typeof ClaudeOrchestratorReplayHarnessError.Type;

interface ClaudeQueryOpenFrame {
  readonly type: "query.open";
  readonly options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions;
}

interface ClaudePromptOfferFrame {
  readonly type: "prompt.offer";
  readonly message: SDKUserMessage;
}

interface ClaudeQuerySetModelFrame {
  readonly type: "query.set_model";
  readonly model: string;
}

interface ClaudeQuerySetPermissionModeFrame {
  readonly type: "query.set_permission_mode";
  readonly mode: string;
}

interface ClaudeQueryInterruptFrame {
  readonly type: "query.interrupt";
}

interface ClaudePermissionRequestFrame {
  readonly type: "permission.request";
  readonly toolName: string;
  readonly input: Record<string, unknown>;
  readonly options: {
    readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
    readonly blockedPath?: string;
    readonly decisionReason?: string;
    readonly title?: string;
    readonly displayName?: string;
    readonly description?: string;
    readonly toolUseID: string;
    readonly agentID?: string;
  };
}

interface ClaudePermissionResponseFrame {
  readonly type: "permission.response";
  readonly result: PermissionResult;
}

interface ClaudeSessionForkFrame {
  readonly type: "session.fork";
  readonly sessionId: string;
  readonly options: {
    readonly dir?: string;
    readonly upToMessageId?: string;
    readonly title?: string;
  };
}

interface ClaudeSessionForkedFrame {
  readonly type: "session.forked";
  readonly sessionId: string;
}

interface ClaudeSubagentLookupFrame {
  readonly type: "subagent.lookup";
  readonly sessionId: string;
  readonly agentId: string;
}

interface ClaudeSubagentFoundFrame {
  readonly type: "subagent.found";
  readonly toolUseId: string | null;
}

type ClaudeOutboundFrame =
  | { readonly type: "query.stop_task"; readonly taskId: string }
  | { readonly type: "query.background_tasks"; readonly toolUseId: string }
  | ClaudeQueryOpenFrame
  | ClaudePromptOfferFrame
  | ClaudeQuerySetModelFrame
  | {
      readonly type: "query.apply_flag_settings";
      readonly settings: Parameters<
        ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"]
      >[0];
    }
  | ClaudeQuerySetPermissionModeFrame
  | ClaudeQueryInterruptFrame
  | ClaudePermissionResponseFrame
  | ClaudeSessionForkFrame
  | ClaudeSubagentLookupFrame;

interface ClaudeQueryRunner {
  readonly open: (
    input: ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput,
  ) => ClaudeAdapterV2.ClaudeAgentSdkQuerySession;
  readonly forkSession: (
    input: ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput,
  ) => ClaudeSessionForkedFrame;
  readonly subagentLaunchToolUseId: (
    input: ClaudeAdapterV2.ClaudeAgentSdkSubagentLookupInput,
  ) => string | null;
  readonly assertComplete: () => void;
}

function stableStringify(value: unknown): string {
  if (Array.isArray(value)) {
    return `[${value.map(stableStringify).join(",")}]`;
  }
  if (typeof value === "object" && value !== null) {
    const record = value as Record<string, unknown>;
    return `{${Object.keys(record)
      .toSorted()
      .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
      .join(",")}}`;
  }
  return JSON.stringify(value);
}

function normalizeContextHandoffText(value: string): string {
  if (!value.startsWith("Context handoff (")) {
    return value;
  }
  const userMessageMarker = "\n\nUser message:\n";
  const userMessageIndex = value.indexOf(userMessageMarker);
  const headerEndIndex = value.indexOf(":\n");
  if (headerEndIndex === -1 || userMessageIndex === -1 || headerEndIndex >= userMessageIndex) {
    return value;
  }
  return `${value.slice(0, headerEndIndex + 2)}<dynamic-summary>${value.slice(userMessageIndex)}`;
}

function normalizeReplayFrame(value: unknown): unknown {
  if (typeof value === "string") {
    return normalizeContextHandoffText(value);
  }
  if (Array.isArray(value)) {
    return value.map(normalizeReplayFrame);
  }
  if (typeof value !== "object" || value === null) {
    return value;
  }
  return Object.fromEntries(
    Object.entries(value).map(([key, entry]) => [key, normalizeReplayFrame(entry)]),
  );
}

function sameFrame(left: unknown, right: unknown): boolean {
  return (
    stableStringify(normalizeReplayFrame(left)) === stableStringify(normalizeReplayFrame(right))
  );
}

function isClaudeSdkReplayMessage(frame: unknown): frame is SDKMessage {
  if (typeof frame !== "object" || frame === null) {
    return false;
  }
  const type = Reflect.get(frame, "type");
  return (
    type === "assistant" ||
    type === "user" ||
    type === "result" ||
    type === "system" ||
    type === "stream_event" ||
    type === "rate_limit_event" ||
    // The SDK types omit command_lifecycle for prompt uuids.
    type === "command_lifecycle"
  );
}

function sdkMessageFromReplayFrame(frame: unknown): SDKMessage {
  if (!isClaudeSdkReplayMessage(frame)) {
    throw new Error("Replay frame is not a Claude Agent SDK message.");
  }
  return frame;
}

function isClaudePermissionRequestFrame(frame: unknown): frame is ClaudePermissionRequestFrame {
  const options =
    typeof frame === "object" && frame !== null ? Reflect.get(frame, "options") : undefined;
  return (
    typeof frame === "object" &&
    frame !== null &&
    Reflect.get(frame, "type") === "permission.request" &&
    typeof Reflect.get(frame, "toolName") === "string" &&
    typeof Reflect.get(frame, "input") === "object" &&
    Reflect.get(frame, "input") !== null &&
    typeof options === "object" &&
    options !== null &&
    typeof Reflect.get(options, "toolUseID") === "string"
  );
}

function makeClaudePermissionResponseFrame(
  result: PermissionResult,
): ClaudePermissionResponseFrame {
  return {
    type: "permission.response",
    result,
  };
}

function permissionRequestOptionsFromFrame(
  frame: ClaudePermissionRequestFrame,
  signal: AbortSignal,
): Parameters<CanUseTool>[2] {
  const options = frame.options;
  return {
    signal,
    ...(options.suggestions === undefined ? {} : { suggestions: options.suggestions }),
    ...(options.blockedPath === undefined ? {} : { blockedPath: options.blockedPath }),
    ...(options.decisionReason === undefined ? {} : { decisionReason: options.decisionReason }),
    ...(options.title === undefined ? {} : { title: options.title }),
    ...(options.displayName === undefined ? {} : { displayName: options.displayName }),
    ...(options.description === undefined ? {} : { description: options.description }),
    toolUseID: options.toolUseID,
    ...(options.agentID === undefined ? {} : { agentID: options.agentID }),
    requestId: options.toolUseID,
  };
}

function unresolvedCursorSignal(): void {}

function makeCursorSignal(): {
  readonly promise: Promise<void>;
  readonly resolve: () => void;
} {
  let resolve: () => void = unresolvedCursorSignal;
  const promise = new Promise<void>((onResolve) => {
    resolve = onResolve;
  });
  return { promise, resolve };
}

function waitForCursorAdvance(promise: Promise<void>, signal: AbortSignal): Promise<void> {
  if (signal.aborted) {
    return Promise.resolve();
  }
  return new Promise<void>((resolve) => {
    let waiting = true;
    const finish = () => {
      if (!waiting) {
        return;
      }
      waiting = false;
      signal.removeEventListener("abort", finish);
      resolve();
    };
    signal.addEventListener("abort", finish, { once: true });
    void promise.then(finish);
    if (signal.aborted) {
      finish();
    }
  });
}

async function waitForReplayDelay(afterMs: number, signal: AbortSignal): Promise<void> {
  const exit = await Effect.runPromiseExit(Effect.sleep(Duration.millis(afterMs)), { signal });
  if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
    throw Cause.squash(exit.cause);
  }
}

function stableClaudeQueryOptions(
  options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions,
): ClaudeAdapterV2.ClaudeAgentSdkQueryOptions {
  const stable = {
    model: options.model,
    tools: options.tools,
    permissionMode: options.permissionMode,
    ...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
    ...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
    ...(options.settings === undefined ? {} : { settings: options.settings }),
    ...(options.allowDangerouslySkipPermissions === true
      ? { allowDangerouslySkipPermissions: true }
      : {}),
    ...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
    ...(options.forkSession === true ? { forkSession: true } : {}),
  };
  return options.resume === undefined
    ? { ...stable, sessionId: options.sessionId }
    : { ...stable, resume: options.resume };
}

function makeClaudeQueryOpenFrame(
  input: Pick<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput, "options">,
): ClaudeQueryOpenFrame {
  return {
    type: "query.open",
    options: stableClaudeQueryOptions(input.options),
  };
}

function makeClaudePromptOfferFrame(message: SDKUserMessage): ClaudePromptOfferFrame {
  return {
    type: "prompt.offer",
    message,
  };
}

function makeClaudeSessionForkFrame(
  input: ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput,
  scenario: string,
): ClaudeSessionForkFrame {
  return {
    type: "session.fork",
    sessionId: input.sessionId,
    options: {
      ...(input.options.dir === undefined ? {} : { dir: sanitizedReplayCwd(scenario) }),
      ...(input.options.upToMessageId === undefined
        ? {}
        : { upToMessageId: input.options.upToMessageId }),
      ...(input.options.title === undefined ? {} : { title: input.options.title }),
    },
  };
}

function makeReplayQueryRunner(
  transcript: ClaudeAgentSdkReplayTranscript,
  replayOptions: { readonly replayGate?: ProviderReplayGate } = {},
): ClaudeQueryRunner {
  let cursor = 0;
  let failure: ClaudeAgentSdkReplayError | null = null;
  let cursorAdvanced = makeCursorSignal();
  const iteratorAbortControllers = new Set<AbortController>();

  const abortReplayIterators = () => {
    for (const abortController of iteratorAbortControllers) {
      abortController.abort();
    }
  };

  const fail = (error: ClaudeAgentSdkReplayError): never => {
    failure = error;
    abortReplayIterators();
    replayOptions.replayGate?.releaseAll();
    cursorAdvanced.resolve();
    throw error;
  };

  const throwIfFailed = () => {
    if (failure !== null) {
      throw failure;
    }
  };

  const advance = () => {
    cursor += 1;
    const signal = cursorAdvanced;
    cursorAdvanced = makeCursorSignal();
    signal.resolve();
  };

  async function* replayMessages(
    options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions,
    signal: AbortSignal,
  ): AsyncGenerator<SDKMessage, void> {
    while (true) {
      throwIfFailed();

      const entry = transcript.entries[cursor];
      if (entry === undefined) {
        return;
      }

      if (entry.type === "emit_inbound") {
        if (replayOptions.replayGate !== undefined) {
          await replayOptions.replayGate.beforeEmit(entry.label, signal);
          throwIfFailed();
          if (signal.aborted) {
            return;
          }
        }
        if (entry.afterMs !== undefined && entry.afterMs > 0) {
          await waitForReplayDelay(entry.afterMs, signal);
          throwIfFailed();
          if (signal.aborted) {
            return;
          }
        }
        if (isClaudePermissionRequestFrame(entry.frame)) {
          const request = entry.frame;
          const invokeCanUseTool = options.canUseTool;
          if (invokeCanUseTool === undefined) {
            const error = new ClaudeReplayUnexpectedOutboundError({
              scenario: transcript.scenario,
              cursor,
              expectedType: "permission.request",
              actual: request,
            });
            return fail(error);
          }
          advance();
          let result: PermissionResult | null;
          try {
            result = await invokeCanUseTool(
              request.toolName,
              request.input,
              permissionRequestOptionsFromFrame(request, signal),
            );
          } catch (cause) {
            throwIfFailed();
            if (signal.aborted) {
              return;
            }
            throw cause;
          }
          throwIfFailed();
          if (signal.aborted) {
            return;
          }
          if (result === null) {
            const error = new ClaudeReplayUnexpectedOutboundError({
              scenario: transcript.scenario,
              cursor,
              expectedType: "permission.response",
              actual: null,
            });
            return fail(error);
          }
          assertNextOutboundFrame(makeClaudePermissionResponseFrame(result));
          continue;
        }
        advance();
        yield sdkMessageFromReplayFrame(withReplayedPromptUuids(entry.frame));
        continue;
      }

      if (entry.type === "runtime_exit") {
        advance();
        if (entry.status === "success") {
          return;
        }
        fail(
          new ClaudeReplayRuntimeExitError({
            scenario: transcript.scenario,
            cursor: cursor - 1,
            status: entry.status,
            ...(entry.error === undefined ? {} : { error: entry.error }),
          }),
        );
      }

      if (entry.type === "expect_outbound") {
        await waitForCursorAdvance(cursorAdvanced.promise, signal);
        throwIfFailed();
        if (signal.aborted) {
          return;
        }
        continue;
      }
    }
  }

  const replayMessagesWithGateCleanup = (
    options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions,
  ): AsyncIterable<SDKMessage> => ({
    [Symbol.asyncIterator]: () => {
      const abortController = new AbortController();
      iteratorAbortControllers.add(abortController);
      const iterator = replayMessages(options, abortController.signal);
      return {
        next: async () => {
          try {
            const result = await iterator.next();
            if (result.done) {
              iteratorAbortControllers.delete(abortController);
            }
            return result;
          } catch (cause) {
            iteratorAbortControllers.delete(abortController);
            throw cause;
          }
        },
        return: async () => {
          abortController.abort();
          replayOptions.replayGate?.releaseAll();
          try {
            return await iterator.return();
          } finally {
            iteratorAbortControllers.delete(abortController);
          }
        },
      };
    },
  });

  // Prompt uuids differ on replay; rewrite inbound echoes and acknowledgements to match.
  const promptUuidReplacements = new Map<string, string>();
  const replayedPromptUuid = (value: string): string => promptUuidReplacements.get(value) ?? value;
  const withReplayedPromptUuids = (frame: unknown): unknown => {
    if (promptUuidReplacements.size === 0 || typeof frame !== "object" || frame === null) {
      return frame;
    }
    const uuid: unknown = Reflect.get(frame, "user_message_uuid");
    const uuids: unknown = Reflect.get(frame, "user_message_uuids");
    const commandUuid: unknown = Reflect.get(frame, "command_uuid");
    if (typeof uuid !== "string" && !Array.isArray(uuids) && typeof commandUuid !== "string") {
      return frame;
    }
    return {
      ...frame,
      ...(typeof commandUuid === "string" ? { command_uuid: replayedPromptUuid(commandUuid) } : {}),
      ...(typeof uuid === "string" ? { user_message_uuid: replayedPromptUuid(uuid) } : {}),
      ...(Array.isArray(uuids)
        ? {
            user_message_uuids: uuids.map((entry) =>
              typeof entry === "string" ? replayedPromptUuid(entry) : entry,
            ),
          }
        : {}),
    };
  };
  const promptOfferUuid = (frame: unknown): string | undefined => {
    if (
      typeof frame !== "object" ||
      frame === null ||
      Reflect.get(frame, "type") !== "prompt.offer"
    ) {
      return undefined;
    }
    const message: unknown = Reflect.get(frame, "message");
    const uuid: unknown =
      typeof message === "object" && message !== null ? Reflect.get(message, "uuid") : undefined;
    return typeof uuid === "string" ? uuid : undefined;
  };
  const withoutPromptOfferUuid = (frame: unknown): unknown => {
    if (promptOfferUuid(frame) === undefined || typeof frame !== "object" || frame === null) {
      return frame;
    }
    const message = Reflect.get(frame, "message") as Record<string, unknown>;
    const { uuid: _uuid, ...rest } = message;
    return { ...frame, message: rest };
  };

  const assertNextOutboundFrame = (actual: ClaudeOutboundFrame) => {
    if (failure !== null) {
      throw failure;
    }
    const entry = transcript.entries[cursor];
    if (entry === undefined) {
      return fail(
        new ClaudeReplayExhaustedError({
          scenario: transcript.scenario,
          cursor,
          actual,
        }),
      );
    }
    if (entry.type !== "expect_outbound") {
      return fail(
        new ClaudeReplayUnexpectedOutboundError({
          scenario: transcript.scenario,
          cursor,
          expectedType: entry.type,
          actual,
        }),
      );
    }

    const expected = entry.frame;
    const expectedUuid = promptOfferUuid(expected);
    const actualUuid = promptOfferUuid(actual);
    if (
      !sameFrame(withoutPromptOfferUuid(expected), withoutPromptOfferUuid(actual)) ||
      (expectedUuid !== undefined && actualUuid === undefined)
    ) {
      fail(
        new ClaudeReplayFrameMismatchError({
          scenario: transcript.scenario,
          cursor,
          ...(entry.label === undefined ? {} : { label: entry.label }),
          expected,
          actual,
        }),
      );
    }
    if (expectedUuid !== undefined && actualUuid !== undefined) {
      promptUuidReplacements.set(expectedUuid, actualUuid);
    }

    advance();
  };

  const assertNextReplyFrame = <Frame extends ClaudeSessionForkedFrame | ClaudeSubagentFoundFrame>(
    type: Frame["type"],
    isValid: (frame: object) => boolean,
  ): Frame => {
    const entry = transcript.entries[cursor];
    if (entry === undefined) {
      return fail(
        new ClaudeReplayExhaustedError({
          scenario: transcript.scenario,
          cursor,
          actual: { type },
        }),
      );
    }
    if (entry.type !== "emit_inbound") {
      return fail(
        new ClaudeReplayUnexpectedOutboundError({
          scenario: transcript.scenario,
          cursor,
          expectedType: entry.type,
          actual: { type },
        }),
      );
    }
    if (
      typeof entry.frame !== "object" ||
      entry.frame === null ||
      Reflect.get(entry.frame, "type") !== type ||
      !isValid(entry.frame)
    ) {
      return fail(
        new ClaudeReplayFrameMismatchError({
          scenario: transcript.scenario,
          cursor,
          expected: { type },
          actual: entry.frame,
        }),
      );
    }

    const frame = entry.frame as Frame;
    advance();
    return frame;
  };

  const replayEffect = (tryEffect: () => void) =>
    Effect.try({
      try: tryEffect,
      catch: (cause) => replayQueryRunnerError(transcript, cause),
    });

  return {
    open: (input) => {
      assertNextOutboundFrame(makeClaudeQueryOpenFrame(input));
      return {
        messages: Stream.fromAsyncIterable(replayMessagesWithGateCleanup(input.options), (cause) =>
          replayQueryRunnerError(transcript, cause),
        ),
        offer: (message) =>
          replayEffect(() => {
            assertNextOutboundFrame(makeClaudePromptOfferFrame(message));
          }),
        setModel: (model) =>
          replayEffect(() => {
            assertNextOutboundFrame({
              type: "query.set_model",
              model,
            });
          }),
        applyFlagSettings: (settings) =>
          replayEffect(() => {
            assertNextOutboundFrame({
              type: "query.apply_flag_settings",
              settings,
            });
          }),
        setPermissionMode: (mode) =>
          replayEffect(() => {
            assertNextOutboundFrame({
              type: "query.set_permission_mode",
              mode,
            });
          }),
        stopTask: (taskId) =>
          replayEffect(() => {
            assertNextOutboundFrame({ type: "query.stop_task", taskId });
          }),
        backgroundTasks: (toolUseId) =>
          replayEffect(() => {
            assertNextOutboundFrame({ type: "query.background_tasks", toolUseId });
          }).pipe(Effect.as(true)),
        // Recorded CLIs predate MCP Apps capabilities, so replays never reach these.
        mcpServerStatus: Effect.die("unexpected MCP server status in replay"),
        readMcpResource: () => Effect.die("unexpected MCP resource read in replay"),
        callMcpTool: () => Effect.die("unexpected MCP tool call in replay"),
        listPermissionRules: Effect.die("unexpected permission rules read in replay"),
        interrupt: replayEffect(() => {
          assertNextOutboundFrame({ type: "query.interrupt" });
        }),
        close: Effect.void,
      };
    },
    forkSession: (input) => {
      assertNextOutboundFrame(makeClaudeSessionForkFrame(input, transcript.scenario));
      return assertNextReplyFrame<ClaudeSessionForkedFrame>(
        "session.forked",
        (frame) => typeof Reflect.get(frame, "sessionId") === "string",
      );
    },
    subagentLaunchToolUseId: (input) => {
      assertNextOutboundFrame({
        type: "subagent.lookup",
        sessionId: input.sessionId,
        agentId: input.agentId,
      });
      return assertNextReplyFrame<ClaudeSubagentFoundFrame>("subagent.found", (frame) => {
        const toolUseId = Reflect.get(frame, "toolUseId");
        return toolUseId === null || typeof toolUseId === "string";
      }).toolUseId;
    },
    assertComplete: () => {
      if (failure !== null) {
        throw failure;
      }
      if (cursor !== transcript.entries.length) {
        replayOptions.replayGate?.releaseAll();
        throw new ClaudeReplayIncompleteError({
          scenario: transcript.scenario,
          cursor,
          remaining: transcript.entries.length - cursor,
        });
      }
    },
  };
}

function metadataFromTranscript(transcript: ProviderReplayTranscript): {
  readonly provider?: string;
  readonly protocol?: string;
  readonly scenario?: string;
} {
  return {
    provider: transcript.provider,
    protocol: transcript.protocol,
    scenario: transcript.scenario,
  };
}

function nativeSessionIdFor(transcript: ClaudeAgentSdkReplayTranscript): string {
  const metadataSessionId = transcript.metadata?.nativeSessionId;
  return typeof metadataSessionId === "string"
    ? metadataSessionId
    : "00000000-0000-4000-8000-000000000000";
}

const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError);
const isClaudeAgentSdkReplayError = Schema.is(ClaudeAgentSdkReplayError);

function replayQueryRunnerError(
  transcript: ClaudeAgentSdkReplayTranscript,
  cause: unknown,
): ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError {
  if (isClaudeAgentSdkQueryRunnerError(cause)) {
    return cause;
  }
  const replayCause = isClaudeAgentSdkReplayError(cause)
    ? cause
    : new ClaudeReplayDriverError({ scenario: transcript.scenario, cause });
  return new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
    cause: replayCause,
    method: `replay-scenario:${transcript.scenario}`,
  });
}

function replayQueryRunnerService(
  transcript: ClaudeAgentSdkReplayTranscript,
  queryRunner: ClaudeQueryRunner,
): ClaudeAdapterV2.ClaudeAgentSdkQueryRunner["Service"] {
  const replay = <A>(run: () => A) =>
    Effect.try({
      try: run,
      catch: (cause) => replayQueryRunnerError(transcript, cause),
    });
  return ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.of({
    allocateSessionId: Effect.succeed(nativeSessionIdFor(transcript)),
    open: (input) => replay(() => queryRunner.open(input)),
    forkSession: (input) => replay(() => queryRunner.forkSession(input)),
    subagentLaunchToolUseId: (input) => replay(() => queryRunner.subagentLaunchToolUseId(input)),
    assertComplete: replay(() => queryRunner.assertComplete()),
  });
}

function layerClaudeAgentSdkReplay(
  transcript: ClaudeAgentSdkReplayTranscript,
  options: {
    readonly replayGate?: ProviderReplayGate;
    readonly queryRunner?: ClaudeQueryRunner;
  } = {},
): Layer.Layer<ClaudeAdapterV2.ClaudeAgentSdkQueryRunner> {
  if (options.queryRunner !== undefined) {
    return Layer.succeed(
      ClaudeAdapterV2.ClaudeAgentSdkQueryRunner,
      replayQueryRunnerService(transcript, options.queryRunner),
    );
  }
  const queryRunner = makeReplayQueryRunner(transcript, options);
  return Layer.effect(
    ClaudeAdapterV2.ClaudeAgentSdkQueryRunner,
    Effect.gen(function* () {
      yield* Effect.addFinalizer(() =>
        Effect.sync(() => {
          queryRunner.assertComplete();
        }),
      );
      return replayQueryRunnerService(transcript, queryRunner);
    }),
  );
}

/** Replays write recorded Bash output to task_started files under a scenario-owned CLAUDE_CODE_TMPDIR. */
const writeReplayTaskOutputFiles = Effect.fn("ClaudeReplay.writeTaskOutputFiles")(function* (
  transcript: ClaudeAgentSdkReplayTranscript,
) {
  const fileSystem = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  const tmpRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-replay-tasks-" });
  const frames = transcript.entries.flatMap((entry) =>
    entry.type === "emit_inbound" && typeof entry.frame === "object" && entry.frame !== null
      ? [entry.frame as Record<string, unknown>]
      : [],
  );
  const outputByToolUseId = new Map<string, string>();
  for (const frame of frames) {
    const result = frame.tool_use_result as Record<string, unknown> | undefined;
    const content = (frame.message as { readonly content?: unknown } | undefined)?.content;
    if (typeof result?.stdout !== "string" || !Array.isArray(content)) continue;
    const toolResult = content.find(
      (block): block is { readonly tool_use_id: string } =>
        block?.type === "tool_result" && typeof block.tool_use_id === "string",
    );
    if (toolResult === undefined) continue;
    const stderr = typeof result.stderr === "string" ? result.stderr : "";
    outputByToolUseId.set(toolResult.tool_use_id, `${result.stdout}${stderr}`);
  }
  const root = claudeTaskOutputRoot(
    { CLAUDE_CODE_TMPDIR: tmpRoot },
    path,
    null,
    yield* HostProcess.Platform,
  );
  for (const frame of frames) {
    if (frame.type !== "system" || frame.subtype !== "task_started") continue;
    if (frame.task_type !== "local_bash" || frame.is_backgrounded !== false) continue;
    const output =
      typeof frame.tool_use_id === "string" ? outputByToolUseId.get(frame.tool_use_id) : undefined;
    if (root === undefined || output === undefined || typeof frame.session_id !== "string") {
      continue;
    }
    const tasks = path.join(root, "replay-project", frame.session_id, "tasks");
    yield* fileSystem.makeDirectory(tasks, { recursive: true });
    yield* fileSystem.writeFileString(path.join(tasks, `${String(frame.task_id)}.output`), output);
  }
  return tmpRoot;
});

function layerClaudeProviderAdapterRegistryReplay(
  transcript: ClaudeAgentSdkReplayTranscript,
  options: {
    readonly replayGate?: ProviderReplayGate;
    readonly queryRunner?: ClaudeQueryRunner;
  } = {},
) {
  const layerServerConfig = Layer.effect(
    ServerConfig.ServerConfig,
    makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
  ).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
  return Layer.unwrap(
    writeReplayTaskOutputFiles(transcript).pipe(
      Effect.orDie,
      Effect.map((tmpRoot) =>
        ProviderAdapterRegistry.layerFromAdaptersEffect(
          ClaudeAdapterV2.createClaudeAdapterV2(
            {
              instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
              displayName: undefined,
              environment: [{ name: "CLAUDE_CODE_TMPDIR", value: tmpRoot, sensitive: false }],
              enabled: true,
              config: DEFAULT_CLAUDE_SETTINGS,
            },
            {},
          ).pipe(Effect.map((adapter) => [adapter])),
        ),
      ),
      Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
    ),
  ).pipe(
    Layer.provide(
      Layer.mergeAll(
        layerClaudeAgentSdkReplay(transcript, options),
        IdAllocator.layer,
        NodeServices.layer,
        NodeCrypto.layer,
        layerServerConfig,
      ),
    ),
  );
}

function serializeReplayError(error: unknown, scenario?: string): unknown {
  return error instanceof Error
    ? {
        name: error.name,
        message:
          scenario === undefined
            ? error.message
            : sanitizeReplayText({ text: error.message, scenario }),
      }
    : error;
}

function permissionResultForRecording(input: {
  readonly decision: ProviderApprovalDecision;
  readonly toolInput: Record<string, unknown>;
  readonly toolUseID: string;
  readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
}): PermissionResult {
  if (input.decision === "accept" || input.decision === "acceptForSession") {
    return {
      behavior: "allow",
      updatedInput: input.toolInput,
      toolUseID: input.toolUseID,
      decisionClassification:
        input.decision === "acceptForSession" ? "user_permanent" : "user_temporary",
      ...(input.decision === "acceptForSession" && input.suggestions !== undefined
        ? { updatedPermissions: input.suggestions }
        : {}),
    };
  }
  return {
    behavior: "deny",
    message:
      input.decision === "cancel"
        ? "User cancelled tool execution."
        : "User declined tool execution.",
    toolUseID: input.toolUseID,
    decisionClassification: "user_reject",
    ...(input.decision === "cancel" ? { interrupt: true } : {}),
  };
}

function permissionRequestFrame(input: {
  readonly toolName: string;
  readonly toolInput: Record<string, unknown>;
  readonly callbackOptions: Parameters<CanUseTool>[2];
}): ClaudePermissionRequestFrame {
  const { callbackOptions } = input;
  return {
    type: "permission.request",
    toolName: input.toolName,
    input: input.toolInput,
    options: {
      ...(callbackOptions.suggestions === undefined
        ? {}
        : { suggestions: callbackOptions.suggestions }),
      ...(callbackOptions.blockedPath === undefined
        ? {}
        : { blockedPath: callbackOptions.blockedPath }),
      ...(callbackOptions.decisionReason === undefined
        ? {}
        : { decisionReason: callbackOptions.decisionReason }),
      ...(callbackOptions.title === undefined ? {} : { title: callbackOptions.title }),
      ...(callbackOptions.displayName === undefined
        ? {}
        : { displayName: callbackOptions.displayName }),
      ...(callbackOptions.description === undefined
        ? {}
        : { description: callbackOptions.description }),
      toolUseID: callbackOptions.toolUseID,
      ...(callbackOptions.agentID === undefined ? {} : { agentID: callbackOptions.agentID }),
    },
  };
}

function sanitizedReplayCwd(scenario: string): string {
  return `/tmp/claude-replay-${scenario}`;
}

function parentDirectory(input: string): string {
  const trimmed = input.replace(/\/+$/u, "");
  const lastSlash = trimmed.lastIndexOf("/");
  if (lastSlash <= 0) {
    return "/";
  }
  return trimmed.slice(0, lastSlash);
}

function sanitizeReplayText(input: { readonly text: string; readonly scenario: string }): string {
  const sanitizedCwd = sanitizedReplayCwd(input.scenario);
  const repoRoot = parentDirectory(parentDirectory(process.cwd()));
  return [repoRoot, process.cwd()]
    .toSorted((left, right) => right.length - left.length)
    .reduce((text, localPath) => text.replaceAll(localPath, sanitizedCwd), input.text);
}

function sanitizeSdkMessageForReplay(input: {
  readonly message: SDKMessage;
  readonly scenario: string;
}): SDKMessage {
  const { message } = input;
  if (message.type === "system" && message.subtype === "init") {
    return {
      type: "system",
      subtype: "init",
      ...(message.agents === undefined ? {} : { agents: [] }),
      apiKeySource: message.apiKeySource,
      ...(message.betas === undefined ? {} : { betas: message.betas }),
      claude_code_version: message.claude_code_version,
      cwd: sanitizedReplayCwd(input.scenario),
      tools: [],
      mcp_servers: [],
      model: message.model,
      permissionMode: message.permissionMode,
      slash_commands: [],
      output_style: message.output_style,
      skills: [],
      plugins: [],
      ...(message.fast_mode_state === undefined
        ? {}
        : { fast_mode_state: message.fast_mode_state }),
      uuid: message.uuid,
      session_id: message.session_id,
    };
  }
  // Recorded commands and skills are account configuration.
  if (message.type === "system" && message.subtype === "commands_changed") {
    return { ...message, commands: [] };
  }
  if (message.type === "rate_limit_event") {
    return {
      ...message,
      rate_limit_info: {
        status: message.rate_limit_info.status,
      },
    };
  }
  if (message.type === "result" && message.subtype !== "success" && message.errors.length > 0) {
    return {
      ...message,
      errors: message.errors.map((error) =>
        sanitizeReplayText({ text: error, scenario: input.scenario }),
      ),
    };
  }
  return message;
}

class RecordingMessageReader implements AsyncIterator<SDKMessage> {
  private pending: Promise<IteratorResult<SDKMessage>> | undefined;
  private readonly iterator: AsyncIterator<SDKMessage>;

  constructor(iterator: AsyncIterator<SDKMessage>) {
    this.iterator = iterator;
  }

  next(): Promise<IteratorResult<SDKMessage>> {
    const pending = this.pending ?? this.iterator.next();
    this.pending = undefined;
    return pending;
  }

  async peekWithin(ms: number): Promise<SDKMessage | undefined> {
    const pending = this.pending ?? this.iterator.next();
    this.pending = pending;
    return Promise.race([
      pending.then(
        (result) => (result.done === true ? undefined : result.value),
        () => undefined,
      ),
      Effect.runPromise(Effect.sleep(Duration.millis(ms))).then(() => undefined),
    ]);
  }
}

class RecordingPromptQueue implements AsyncIterable<SDKUserMessage> {
  private readonly pending: Array<IteratorResult<SDKUserMessage>> = [];
  private readonly waiters: Array<(result: IteratorResult<SDKUserMessage>) => void> = [];
  private closed = false;

  offer(message: SDKUserMessage): void {
    if (this.closed) {
      throw new Error("Cannot offer a prompt to a closed Claude recording queue.");
    }
    this.push({ done: false, value: message });
  }

  close(): void {
    if (this.closed) {
      return;
    }
    this.closed = true;
    this.push({ done: true, value: undefined });
  }

  async *[Symbol.asyncIterator](): AsyncIterator<SDKUserMessage> {
    while (true) {
      const next = await this.take();
      if (next.done === true) {
        return;
      }
      yield next.value;
    }
  }

  private push(result: IteratorResult<SDKUserMessage>): void {
    const waiter = this.waiters.shift();
    if (waiter === undefined) {
      this.pending.push(result);
      return;
    }
    waiter(result);
  }

  private take(): Promise<IteratorResult<SDKUserMessage>> {
    const next = this.pending.shift();
    if (next !== undefined) {
      return Promise.resolve(next);
    }
    return new Promise((resolve) => {
      this.waiters.push(resolve);
    });
  }
}

async function recordMessagesUntilTurnResult(input: {
  readonly iterator: AsyncIterator<SDKMessage>;
  readonly entries: Array<ProviderReplayEntry>;
  readonly scenario: string;
}): Promise<boolean> {
  while (true) {
    const next = await input.iterator.next();
    if (next.done === true) {
      return false;
    }
    const replayMessage = sanitizeSdkMessageForReplay({
      message: next.value,
      scenario: input.scenario,
    });
    input.entries.push({
      type: "emit_inbound",
      label: replayMessage.type,
      frame: replayMessage,
    });
    if (replayMessage.type === "result") {
      return true;
    }
  }
}

async function recordMessagesUntilTurnResultAndFinalize(input: {
  readonly iterator: AsyncIterator<SDKMessage>;
  readonly entries: Array<ProviderReplayEntry>;
  readonly scenario: string;
  readonly finalize: () => void;
}): Promise<boolean> {
  try {
    return await recordMessagesUntilTurnResult(input);
  } finally {
    input.finalize();
  }
}

async function recordMessagesUntilTurnResultWithCursor(input: {
  readonly iterator: AsyncIterator<SDKMessage>;
  readonly entries: Array<ProviderReplayEntry>;
  readonly scenario: string;
}): Promise<{
  readonly completed: boolean;
  readonly assistantMessageUuid: SDKAssistantMessage["uuid"] | null;
}> {
  let assistantMessageUuid: SDKAssistantMessage["uuid"] | null = null;
  while (true) {
    const next = await input.iterator.next();
    if (next.done === true) {
      return { completed: false, assistantMessageUuid };
    }
    const replayMessage = sanitizeSdkMessageForReplay({
      message: next.value,
      scenario: input.scenario,
    });
    input.entries.push({
      type: "emit_inbound",
      label: replayMessage.type,
      frame: replayMessage,
    });
    if (replayMessage.type === "assistant") {
      assistantMessageUuid = replayMessage.uuid;
    }
    if (replayMessage.type === "result") {
      return { completed: true, assistantMessageUuid };
    }
  }
}

function requireAssistantCursor(input: {
  readonly scenario: string;
  readonly promptIndex: number;
  readonly cursor: SDKAssistantMessage["uuid"] | null;
}): SDKAssistantMessage["uuid"] {
  if (input.cursor !== null) {
    return input.cursor;
  }
  throw new Error(
    `Claude replay scenario ${input.scenario} prompt ${input.promptIndex} completed without an SDKAssistantMessage.uuid cursor.`,
  );
}

async function recordMessagesUntilTurnResults(input: {
  readonly iterator: AsyncIterator<SDKMessage>;
  readonly entries: Array<ProviderReplayEntry>;
  readonly scenario: string;
  readonly resultCount: number;
}): Promise<boolean> {
  let seenResults = 0;
  while (true) {
    const next = await input.iterator.next();
    if (next.done === true) {
      return false;
    }
    const replayMessage = sanitizeSdkMessageForReplay({
      message: next.value,
      scenario: input.scenario,
    });
    input.entries.push({
      type: "emit_inbound",
      label: replayMessage.type,
      frame: replayMessage,
    });
    if (replayMessage.type === "result") {
      seenResults += 1;
      if (seenResults >= input.resultCount) {
        return true;
      }
    }
  }
}

async function recordMessagesUntilIteratorDone(input: {
  readonly iterator: AsyncIterator<SDKMessage>;
  readonly entries: Array<ProviderReplayEntry>;
  readonly scenario: string;
}): Promise<void> {
  while (true) {
    const next = await input.iterator.next();
    if (next.done === true) {
      return;
    }
    const replayMessage = sanitizeSdkMessageForReplay({
      message: next.value,
      scenario: input.scenario,
    });
    input.entries.push({
      type: "emit_inbound",
      label: replayMessage.type,
      frame: replayMessage,
    });
  }
}

const CLAUDE_RECORDING_WAKE_QUIET_MS = 5_000;

function isSystemInitFrame(message: SDKMessage | undefined): boolean {
  return message?.type === "system" && message.subtype === "init";
}

function isTaskNotificationOriginResultFrame(frame: unknown): boolean {
  if (typeof frame !== "object" || frame === null || Reflect.get(frame, "type") !== "result") {
    return false;
  }
  const origin: unknown = Reflect.get(frame, "origin");
  return (
    typeof origin === "object" &&
    origin !== null &&
    Reflect.get(origin, "kind") === "task-notification"
  );
}

function sdkMessageHasRootToolUse(message: SDKMessage): boolean {
  return (
    message.type === "assistant" &&
    message.parent_tool_use_id === null &&
    message.message.content.some((part) => part.type === "tool_use")
  );
}

async function recordMessagesUntilToolUse(input: {
  readonly iterator: AsyncIterator<SDKMessage>;
  readonly entries: Array<ProviderReplayEntry>;
  readonly scenario: string;
  readonly toolUseCount: number;
}): Promise<void> {
  let toolUses = 0;
  while (true) {
    const next = await input.iterator.next();
    if (next.done === true) {
      throw new Error(`Claude query ended before ${input.scenario} started a tool use.`);
    }
    const replayMessage = sanitizeSdkMessageForReplay({
      message: next.value,
      scenario: input.scenario,
    });
    input.entries.push({
      type: "emit_inbound",
      label: replayMessage.type,
      frame: replayMessage,
    });
    if (replayMessage.type === "result") {
      throw new Error(`Claude query completed before ${input.scenario} started a tool use.`);
    }
    if (sdkMessageHasRootToolUse(replayMessage)) {
      toolUses += 1;
      if (toolUses >= input.toolUseCount) {
        return;
      }
    }
  }
}

// The SDK may lack a platform executable. Prefer installed Claude only when directly spawnable,
// including Windows shims resolved to package entries.
const resolveClaudeRecordingExecutablePath = Effect.fn("resolveClaudeRecordingExecutablePath")(
  function* (environment: NodeJS.ProcessEnv) {
    const resolveExecutable = yield* SpawnExecutableResolution;
    const platform = yield* HostProcess.Platform;
    const resolved = resolveExecutable("claude", platform, environment);
    if (resolved === undefined) {
      return undefined;
    }
    const executablePath = yield* resolveClaudeSdkExecutablePath(resolved, environment);
    if (platform === "win32" && isWindowsClaudeLauncherShimPath(executablePath)) {
      return undefined;
    }
    return executablePath;
  },
);

async function openRecordingQuery(input: Parameters<typeof query>[0]) {
  const executablePath = await Effect.runPromise(resolveClaudeRecordingExecutablePath(process.env));
  return query({
    ...input,
    options: {
      ...input.options,
      ...(executablePath === undefined ? {} : { pathToClaudeCodeExecutable: executablePath }),
    },
  });
}

async function recordClaudeStreamingQuery(input: {
  readonly scenario: string;
  readonly prompts: ReadonlyArray<string>;
  readonly modelSelection: ModelSelection;
  readonly cwd: string;
  readonly sessionId: string;
  readonly entries: Array<ProviderReplayEntry>;
  readonly enableTools?: boolean;
  readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools;
  readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"];
  readonly allowedTools?: ReadonlyArray<string>;
  readonly disallowedTools?: ReadonlyArray<string>;
  readonly allowDangerouslySkipPermissions?: boolean;
  readonly enablePermissionCallback?: boolean;
  readonly permissionDecision?: ProviderApprovalDecision;
  readonly backgroundWakeCounts?: ReadonlyArray<number>;
  readonly offerNextPromptImmediately?: boolean;
}): Promise<void> {
  const promptQueue = new RecordingPromptQueue();
  const canUseTool: CanUseTool | undefined =
    input.enablePermissionCallback === true
      ? async (toolName, toolInput, callbackOptions) => {
          const requestFrame = permissionRequestFrame({
            toolName,
            toolInput,
            callbackOptions,
          });
          input.entries.push({
            type: "emit_inbound",
            label: `permission.request:${toolName}`,
            frame: requestFrame,
          });
          const result = permissionResultForRecording({
            decision: input.permissionDecision ?? "accept",
            toolInput,
            toolUseID: callbackOptions.toolUseID,
            ...(callbackOptions.suggestions === undefined
              ? {}
              : { suggestions: callbackOptions.suggestions }),
          });
          input.entries.push({
            type: "expect_outbound",
            label: `permission.response:${toolName}`,
            frame: makeClaudePermissionResponseFrame(result),
          });
          return result;
        }
      : undefined;
  const options = ClaudeAdapterV2.makeClaudeQueryOptions({
    modelSelection: input.modelSelection,
    nativeThreadId: input.sessionId,
    resume: false,
    cwd: input.cwd,
    ...(input.enableTools === true
      ? {
          tools: input.tools ?? { type: "preset", preset: "claude_code" },
          permissionMode: input.permissionMode ?? "default",
          ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
          ...(input.disallowedTools === undefined
            ? {}
            : { disallowedTools: input.disallowedTools }),
          ...(input.allowDangerouslySkipPermissions === true
            ? { allowDangerouslySkipPermissions: true }
            : {}),
          ...(canUseTool === undefined ? {} : { canUseTool }),
        }
      : {}),
  });
  input.entries.push({
    type: "expect_outbound",
    label: "query.open",
    frame: makeClaudeQueryOpenFrame({ options }),
  });
  const queryRuntime = await openRecordingQuery({
    prompt: promptQueue,
    options,
  });
  const iterator = new RecordingMessageReader(queryRuntime[Symbol.asyncIterator]());
  let wakeNumber = 0;
  const recordTurn = async (promptNumber: number): Promise<"prompt" | "wake"> => {
    const completed = await recordMessagesUntilTurnResult({
      iterator,
      entries: input.entries,
      scenario: input.scenario,
    });
    if (!completed) {
      throw new Error(
        `Claude streaming query ended before prompt ${promptNumber} and its background wakes completed.`,
      );
    }
    const resultEntry = input.entries.at(-1);
    const resultFrame = resultEntry?.type === "emit_inbound" ? resultEntry.frame : undefined;
    if (!isTaskNotificationOriginResultFrame(resultFrame)) {
      return "prompt";
    }
    wakeNumber += 1;
    input.entries[input.entries.length - 1] = {
      type: "emit_inbound",
      label: claudeBackgroundWakeResultLabel(wakeNumber),
      frame: resultFrame,
    };
    return "wake";
  };
  try {
    for (const [index, prompt] of input.prompts.entries()) {
      const message = ClaudeAdapterV2.makeClaudeUserMessage({
        text: prompt,
        uuid: await Effect.runPromise(
          SecureRandom.SecureRandom.pipe(
            Effect.flatMap((random) => random.uuidV4()),
            Effect.filterOrFail(ClaudeAdapterV2.isClaudePromptUuid),
            Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
          ),
        ),
      });
      input.entries.push({
        type: "expect_outbound",
        label: `prompt.offer:${index + 1}`,
        frame: makeClaudePromptOfferFrame(message),
      });
      promptQueue.offer(message);
      // Wake turns can precede the prompt turn; identify results by origin.
      let promptSettled = false;
      let wakes = 0;
      const expectedWakes = input.backgroundWakeCounts?.[index] ?? 0;
      while (!promptSettled || wakes < expectedWakes) {
        if ((await recordTurn(index + 1)) === "prompt") {
          promptSettled = true;
        } else {
          wakes += 1;
        }
      }
      if (input.backgroundWakeCounts !== undefined && input.offerNextPromptImmediately !== true) {
        // system:init opens each turn; leave ongoing subagent frames for the next recording.
        while (isSystemInitFrame(await iterator.peekWithin(CLAUDE_RECORDING_WAKE_QUIET_MS))) {
          await recordTurn(index + 1);
        }
      }
    }
    promptQueue.close();
    queryRuntime.close();
    input.entries.push({
      type: "runtime_exit",
      status: "success",
    });
  } catch (error) {
    promptQueue.close();
    queryRuntime.close();
    input.entries.push({
      type: "runtime_exit",
      status: "error",
      error: serializeReplayError(error, input.scenario),
    });
    throw error;
  }
}

async function recordClaudeActiveSteeringQuery(input: {
  readonly scenario: string;
  readonly prompts: ReadonlyArray<string>;
  readonly modelSelection: ModelSelection;
  readonly cwd: string;
  readonly sessionId: string;
  readonly entries: Array<ProviderReplayEntry>;
  readonly enableTools?: boolean;
  readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools;
  readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"];
  readonly allowedTools?: ReadonlyArray<string>;
  readonly disallowedTools?: ReadonlyArray<string>;
  readonly allowDangerouslySkipPermissions?: boolean;
  readonly enablePermissionCallback?: boolean;
  readonly permissionDecision?: ProviderApprovalDecision;
}): Promise<void> {
  if (input.prompts.length < 2) {
    throw new Error("Claude active steering replay recording requires at least two prompts.");
  }

  const promptQueue = new RecordingPromptQueue();
  const offerPrompt = (index: number, priority?: SDKUserMessage["priority"]) => {
    const message = ClaudeAdapterV2.makeClaudeUserMessage({
      text: input.prompts[index]!,
      ...(priority === undefined ? {} : { priority }),
    });
    input.entries.push({
      type: "expect_outbound",
      label: `prompt.offer:${index + 1}`,
      frame: makeClaudePromptOfferFrame(message),
    });
    promptQueue.offer(message);
  };
  const offerSteeringPrompts = () => {
    for (let index = 1; index < input.prompts.length; index += 1) {
      offerPrompt(index, "now");
    }
  };

  const canUseTool: CanUseTool | undefined =
    input.enablePermissionCallback === true
      ? async (toolName, toolInput, callbackOptions) => {
          const requestFrame = permissionRequestFrame({
            toolName,
            toolInput,
            callbackOptions,
          });
          input.entries.push({
            type: "emit_inbound",
            label: `permission.request:${toolName}`,
            frame: requestFrame,
          });
          const result = permissionResultForRecording({
            decision: input.permissionDecision ?? "accept",
            toolInput,
            toolUseID: callbackOptions.toolUseID,
            ...(callbackOptions.suggestions === undefined
              ? {}
              : { suggestions: callbackOptions.suggestions }),
          });
          input.entries.push({
            type: "expect_outbound",
            label: `permission.response:${toolName}`,
            frame: makeClaudePermissionResponseFrame(result),
          });
          return result;
        }
      : undefined;
  const options = ClaudeAdapterV2.makeClaudeQueryOptions({
    modelSelection: input.modelSelection,
    nativeThreadId: input.sessionId,
    resume: false,
    cwd: input.cwd,
    ...(input.enableTools === true
      ? {
          tools: input.tools ?? { type: "preset", preset: "claude_code" },
          permissionMode: input.permissionMode ?? "default",
          ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
          ...(input.disallowedTools === undefined
            ? {}
            : { disallowedTools: input.disallowedTools }),
          ...(input.allowDangerouslySkipPermissions === true
            ? { allowDangerouslySkipPermissions: true }
            : {}),
          ...(canUseTool === undefined ? {} : { canUseTool }),
        }
      : {}),
  });
  input.entries.push({
    type: "expect_outbound",
    label: "query.open",
    frame: makeClaudeQueryOpenFrame({ options }),
  });
  const queryRuntime = await openRecordingQuery({
    prompt: promptQueue,
    options,
  });
  const iterator = queryRuntime[Symbol.asyncIterator]();
  try {
    offerPrompt(0);
    offerSteeringPrompts();
    const completed = await recordMessagesUntilTurnResults({
      iterator,
      entries: input.entries,
      scenario: input.scenario,
      resultCount: input.prompts.length,
    });
    if (!completed) {
      throw new Error("Claude active steering query ended before the turn completed.");
    }
    promptQueue.close();
    queryRuntime.close();
    input.entries.push({
      type: "runtime_exit",
      status: "success",
    });
  } catch (error) {
    promptQueue.close();
    queryRuntime.close();
    input.entries.push({
      type: "runtime_exit",
      status: "error",
      error: serializeReplayError(error, input.scenario),
    });
    throw error;
  }
}

async function recordClaudeRestartingQueries(input: {
  readonly scenario: string;
  readonly prompts: ReadonlyArray<string>;
  readonly modelSelection: ModelSelection;
  readonly cwd: string;
  readonly sessionId: string;
  readonly entries: Array<ProviderReplayEntry>;
  readonly enableTools?: boolean;
  readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools;
  readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"];
  readonly allowedTools?: ReadonlyArray<string>;
  readonly disallowedTools?: ReadonlyArray<string>;
  readonly allowDangerouslySkipPermissions?: boolean;
}): Promise<void> {
  for (const [index, prompt] of input.prompts.entries()) {
    const promptQueue = new RecordingPromptQueue();
    const options = ClaudeAdapterV2.makeClaudeQueryOptions({
      modelSelection: input.modelSelection,
      nativeThreadId: input.sessionId,
      resume: index > 0,
      cwd: input.cwd,
      ...(input.enableTools === true
        ? {
            tools: input.tools ?? { type: "preset", preset: "claude_code" },
            permissionMode: input.permissionMode ?? "default",
            ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
            ...(input.disallowedTools === undefined
              ? {}
              : { disallowedTools: input.disallowedTools }),
            ...(input.allowDangerouslySkipPermissions === true
              ? { allowDangerouslySkipPermissions: true }
              : {}),
          }
        : {}),
    });

    input.entries.push({
      type: "expect_outbound",
      label: `query.open:${index + 1}`,
      frame: makeClaudeQueryOpenFrame({ options }),
    });
    const message = ClaudeAdapterV2.makeClaudeUserMessage({ text: prompt });
    input.entries.push({
      type: "expect_outbound",
      label: `prompt.offer:${index + 1}`,
      frame: makeClaudePromptOfferFrame(message),
    });

    try {
      const queryRuntime = await openRecordingQuery({
        prompt: promptQueue,
        options,
      });
      promptQueue.offer(message);
      promptQueue.close();
      const iterator = queryRuntime[Symbol.asyncIterator]();
      for (;;) {
        const next = await iterator.next();
        if (next.done === true) {
          break;
        }
        const replayMessage = sanitizeSdkMessageForReplay({
          message: next.value,
          scenario: input.scenario,
        });
        input.entries.push({
          type: "emit_inbound",
          label: replayMessage.type,
          frame: replayMessage,
        });
      }
      input.entries.push({
        type: "runtime_exit",
        status: "success",
      });
    } catch (error) {
      promptQueue.close();
      input.entries.push({
        type: "runtime_exit",
        status: "error",
        error: serializeReplayError(error, input.scenario),
      });
      throw error;
    }
  }
}

async function recordClaudeResumeAtCursorQuery(input: {
  readonly scenario: string;
  readonly prompts: ReadonlyArray<string>;
  readonly modelSelection: ModelSelection;
  readonly cwd: string;
  readonly sessionId: string;
  readonly entries: Array<ProviderReplayEntry>;
  readonly metadata: Record<string, unknown>;
  readonly enableTools?: boolean;
  readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools;
  readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"];
  readonly allowedTools?: ReadonlyArray<string>;
  readonly disallowedTools?: ReadonlyArray<string>;
  readonly allowDangerouslySkipPermissions?: boolean;
}): Promise<void> {
  if (input.prompts.length !== 3) {
    throw new Error(
      `Claude resume-at-cursor replay scenario ${input.scenario} requires exactly three prompts.`,
    );
  }

  const sourcePromptQueue = new RecordingPromptQueue();
  const sourceOptions = ClaudeAdapterV2.makeClaudeQueryOptions({
    modelSelection: input.modelSelection,
    nativeThreadId: input.sessionId,
    resume: false,
    cwd: input.cwd,
    ...(input.enableTools === true
      ? {
          tools: input.tools ?? { type: "preset", preset: "claude_code" },
          permissionMode: input.permissionMode ?? "default",
          ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
          ...(input.disallowedTools === undefined
            ? {}
            : { disallowedTools: input.disallowedTools }),
          ...(input.allowDangerouslySkipPermissions === true
            ? { allowDangerouslySkipPermissions: true }
            : {}),
        }
      : {}),
  });

  input.entries.push({
    type: "expect_outbound",
    label: "query.open:source",
    frame: makeClaudeQueryOpenFrame({ options: sourceOptions }),
  });
  const sourceRuntime = await openRecordingQuery({
    prompt: sourcePromptQueue,
    options: sourceOptions,
  });
  const sourceIterator = sourceRuntime[Symbol.asyncIterator]();

  try {
    const sourceCursors: Array<SDKAssistantMessage["uuid"]> = [];
    for (const [index, prompt] of input.prompts.slice(0, 2).entries()) {
      const message = ClaudeAdapterV2.makeClaudeUserMessage({ text: prompt });
      input.entries.push({
        type: "expect_outbound",
        label: `prompt.offer:${index + 1}`,
        frame: makeClaudePromptOfferFrame(message),
      });
      sourcePromptQueue.offer(message);
      const result = await recordMessagesUntilTurnResultWithCursor({
        iterator: sourceIterator,
        entries: input.entries,
        scenario: input.scenario,
      });
      if (!result.completed) {
        throw new Error(`Claude source query ended before prompt ${index + 1} completed.`);
      }
      sourceCursors.push(
        requireAssistantCursor({
          scenario: input.scenario,
          promptIndex: index + 1,
          cursor: result.assistantMessageUuid,
        }),
      );
    }
    sourcePromptQueue.close();
    sourceRuntime.close();
    input.entries.push({
      type: "runtime_exit",
      status: "success",
    });

    const resumeSessionAt = sourceCursors[0]!;
    input.metadata.resumeSessionAt = resumeSessionAt;
    input.metadata.sourceAssistantMessageUuids = sourceCursors;

    const resumedPromptQueue = new RecordingPromptQueue();
    const resumedOptions = {
      ...ClaudeAdapterV2.makeClaudeQueryOptions({
        modelSelection: input.modelSelection,
        nativeThreadId: input.sessionId,
        resume: true,
        cwd: input.cwd,
        ...(input.enableTools === true
          ? {
              tools: input.tools ?? { type: "preset", preset: "claude_code" },
              permissionMode: input.permissionMode ?? "default",
              ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
              ...(input.disallowedTools === undefined
                ? {}