diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 1c7b48ab2c..3906ec0cec 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -12,6 +12,8 @@ import * as EffectAcpAgent from "effect-acp/agent"; import * as AcpError from "effect-acp/errors"; import type * as AcpSchema from "effect-acp/schema"; +import { beginAcpMockPrompt } from "./acpMockCancellationState.ts"; + const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH; const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH; const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1"; @@ -567,6 +569,7 @@ const program = Effect.gen(function* () { yield* agent.handlePrompt((request) => Effect.gen(function* () { const requestedSessionId = String(request.sessionId ?? sessionId); + beginAcpMockPrompt(cancelledSessions, requestedSessionId); promptCount += 1; if (residualCallbackTriggerPath !== undefined) { diff --git a/apps/server/scripts/acpMockCancellationState.test.ts b/apps/server/scripts/acpMockCancellationState.test.ts new file mode 100644 index 0000000000..98ce4f9a13 --- /dev/null +++ b/apps/server/scripts/acpMockCancellationState.test.ts @@ -0,0 +1,12 @@ +import { assert, it } from "@effect/vitest"; + +import { beginAcpMockPrompt } from "./acpMockCancellationState.ts"; + +it("does not carry an idle cancellation into the next prompt", () => { + const cancelledSessions = new Set(["session:cancelled-while-idle", "session:other"]); + + beginAcpMockPrompt(cancelledSessions, "session:cancelled-while-idle"); + + assert.isFalse(cancelledSessions.has("session:cancelled-while-idle")); + assert.isTrue(cancelledSessions.has("session:other")); +}); diff --git a/apps/server/scripts/acpMockCancellationState.ts b/apps/server/scripts/acpMockCancellationState.ts new file mode 100644 index 0000000000..2b141e9248 --- /dev/null +++ b/apps/server/scripts/acpMockCancellationState.ts @@ -0,0 +1,3 @@ +export function beginAcpMockPrompt(cancelledSessions: Set, sessionId: string): void { + cancelledSessions.delete(sessionId); +} diff --git a/apps/server/scripts/claudeReplayRecordingConfig.test.ts b/apps/server/scripts/claudeReplayRecordingConfig.test.ts new file mode 100644 index 0000000000..4df53b9fa2 --- /dev/null +++ b/apps/server/scripts/claudeReplayRecordingConfig.test.ts @@ -0,0 +1,43 @@ +import { assert, it } from "@effect/vitest"; + +import { validateClaudeReplayRecordingSelection } from "./claudeReplayRecordingConfig.ts"; + +it("rejects a query mode that is incompatible with the selected scenario", () => { + assert.throws( + () => + validateClaudeReplayRecordingSelection({ + scenario: "simple", + configuredQueryMode: "streaming", + selectedQueryMode: "fork_session_siblings", + configuredPromptCount: 1, + selectedPromptCount: 1, + }), + "Select a scenario configured for the requested query mode", + ); +}); + +it("rejects prompt overrides that do not preserve the scenario shape", () => { + assert.throws( + () => + validateClaudeReplayRecordingSelection({ + scenario: "thread_fork_native_siblings", + configuredQueryMode: "fork_session_siblings", + selectedQueryMode: "fork_session_siblings", + configuredPromptCount: 3, + selectedPromptCount: 1, + }), + "requires exactly 3 prompt(s)", + ); +}); + +it("accepts the configured scenario mode and prompt shape", () => { + assert.doesNotThrow(() => + validateClaudeReplayRecordingSelection({ + scenario: "thread_fork_native_siblings", + configuredQueryMode: "fork_session_siblings", + selectedQueryMode: "fork_session_siblings", + configuredPromptCount: 3, + selectedPromptCount: 3, + }), + ); +}); diff --git a/apps/server/scripts/claudeReplayRecordingConfig.ts b/apps/server/scripts/claudeReplayRecordingConfig.ts new file mode 100644 index 0000000000..5d5baf332a --- /dev/null +++ b/apps/server/scripts/claudeReplayRecordingConfig.ts @@ -0,0 +1,32 @@ +export type ClaudeRecordingQueryMode = + | "streaming" + | "restart" + | "resume_at_cursor" + | "fork_session" + | "fork_session_prior_turn" + | "fork_session_continue" + | "fork_session_siblings" + | "fork_session_merge_back" + | "fork_session_merge_back_siblings" + | "active_steering" + | "interrupt" + | "interrupt_restart"; + +export function validateClaudeReplayRecordingSelection(input: { + readonly scenario: string; + readonly configuredQueryMode: ClaudeRecordingQueryMode; + readonly selectedQueryMode: ClaudeRecordingQueryMode; + readonly configuredPromptCount: number; + readonly selectedPromptCount: number; +}): void { + if (input.selectedQueryMode !== input.configuredQueryMode) { + throw new Error( + `Claude replay fixture '${input.scenario}' uses query mode '${input.configuredQueryMode}', not '${input.selectedQueryMode}'. Select a scenario configured for the requested query mode.`, + ); + } + if (input.selectedPromptCount !== input.configuredPromptCount) { + throw new Error( + `Claude replay fixture '${input.scenario}' requires exactly ${input.configuredPromptCount} prompt(s) for query mode '${input.configuredQueryMode}', but received ${input.selectedPromptCount}.`, + ); + } +} diff --git a/apps/server/scripts/cursorReplayRecordingWorkspace.test.ts b/apps/server/scripts/cursorReplayRecordingWorkspace.test.ts new file mode 100644 index 0000000000..5c8ad5fed7 --- /dev/null +++ b/apps/server/scripts/cursorReplayRecordingWorkspace.test.ts @@ -0,0 +1,35 @@ +import { assert, it } from "@effect/vitest"; + +import { + cursorReplayPromptsForWorkspace, + shouldSeedCursorReplayWorkspace, +} from "./cursorReplayRecordingWorkspace.ts"; + +it("points the read-only prompt at the unique recording workspace", () => { + assert.deepEqual( + cursorReplayPromptsForWorkspace({ + scenario: "tool_call_read_only", + configuredPrompts: ["stale global path"], + packageJsonPath: "/tmp/t3-cursor-owned-abc123/package.json", + tsconfigPath: "/tmp/t3-cursor-owned-abc123/tsconfig.json", + }), + [ + "Read /tmp/t3-cursor-owned-abc123/package.json and /tmp/t3-cursor-owned-abc123/tsconfig.json, then answer exactly: read only tool fixture complete", + ], + ); +}); + +it("never seeds files into an externally supplied workspace", () => { + assert.isFalse( + shouldSeedCursorReplayWorkspace({ + scenario: "tool_call_read_only", + owned: false, + }), + ); + assert.isTrue( + shouldSeedCursorReplayWorkspace({ + scenario: "tool_call_read_only", + owned: true, + }), + ); +}); diff --git a/apps/server/scripts/cursorReplayRecordingWorkspace.ts b/apps/server/scripts/cursorReplayRecordingWorkspace.ts new file mode 100644 index 0000000000..ba4b5a0e37 --- /dev/null +++ b/apps/server/scripts/cursorReplayRecordingWorkspace.ts @@ -0,0 +1,23 @@ +const SEEDED_CURSOR_REPLAY_SCENARIOS = new Set(["subagent", "tool_call_read_only", "todo_list"]); + +export function cursorReplayPromptsForWorkspace(input: { + readonly scenario: string; + readonly configuredPrompts: ReadonlyArray; + readonly packageJsonPath: string; + readonly tsconfigPath: string; +}): ReadonlyArray { + if (input.scenario !== "tool_call_read_only") { + return input.configuredPrompts; + } + + return [ + `Read ${input.packageJsonPath} and ${input.tsconfigPath}, then answer exactly: read only tool fixture complete`, + ]; +} + +export function shouldSeedCursorReplayWorkspace(input: { + readonly scenario: string; + readonly owned: boolean; +}): boolean { + return input.owned && SEEDED_CURSOR_REPLAY_SCENARIOS.has(input.scenario); +} diff --git a/apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts b/apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts index 77f9e88d2a..0aff87a35c 100644 --- a/apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts +++ b/apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts @@ -59,6 +59,10 @@ import { WORKSPACE_NEVER_POLICY, WEB_SEARCH_PROMPT, } from "../src/orchestration-v2/testkit/fixtures/shared.ts"; +import { + validateClaudeReplayRecordingSelection, + type ClaudeRecordingQueryMode, +} from "./claudeReplayRecordingConfig.ts"; const CLAUDE_RECORDINGS = { simple: { @@ -229,20 +233,6 @@ function readArgValue(name: string): string | undefined { return index >= 0 ? args[index + 1] : undefined; } -type ClaudeRecordingQueryMode = - | "streaming" - | "restart" - | "resume_at_cursor" - | "fork_session" - | "fork_session_prior_turn" - | "fork_session_continue" - | "fork_session_siblings" - | "fork_session_merge_back" - | "fork_session_merge_back_siblings" - | "active_steering" - | "interrupt" - | "interrupt_restart"; - function selectedQueryMode(defaultMode: ClaudeRecordingQueryMode): ClaudeRecordingQueryMode { const raw = readArgValue("--query-mode") ?? process.env.T3_CLAUDE_REPLAY_QUERY_MODE; if (raw === undefined) { @@ -327,6 +317,16 @@ function selectedPrompts(): ReadonlyArray { return recording.prompts; } +const prompts = selectedPrompts(); +const queryMode = selectedQueryMode(recording.queryMode); +validateClaudeReplayRecordingSelection({ + scenario, + configuredQueryMode: recording.queryMode, + selectedQueryMode: queryMode, + configuredPromptCount: recording.prompts.length, + selectedPromptCount: prompts.length, +}); + function runtimePolicyForRecording(input: { readonly cwd: string; readonly override?: RuntimePolicyV2Override; @@ -400,7 +400,7 @@ try { const transcript = await recordClaudeAgentSdkReplayTranscript({ scenario, - prompts: selectedPrompts(), + prompts, modelSelection: { ...CLAUDE_MODEL_SELECTION, model: process.env.T3_CLAUDE_REPLAY_MODEL ?? CLAUDE_MODEL_SELECTION.model, @@ -409,7 +409,7 @@ try { ...(process.env.T3_CLAUDE_REPLAY_SESSION_ID === undefined ? {} : { sessionId: process.env.T3_CLAUDE_REPLAY_SESSION_ID }), - queryMode: selectedQueryMode(recording.queryMode), + queryMode, ...("enableTools" in recording && recording.enableTools === true ? { enableTools: true } : {}), ...(queryPolicy.tools === undefined ? {} : { tools: queryPolicy.tools }), permissionMode: queryPolicy.permissionMode, diff --git a/apps/server/scripts/record-codex-app-server-replay-fixture.ts b/apps/server/scripts/record-codex-app-server-replay-fixture.ts index 026703d111..e0f4105ab4 100644 --- a/apps/server/scripts/record-codex-app-server-replay-fixture.ts +++ b/apps/server/scripts/record-codex-app-server-replay-fixture.ts @@ -51,6 +51,7 @@ import { TURN_INTERRUPT_MID_TOOL_PROMPT, TURN_INTERRUPT_PROMPT, } from "../src/orchestration-v2/testkit/fixtures/shared.ts"; +import { makeReplayRecorderDeferredRegistry } from "./replayRecorderDeferredRegistry.ts"; const CODEX_REPLAY_PLAN_MODE_DEVELOPER_INSTRUCTIONS = process.env.T3_CODEX_REPLAY_PLAN_DEVELOPER_INSTRUCTIONS ?? @@ -169,11 +170,11 @@ function readArgValues(name: string): ReadonlyArray { return args.flatMap((arg, index) => (arg === name && args[index + 1] ? [args[index + 1]!] : [])); } -function defaultTranscriptPath(scenario: ReplayScenario): string { +function defaultTranscriptUrl(scenario: ReplayScenario): URL { return new URL( `../src/orchestration-v2/testkit/fixtures/${scenario.name}/codex_transcript.ndjson`, import.meta.url, - ).pathname; + ); } function isRecord(value: unknown): value is Record { @@ -1158,45 +1159,16 @@ function runReplaySession({ readonly recorder: Recorder; }) { return Effect.gen(function* () { - const startedTurns = new Map>(); - const completedTurns = new Map>(); - const startedCommandExecutions = new Map>(); + const startedTurns = yield* makeReplayRecorderDeferredRegistry(); + const completedTurns = yield* makeReplayRecorderDeferredRegistry(); + const startedCommandExecutions = yield* makeReplayRecorderDeferredRegistry(); let approvalGate: Deferred.Deferred | undefined; - const getStarted = (turnId: string) => { - const existing = startedTurns.get(turnId); - if (existing) { - return Effect.succeed(existing); - } - return Deferred.make().pipe( - Effect.tap((deferred) => Effect.sync(() => startedTurns.set(turnId, deferred))), - ); - }; - const getCompletion = (turnId: string) => { - const existing = completedTurns.get(turnId); - if (existing) { - return Effect.succeed(existing); - } - return Deferred.make().pipe( - Effect.tap((deferred) => Effect.sync(() => completedTurns.set(turnId, deferred))), - ); - }; - const getCommandExecutionStarted = (turnId: string) => { - const existing = startedCommandExecutions.get(turnId); - if (existing) { - return Effect.succeed(existing); - } - return Deferred.make().pipe( - Effect.tap((deferred) => Effect.sync(() => startedCommandExecutions.set(turnId, deferred))), - ); - }; - const startTurn = (turnId: string) => - getStarted(turnId).pipe(Effect.flatMap((deferred) => Deferred.succeed(deferred, void 0))); - const completeTurn = (turnId: string) => - getCompletion(turnId).pipe(Effect.flatMap((deferred) => Deferred.succeed(deferred, void 0))); - const startCommandExecution = (turnId: string) => - getCommandExecutionStarted(turnId).pipe( - Effect.flatMap((deferred) => Deferred.succeed(deferred, void 0)), - ); + const getStarted = startedTurns.getOrCreate; + const getCompletion = completedTurns.getOrCreate; + const getCommandExecutionStarted = startedCommandExecutions.getOrCreate; + const startTurn = startedTurns.succeed; + const completeTurn = completedTurns.succeed; + const startCommandExecution = startedCommandExecutions.succeed; const beforeApprovalResponse = () => approvalGate ? Deferred.await(approvalGate) : Effect.void; @@ -1415,11 +1387,13 @@ const program = Effect.gen(function* () { yield* Effect.forEach( selected, (scenario) => - runScenario({ - scenario, - outPath: - singleOutPath ?? - (outDir ? path.join(outDir, scenario.fileName) : defaultTranscriptPath(scenario)), + Effect.gen(function* () { + const defaultOutPath = yield* path.fromFileUrl(defaultTranscriptUrl(scenario)); + yield* runScenario({ + scenario, + outPath: + singleOutPath ?? (outDir ? path.join(outDir, scenario.fileName) : defaultOutPath), + }); }), { concurrency: 1 }, ); diff --git a/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts b/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts index 95a97321c8..520835867c 100644 --- a/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts +++ b/apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts @@ -20,9 +20,12 @@ import { SUBAGENT_PROMPT, TODO_LIST_PROMPT, TOOL_CALL_READ_ONLY_PROMPT, - TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, TURN_INTERRUPT_MID_TOOL_PROMPT, } from "../src/orchestration-v2/testkit/fixtures/shared.ts"; +import { + cursorReplayPromptsForWorkspace, + shouldSeedCursorReplayWorkspace, +} from "./cursorReplayRecordingWorkspace.ts"; const RECORDINGS = { simple: { @@ -99,35 +102,18 @@ const runFileSystem = ( async function prepareWorkspace(scenario: RecordingName): Promise<{ readonly cwd: string; - readonly remove: boolean; + readonly owned: boolean; }> { - if (process.env.T3_CURSOR_REPLAY_CWD !== undefined) { + const configuredCwd = process.env.T3_CURSOR_REPLAY_CWD?.trim(); + if (configuredCwd) { return { - cwd: process.env.T3_CURSOR_REPLAY_CWD, - remove: false, - }; - } - if (scenario === "tool_call_read_only") { - await runFileSystem( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - yield* fs.remove(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { - recursive: true, - force: true, - }); - yield* fs.makeDirectory(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { - recursive: true, - }); - }), - ); - return { - cwd: TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, - remove: true, + cwd: configuredCwd, + owned: false, }; } return { cwd: await makeCheckpointWorkspace(`cursor-agent-sdk-record-${scenario}`), - remove: true, + owned: true, }; } @@ -172,16 +158,27 @@ if (!apiKey) { const recording = RECORDINGS[scenario]; const workspace = await prepareWorkspace(scenario); -if (scenario === "subagent" || scenario === "tool_call_read_only" || scenario === "todo_list") { - await writeFixtureFiles(workspace.cwd); -} - const outputPath = readArgValue("--out") ?? new URL(recording.output, import.meta.url).pathname; try { + if (shouldSeedCursorReplayWorkspace({ scenario, owned: workspace.owned })) { + await writeFixtureFiles(workspace.cwd); + } + const prompts = await runFileSystem( + Effect.gen(function* () { + const path = yield* Path.Path; + return cursorReplayPromptsForWorkspace({ + scenario, + configuredPrompts: recording.prompts, + packageJsonPath: path.join(workspace.cwd, "package.json"), + tsconfigPath: path.join(workspace.cwd, "tsconfig.json"), + }); + }), + ); const transcript = await recordCursorAgentSdkReplayTranscript({ scenario, - prompts: recording.prompts, + prompts, + ...(scenario === "tool_call_read_only" ? { transcriptPrompts: recording.prompts } : {}), modelSelection: { ...CURSOR_MODEL_SELECTION, model: process.env.T3_CURSOR_REPLAY_MODEL ?? CURSOR_MODEL_SELECTION.model, @@ -211,7 +208,7 @@ try { Console.log(`Wrote ${transcript.entries.length} Cursor SDK replay entries to ${outputPath}`), ); } finally { - if (workspace.remove) { + if (workspace.owned) { await runFileSystem( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/scripts/replayRecorderDeferredRegistry.test.ts b/apps/server/scripts/replayRecorderDeferredRegistry.test.ts new file mode 100644 index 0000000000..0aa0949f09 --- /dev/null +++ b/apps/server/scripts/replayRecorderDeferredRegistry.test.ts @@ -0,0 +1,26 @@ +import { assert, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; + +import { makeReplayRecorderDeferredRegistry } from "./replayRecorderDeferredRegistry.ts"; + +it.effect("atomically shares one deferred across concurrent get-or-create calls", () => + Effect.gen(function* () { + const registry = yield* makeReplayRecorderDeferredRegistry(); + const deferreds = yield* Effect.all( + Array.from({ length: 100 }, () => registry.getOrCreate("turn-1")), + { concurrency: "unbounded" }, + ); + + for (const deferred of deferreds) { + assert.strictEqual(deferred, deferreds[0]); + } + + yield* registry.succeed("turn-1"); + assert.isTrue(yield* Deferred.isDone(deferreds[0]!)); + yield* Effect.all(deferreds.map(Deferred.await), { + concurrency: "unbounded", + discard: true, + }); + }), +); diff --git a/apps/server/scripts/replayRecorderDeferredRegistry.ts b/apps/server/scripts/replayRecorderDeferredRegistry.ts new file mode 100644 index 0000000000..3970eaa901 --- /dev/null +++ b/apps/server/scripts/replayRecorderDeferredRegistry.ts @@ -0,0 +1,43 @@ +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as SynchronizedRef from "effect/SynchronizedRef"; + +export interface ReplayRecorderDeferredRegistry { + readonly getOrCreate: (key: string) => Effect.Effect>; + readonly succeed: (key: string) => Effect.Effect; +} + +export const makeReplayRecorderDeferredRegistry = Effect.fn("makeReplayRecorderDeferredRegistry")( + function* () { + const state = yield* SynchronizedRef.make(new Map>()); + + const getOrCreate = Effect.fn("ReplayRecorderDeferredRegistry.getOrCreate")(function* ( + key: string, + ) { + return yield* SynchronizedRef.modifyEffect(state, (deferreds) => { + const existing = deferreds.get(key); + if (existing !== undefined) { + return Effect.succeed([existing, deferreds] as const); + } + + return Deferred.make().pipe( + Effect.map((deferred) => { + const next = new Map(deferreds); + next.set(key, deferred); + return [deferred, next] as const; + }), + ); + }); + }); + + const succeed = Effect.fn("ReplayRecorderDeferredRegistry.succeed")(function* (key: string) { + const deferred = yield* getOrCreate(key); + yield* Deferred.succeed(deferred, undefined); + }); + + return { + getOrCreate, + succeed, + } satisfies ReplayRecorderDeferredRegistry; + }, +); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.test.ts index e55a1052cb..cfe3009548 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.test.ts @@ -5,22 +5,30 @@ import { ThreadId, type ProviderReplayEntry, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { vi } from "vite-plus/test"; import { CLAUDE_PROVIDER, + ClaudeAgentSdkQueryRunnerError, makeClaudeUserMessage, type ClaudeAgentSdkQueryOptions, } from "./ClaudeAdapterV2.ts"; import { CLAUDE_AGENT_SDK_REPLAY_PROTOCOL, + ClaudeReplayRuntimeExitError, makeReplayQueryRunner, recordInterruptedClaudeQuery, + recordMessagesUntilTurnResultAndFinalize, } from "./ClaudeAdapterV2.testkit.ts"; +const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError); +const isClaudeReplayRuntimeExitError = Schema.is(ClaudeReplayRuntimeExitError); + const claudeSdkMock = vi.hoisted(() => { const close = vi.fn(); const interrupt = vi.fn(async () => {}); @@ -110,6 +118,164 @@ describe("ClaudeAdapterV2 replay testkit", () => { }), ); + it.effect("keeps permission callbacks scoped to the query that opened the stream", () => + Effect.gen(function* () { + const firstCanUseTool = vi.fn>( + async (_toolName, _input, options) => ({ + behavior: "allow", + updatedInput: { query: "first" }, + toolUseID: options.toolUseID, + decisionClassification: "user_temporary", + }), + ); + const secondCanUseTool = vi.fn>( + async (_toolName, _input, options) => ({ + behavior: "allow", + updatedInput: { query: "second" }, + toolUseID: options.toolUseID, + decisionClassification: "user_temporary", + }), + ); + const firstStableOptions = { + model: "claude-sonnet-4-6", + tools: [], + permissionMode: "default", + sessionId: "session-replay-permission-first", + } satisfies ClaudeAgentSdkQueryOptions; + const secondStableOptions = { + model: "claude-sonnet-4-6", + tools: [], + permissionMode: "default", + sessionId: "session-replay-permission-second", + } satisfies ClaudeAgentSdkQueryOptions; + const runner = makeReplayQueryRunner({ + provider: CLAUDE_PROVIDER, + protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL, + version: "test", + scenario: "permission-callbacks-are-query-scoped", + entries: [ + { + type: "expect_outbound", + frame: { + type: "query.open", + options: firstStableOptions, + }, + }, + { + type: "expect_outbound", + frame: { + type: "query.open", + options: secondStableOptions, + }, + }, + { + type: "emit_inbound", + frame: { + type: "permission.request", + toolName: "Read", + input: { file_path: "/workspace/first.ts" }, + options: { + toolUseID: "tool-use-first", + }, + }, + }, + { + type: "expect_outbound", + frame: { + type: "permission.response", + result: { + behavior: "allow", + updatedInput: { query: "first" }, + toolUseID: "tool-use-first", + decisionClassification: "user_temporary", + }, + }, + }, + { + type: "runtime_exit", + status: "success", + }, + { + type: "runtime_exit", + status: "success", + }, + ], + }); + const firstSession = runner.open({ + options: { + ...firstStableOptions, + canUseTool: firstCanUseTool, + }, + threadId: ThreadId.make("thread-replay-permission-first"), + providerSessionId: ProviderSessionId.make("provider-session-replay-permission-first"), + }); + const secondSession = runner.open({ + options: { + ...secondStableOptions, + canUseTool: secondCanUseTool, + }, + threadId: ThreadId.make("thread-replay-permission-second"), + providerSessionId: ProviderSessionId.make("provider-session-replay-permission-second"), + }); + + yield* Stream.runDrain(firstSession.messages); + yield* Stream.runDrain(secondSession.messages); + runner.assertComplete(); + + assert.equal(firstCanUseTool.mock.calls.length, 1); + assert.equal(secondCanUseTool.mock.calls.length, 0); + }), + ); + + it.effect("fails a replay stream when the recorded runtime was cancelled", () => + Effect.gen(function* () { + const options = { + model: "claude-sonnet-4-6", + tools: [], + permissionMode: "default", + sessionId: "session-replay-cancelled", + } satisfies ClaudeAgentSdkQueryOptions; + const runner = makeReplayQueryRunner({ + provider: CLAUDE_PROVIDER, + protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL, + version: "test", + scenario: "cancelled-runtime-is-not-success", + entries: [ + { + type: "expect_outbound", + frame: { + type: "query.open", + options, + }, + }, + { + type: "runtime_exit", + status: "cancelled", + }, + ], + }); + const session = runner.open({ + options, + threadId: ThreadId.make("thread-replay-cancelled"), + providerSessionId: ProviderSessionId.make("provider-session-replay-cancelled"), + }); + + const exit = yield* Effect.exit(Stream.runDrain(session.messages)); + + assert.isTrue(Exit.isFailure(exit)); + if (Exit.isFailure(exit)) { + const error = Cause.squash(exit.cause); + assert.isTrue(isClaudeAgentSdkQueryRunnerError(error)); + if (isClaudeAgentSdkQueryRunnerError(error)) { + assert.isTrue(isClaudeReplayRuntimeExitError(error.cause)); + if (isClaudeReplayRuntimeExitError(error.cause)) { + assert.equal(error.cause.status, "cancelled"); + } + } + } + }), + ); + it.effect("closes an interrupted recording and emits runtime_exit when no tool use arrives", () => Effect.gen(function* () { claudeSdkMock.reset(); @@ -150,4 +316,32 @@ describe("ClaudeAdapterV2 replay testkit", () => { assert.isTrue((yield* Effect.promise(() => promptIterator.next())).done); }), ); + + it("finalizes a resumed recording as soon as its terminal result arrives", async () => { + const next = vi.fn().mockResolvedValue({ + done: false, + value: { + type: "result", + subtype: "success", + }, + }); + const finalize = vi.fn(); + const entries: Array = []; + + const completed = await recordMessagesUntilTurnResultAndFinalize({ + iterator: { next }, + entries, + scenario: "resume-at-cursor-terminal", + finalize, + }); + + assert.isTrue(completed); + assert.equal(next.mock.calls.length, 1); + assert.equal(finalize.mock.calls.length, 1); + const terminalEntry = entries.at(-1); + assert.equal(terminalEntry?.type, "emit_inbound"); + if (terminalEntry?.type === "emit_inbound") { + assert.equal(terminalEntry.label, "result"); + } + }); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index 2868680ecf..86ecac192a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -413,7 +413,6 @@ export function makeReplayQueryRunner( let cursor = 0; let failure: ClaudeAgentSdkReplayError | null = null; let cursorAdvanced = makeCursorSignal(); - let activeOptions: ClaudeAgentSdkQueryOptions | null = null; const fail = (error: ClaudeAgentSdkReplayError): never => { failure = error; @@ -428,7 +427,9 @@ export function makeReplayQueryRunner( signal.resolve(); }; - async function* replayMessages(): AsyncGenerator { + async function* replayMessages( + options: ClaudeAgentSdkQueryOptions, + ): AsyncGenerator { while (true) { if (failure !== null) { throw failure; @@ -442,7 +443,7 @@ export function makeReplayQueryRunner( if (entry.type === "emit_inbound") { if (isClaudePermissionRequestFrame(entry.frame)) { const request = entry.frame; - const invokeCanUseTool = activeOptions?.canUseTool; + const invokeCanUseTool = options.canUseTool; if (invokeCanUseTool === undefined) { const error = new ClaudeReplayUnexpectedOutboundError({ scenario: transcript.scenario, @@ -479,7 +480,7 @@ export function makeReplayQueryRunner( if (entry.type === "runtime_exit") { advance(); - if (entry.status === "success" || entry.status === "cancelled") { + if (entry.status === "success") { return; } fail( @@ -592,9 +593,8 @@ export function makeReplayQueryRunner( return { open: (input) => { assertNextOutboundFrame(makeClaudeQueryOpenFrame(input)); - activeOptions = input.options; return { - messages: Stream.fromAsyncIterable(replayMessages(), (cause) => + messages: Stream.fromAsyncIterable(replayMessages(input.options), (cause) => replayQueryRunnerError(transcript, cause), ), offer: (message) => @@ -996,6 +996,19 @@ async function recordMessagesUntilTurnResult(input: { } } +export async function recordMessagesUntilTurnResultAndFinalize(input: { + readonly iterator: AsyncIterator; + readonly entries: Array; + readonly scenario: string; + readonly finalize: () => void; +}): Promise { + try { + return await recordMessagesUntilTurnResult(input); + } finally { + input.finalize(); + } +} + async function recordMessagesUntilTurnResultWithCursor(input: { readonly iterator: AsyncIterator; readonly entries: Array; @@ -1593,12 +1606,18 @@ async function recordClaudeResumeAtCursorQuery(input: { resumedPromptQueue.offer(resumedMessage); resumedPromptQueue.close(); const resumedIterator = resumedRuntime[Symbol.asyncIterator](); - await recordMessagesUntilIteratorDone({ + const resumed = await recordMessagesUntilTurnResultAndFinalize({ iterator: resumedIterator, entries: input.entries, scenario: input.scenario, + finalize: () => { + resumedPromptQueue.close(); + resumedRuntime.close(); + }, }); - resumedRuntime.close(); + if (!resumed) { + throw new Error("Claude resumed query ended before prompt 3 completed."); + } input.entries.push({ type: "runtime_exit", status: "success", diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts index 0e46276c79..e444081f67 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts @@ -722,6 +722,8 @@ function recordingRuntimePolicy(input: { export async function recordCursorAgentSdkReplayTranscript(input: { readonly scenario: string; readonly prompts: ReadonlyArray; + /** Stable transcript representation when runtime-only paths were substituted into prompts. */ + readonly transcriptPrompts?: ReadonlyArray; readonly modelSelection: ModelSelection; readonly cwd: string; readonly interactionMode?: "default" | "plan"; @@ -730,6 +732,12 @@ export async function recordCursorAgentSdkReplayTranscript(input: { readonly interruptAfterRunStartPromptIndex?: number; readonly restartBeforePromptIndex?: number; }): Promise { + if ( + input.transcriptPrompts !== undefined && + input.transcriptPrompts.length !== input.prompts.length + ) { + throw new Error("Cursor transcript prompts must match the runtime prompt count."); + } if (input.interruptAfterToolStart === true && input.prompts.length !== 1) { throw new Error("Cursor interrupt recordings require exactly one prompt."); } @@ -824,7 +832,7 @@ export async function recordCursorAgentSdkReplayTranscript(input: { label: `run.start:${index + 1}`, frame: { type: "run.start", - message: prompt, + message: input.transcriptPrompts?.[index] ?? prompt, options: loggedCursorSendOptions(sendOptions), }, }); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts index 7ea330ca2d..701b7bdb4c 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts @@ -1,14 +1,18 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { OrchestrationV2Command, ProviderInstanceId } from "@t3tools/contracts"; +import { OrchestrationV2Command, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; -import { layer as idAllocatorLayer } from "../IdAllocator.ts"; +import { IdAllocatorV2, layer as idAllocatorLayer } from "../IdAllocator.ts"; import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts"; import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts"; -import { materializeFixtureInput } from "./fixtures/shared.ts"; +import { + CODEX_MODEL_SELECTION, + materializeFixtureInput, + type OrchestratorFixtureInput, +} from "./fixtures/shared.ts"; import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts"; const decodeCommand = Schema.decodeUnknownEffect(OrchestrationV2Command); @@ -23,6 +27,49 @@ function assertUnique(values: ReadonlyArray, label: string) { } describe("orchestrator replay fixture contract", () => { + it.effect("keeps message ordinals separate from app run ordinals after steering", () => + Effect.gen(function* () { + const idAllocator = yield* IdAllocatorV2; + for (const steeringType of ["steer", "restart"] as const) { + const fixtureInput: OrchestratorFixtureInput = { + steps: [ + { type: "message", text: "first run" }, + { type: steeringType, text: "steer first run", targetRunIndex: 1 }, + { type: "message", text: "second run" }, + { type: "interrupt", targetRunIndex: 2 }, + ], + }; + const materialized = yield* materializeFixtureInput({ + scenario: `run-index-after-${steeringType}`, + fixtureInput, + driver: ProviderDriverKind.make("codex"), + modelSelection: CODEX_MODEL_SELECTION, + }); + const secondRunCommand = materialized.commands.find( + (command) => command.type === "message.dispatch" && command.text === "second run", + ); + assert.isDefined(secondRunCommand); + const secondRunDispatch = materialized.steps.find( + (step) => step.type === "dispatch" && step.command === secondRunCommand, + ); + assert.deepInclude(secondRunDispatch, { + type: "dispatch", + await: false, + key: "run:2", + }); + const expectedSecondRunId = idAllocator.derive.run({ + threadId: materialized.projectionThreadIds[0]!, + ordinal: 2, + }); + assert.isTrue( + materialized.steps.some( + (step) => step.type === "await_run_steerable" && step.runId === expectedSecondRunId, + ), + ); + } + }).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime), + ); + it.effect( "defines one stable input and provider-specific replay/output contracts per scenario", () => diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index 8e0779081c..31c177a223 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -384,6 +384,7 @@ export function materializeFixtureInput(input: { const commands: Array = []; const steps: Array = []; let messageIndex = 0; + let runIndex = 0; const activeRunDispatchKeys = new Set(); const runIdFor = (runOrdinal: number) => @@ -428,16 +429,17 @@ export function materializeFixtureInput(input: { switch (step.type) { case "message": messageIndex += 1; + runIndex += 1; { const nextStep = input.fixtureInput.steps[stepIndex + 1]; const shouldRunInBackground = (nextStep !== undefined && - ((nextStep.type === "interrupt" && nextStep.targetRunIndex === messageIndex) || + ((nextStep.type === "interrupt" && nextStep.targetRunIndex === runIndex) || nextStep.type === "queue_message" || - (nextStep.type === "restart" && nextStep.targetRunIndex === messageIndex))) || + (nextStep.type === "restart" && nextStep.targetRunIndex === runIndex))) || nextStep?.type === "approve_next_runtime_request" || nextStep?.type === "answer_next_user_input_request"; - const key = `run:${messageIndex}`; + const key = `run:${runIndex}`; pushDispatch( dispatchMessageCommand({ commandId: yield* idAllocator.allocate.command({ @@ -461,7 +463,7 @@ export function materializeFixtureInput(input: { !( nextStep !== undefined && (nextStep.type === "steer" || nextStep.type === "restart") && - nextStep.targetRunIndex === messageIndex + nextStep.targetRunIndex === runIndex ) ) { steps.push({ type: "await_thread_idle", threadId: ids.threadId }); @@ -470,6 +472,7 @@ export function materializeFixtureInput(input: { break; case "queue_message": messageIndex += 1; + runIndex += 1; pushDispatch( dispatchMessageCommand({ commandId: yield* idAllocator.allocate.command({ @@ -486,7 +489,7 @@ export function materializeFixtureInput(input: { ...(step.attachments === undefined ? {} : { attachments: step.attachments }), }), ); - steps.push({ type: "await", key: `run:${messageIndex - 1}` }); + steps.push({ type: "await", key: `run:${runIndex - 1}` }); steps.push({ type: "await_thread_idle", threadId: ids.threadId }); break; case "answer_next_user_input_request":