Open History to see the last commit
1import { assert } from "@effect/vitest";
2import {
3 type ChatAttachment,
4 CommandId,
5 isOrchestrationV2WorkActive,
6 MessageId,
7 ProjectId,
8 ThreadId,
9 type ModelSelection,
10 type OrchestrationV2Command,
11 type OrchestrationV2ExecutionNode,
12 type OrchestrationV2RunStatus,
13 type OrchestrationV2ThreadProjection,
14 type OrchestrationV2TurnItem,
15 type OrchestrationV2UserMessageInputIntent,
16 ProviderInstanceId,
17 type ProviderInteractionMode,
18 type ProviderDriverKind,
19 type ProviderReplayTranscript,
20 type ProviderUserInputAnswers,
21 type RuntimeMode,
22} from "@t3tools/contracts";
23import type * as Duration from "effect/Duration";
24import * as Effect from "effect/Effect";
25
26import type {
27 OrchestratorV2ScenarioResult,
28 OrchestratorV2ScenarioStep,
29} from "../OrchestratorScenario.ts";
30import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
31import type { RuntimePolicyV2Override } from "../../RuntimePolicy.ts";
32
33export const SIMPLE_PROMPT = "Respond with the following text: fixture simple ok";
34export const MULTI_TURN_FIRST_PROMPT = "Respond with exactly: first fixture turn complete";
35export const MULTI_TURN_SECOND_PROMPT = "Respond with exactly: second fixture turn complete";
36export const PROVIDER_THREAD_RESUME_FIRST_PROMPT =
37 "Respond with exactly: provider thread resume fixture first turn complete";
38export const PROVIDER_THREAD_RESUME_SECOND_PROMPT =
39 "Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete";
40export const TOOL_CALL_READ_ONLY_WORKSPACE_ROOT = "/tmp/claude-replay-tool_call_read_only";
41export const TOOL_CALL_READ_ONLY_PROMPT = `Read ${TOOL_CALL_READ_ONLY_WORKSPACE_ROOT}/package.json and ${TOOL_CALL_READ_ONLY_WORKSPACE_ROOT}/tsconfig.json, then answer exactly: read only tool fixture complete`;
42export const CLAUDE_LOCAL_BASH_TASK_PROMPT =
43 "Run a local Bash typecheck command, then answer exactly: claude local bash task fixture complete";
44export const CLAUDE_RESULT_IS_ERROR_PROMPT = "Say hello before the credentials expire.";
45export const CLAUDE_RESULT_IS_ERROR_FOLLOW_UP = "Try again now that auth is back.";
46export const TOOL_CALL_WRITE_PROMPT =
47 "Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.";
48export const MESSAGE_STEERING_INITIAL_PROMPT =
49 "Respond with exactly: steering fixture initial response";
50export const SUBAGENT_PROMPT =
51 "Spawn 2 subagents, one to read package.json and one to read tsconfig.json";
52export const SUBAGENT_V2_NESTED_PROMPT =
53 "Spawn one subagent and tell it to spawn its own subagent, which must in turn spawn one more subagent whose only task is to reply with exactly: Hello. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.";
54export const SUBAGENT_V2_PROMPT =
55 "Spawn one subagent whose only task is to reply with exactly: Hello. Wait for it to finish, then reply with exactly what it said.";
56export const SUBAGENT_V2_APPROVAL_PROMPT =
57 "Do not run any commands yourself. Spawn one subagent whose only task is to run this exact shell command: printf 'subagent approval fixture' > subagent-approval.txt and then reply with exactly: Written. Wait for it to finish, then reply with exactly what it said.";
58export const SUBAGENT_V2_NESTED_APPROVAL_PROMPT =
59 "Do not run any commands yourself. Spawn one subagent and tell it not to run any commands itself but to spawn its own subagent, whose only task is to run this exact shell command: printf 'nested approval fixture' > nested-approval.txt and then reply with exactly: Written. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.";
60export const OPENCODE_SUBAGENT_PROMPT =
61 "Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK.";
62export const SUBAGENT_CONTINUE_PROMPT =
63 "Spawn one subagent and have it reply exactly: initial subagent response";
64export const SUBAGENT_CONTINUE_PARENT_PROMPT =
65 "Have the same subagent you spawned earlier reply exactly: continued subagent response";
66export const SUBAGENT_CONTINUE_CHILD_PROMPT = "Reply exactly: continued subagent response";
67export const OPENCODE2_SIMPLE_PROMPT =
68 "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence.";
69export const OPENCODE2_TOOL_CALL_PROMPT =
70 "Use the read tool to read hello.txt, then run the shell command `echo TOOL_OK` with the bash tool, then reply DONE.";
71export const OPENCODE2_INTERRUPT_PROMPT =
72 "Run the shell command `sleep 60 && echo LATE` with the bash tool, then reply DONE.";
73export const OPENCODE2_PERMISSION_PROMPT =
74 "Run the shell command `echo FIRST` with the bash tool. After it completes, run `echo SECOND` with the bash tool. Then reply with what happened.";
75export const OPENCODE2_STEER_PROMPT =
76 "Run the shell command `sleep 12 && echo A` with the bash tool, then reply DONE_A.";
77export const OPENCODE2_STEER_TEXT = "Also mention the word STEERED in your final reply.";
78export const OPENCODE2_QUEUED_PROMPT = "Reply exactly QUEUED_B.";
79export const OPENCODE2_CANCELLED_PROMPT = "Reply exactly QUEUED_C.";
80export const OPENCODE2_REVERT_FIRST_PROMPT =
81 "Create a file named reverted.txt containing the word ALPHA using the write tool, then reply DONE.";
82export const OPENCODE2_REVERT_SECOND_PROMPT =
83 "Overwrite reverted.txt so it contains the word BETA using the write tool, then reply DONE.";
84export const OPENCODE2_QUESTION_PROMPT =
85 "Before doing anything, use the question tool to ask me which color I prefer, offering the options red and blue. After I answer, reply with only the chosen color.";
86export const OPENCODE2_SUBAGENT_PROMPT =
87 "Use the subagent tool to delegate to the explore subagent with the prompt: 'List the files in the current directory and report their names.' Wait for it, then summarize its answer in one line.";
88export const OPENCODE2_NESTED_BACKGROUND_PROMPT =
89 "Use the subagent tool (foreground, do not set background) to delegate to the general subagent with this exact prompt: 'Use the subagent tool with background set to true to delegate to the general subagent with the prompt: Run the shell command `sleep 25` with the shell tool, then reply exactly GRANDCHILD_OK. As soon as it is launched, reply exactly MIDDLE_OK and end your turn without waiting for it.' Wait for that subagent to return, then reply exactly ROOT_OK.";
90export const OPENCODE2_BACKGROUND_PROMPT =
91 "Use the subagent tool with background enabled to delegate to the general subagent with the prompt: 'Run the shell command `sleep 20` with the bash tool and then reply exactly CHILD_OK.' As soon as it is launched, reply exactly PARENT_OK and end your turn without waiting for it.";
92export const OPENCODE2_COMPACTION_FIRST_PROMPT = "Remember the codeword PAPAYA. Reply OK.";
93export const OPENCODE2_COMPACTION_RECALL_PROMPT = "What was the codeword? One word.";
94export const OPENCODE2_RESTART_PROMPT =
95 "Run the shell command `sleep 25 && echo RESUMED` with the bash tool, then reply with its output.";
96export const OPENCODE2_RESTART_RECALL_PROMPT =
97 "What did I last ask you to run? Answer in one short sentence.";
98export const OPENCODE2_COMMAND_PROMPT = "/hello WORLD";
99export const OPENCODE2_SKILL_PROMPT = "Use $greet to say hi in three words.";
100export const TURN_INTERRUPT_PROMPT =
101 "Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.";
102export const TURN_INTERRUPT_MID_TOOL_PROMPT =
103 "Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.";
104const COMMAND_OUTPUT_STREAMING_COMMAND =
105 "for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'";
106export const COMMAND_OUTPUT_STREAMING_PROMPT = `Run this exact shell command in the foreground and wait for it to finish: \`${COMMAND_OUTPUT_STREAMING_COMMAND}\`. Then respond exactly: command output fixture complete`;
107export const TURN_INTERRUPT_RECOVERY_PROMPT =
108 "Respond with exactly: interrupt recovery fixture complete";
109export const MESSAGE_STEERING_STEER_PROMPT =
110 "Actually, respond with exactly: steering fixture observed";
111export const THREAD_ROLLBACK_FIRST_PROMPT =
112 "Respond with exactly: rollback fixture first turn complete";
113export const THREAD_ROLLBACK_SECOND_PROMPT =
114 "Respond with exactly: rollback fixture second turn complete";
115export const THREAD_ROLLBACK_AFTER_PROMPT = "Repeat the conversation verbatim.";
116export const THREAD_FORK_NATIVE_SOURCE_PROMPT =
117 "Respond with the following text: source fork seed ok";
118export const THREAD_FORK_NATIVE_TARGET_PROMPT = "Respond with the following text: fork native ok";
119const THREAD_FORK_NATIVE_CONTINUE_SOURCE_MARKER = "source-marker-7Q9V";
120const THREAD_FORK_NATIVE_CONTINUE_FORK_MARKER = "fork-marker-2K4M";
121export const THREAD_FORK_NATIVE_CONTINUE_SOURCE_PROMPT = `Remember the opaque marker ${THREAD_FORK_NATIVE_CONTINUE_SOURCE_MARKER} for later in this conversation. Respond with exactly: source marker stored`;
122export const THREAD_FORK_NATIVE_CONTINUE_FIRST_PROMPT = `Remember the second opaque marker ${THREAD_FORK_NATIVE_CONTINUE_FORK_MARKER} for later in this conversation. Respond with exactly: fork marker stored`;
123export const THREAD_FORK_NATIVE_CONTINUE_SECOND_PROMPT =
124 "Return the two opaque markers previously provided in chronological order, separated by a single | character. Respond with only the markers and separator.";
125const THREAD_FORK_NATIVE_SIBLINGS_SOURCE_MARKER = "sibling-source-8R3D";
126const THREAD_FORK_NATIVE_SIBLINGS_FIRST_MARKER = "sibling-first-5L2P";
127const THREAD_FORK_NATIVE_SIBLINGS_SECOND_MARKER = "sibling-second-9N6C";
128export const THREAD_FORK_NATIVE_SIBLINGS_SOURCE_PROMPT = `Remember the opaque marker ${THREAD_FORK_NATIVE_SIBLINGS_SOURCE_MARKER} for later in this conversation. Respond with exactly: sibling source stored`;
129export const THREAD_FORK_NATIVE_SIBLINGS_FIRST_PROMPT = `Remember the fork-local marker ${THREAD_FORK_NATIVE_SIBLINGS_FIRST_MARKER}. Return the source marker followed by this marker, separated by |. Respond with only the markers and separator.`;
130export const THREAD_FORK_NATIVE_SIBLINGS_SECOND_PROMPT = `Remember the fork-local marker ${THREAD_FORK_NATIVE_SIBLINGS_SECOND_MARKER}. Return the source marker followed by this marker, separated by |. Respond with only the markers and separator.`;
131const THREAD_MERGE_BACK_SOURCE_MARKER = "merge-source-4H8Q";
132const THREAD_MERGE_BACK_FORK_MARKER = "merge-fork-7T2W";
133export const THREAD_MERGE_BACK_SOURCE_PROMPT = `Remember the opaque marker ${THREAD_MERGE_BACK_SOURCE_MARKER} for later in this conversation. Respond with exactly: merge source stored`;
134export const THREAD_MERGE_BACK_FORK_PROMPT = `Remember the fork-local marker ${THREAD_MERGE_BACK_FORK_MARKER}. Respond with exactly: merge fork stored`;
135export const THREAD_MERGE_BACK_HANDOFF_PROMPT = [
136 "Context handoff (merge_back / fork_delta_summary):",
137 "Merge-back context from forked conversation.",
138 "",
139 "Fork delta:",
140 `- User introduced opaque marker ${THREAD_MERGE_BACK_FORK_MARKER}.`,
141 "- Assistant confirmed: merge fork stored",
142 "",
143 "User message:",
144 "Retain the transferred fork marker for later. Respond with exactly: merge delta stored",
145].join("\n");
146export const THREAD_MERGE_BACK_RECALL_PROMPT =
147 "Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.";
148const THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER = "merge-sibling-source-3C7K";
149const THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER = "merge-sibling-first-6V2J";
150const THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER = "merge-sibling-second-9X5B";
151export const THREAD_MERGE_BACK_SIBLINGS_SOURCE_PROMPT = `Remember the opaque marker ${THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER} for later in this conversation. Respond with exactly: merge sibling source stored`;
152export const THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT = `Remember the fork-local marker ${THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER}. Respond with exactly: first merge sibling stored`;
153export const THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT = `Remember the fork-local marker ${THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER}. Respond with exactly: second merge sibling stored`;
154export const THREAD_MERGE_BACK_SIBLINGS_FIRST_HANDOFF_PROMPT = [
155 "Context handoff (merge_back / fork_delta_summary):",
156 "Merge-back context from first forked conversation.",
157 "",
158 "Fork delta:",
159 `- User introduced opaque marker ${THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER}.`,
160 "- Assistant confirmed: first merge sibling stored",
161 "",
162 "User message:",
163 "Retain the first transferred marker for later. Respond with exactly: first merge delta stored",
164].join("\n");
165export const THREAD_MERGE_BACK_SIBLINGS_SECOND_HANDOFF_PROMPT = [
166 "Context handoff (merge_back / fork_delta_summary):",
167 "Merge-back context from second forked conversation.",
168 "",
169 "Fork delta:",
170 `- User introduced opaque marker ${THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER}.`,
171 "- Assistant confirmed: second merge sibling stored",
172 "",
173 "User message:",
174 "Retain the second transferred marker for later. Respond with exactly: second merge delta stored",
175].join("\n");
176export const THREAD_MERGE_BACK_SIBLINGS_RECALL = [
177 THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER,
178 THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER,
179 THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER,
180].join("|");
181export const THREAD_MERGE_BACK_SIBLINGS_RECALL_PROMPT =
182 "Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.";
183export const THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT =
184 "For this fork-boundary fixture, respond with exactly: fork boundary alpha";
185export const THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT =
186 "For this fork-boundary fixture, respond with exactly: fork boundary beta";
187export const THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT =
188 "Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.";
189export const TODO_LIST_PROMPT =
190 "Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete";
191export const PLAN_QUESTIONS_PROMPT =
192 "Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete";
193export const PROPOSED_PLAN_PROMPT =
194 "Create a short implementation plan for adding deterministic replay fixtures. Do not ask questions. Present the final plan in a proposed plan block.";
195export const WEB_SEARCH_PROMPT =
196 "Search the web for FIFA World Cup ticket pricing, then answer exactly: web search fixture complete";
197export const SKILL_INVOCATION_PROMPT = "$review README.md";
198export const SKILL_INVOCATION_CURSOR_MESSAGE = "/review README.md";
199
200export type OrchestratorFixtureInputStep =
201 | {
202 readonly type: "message";
203 readonly text: string;
204 readonly attachments?: ReadonlyArray<ChatAttachment>;
205 }
206 | {
207 readonly type: "queue_message";
208 readonly text: string;
209 readonly attachments?: ReadonlyArray<ChatAttachment>;
210 readonly createdBy?: Extract<
211 OrchestrationV2Command,
212 { readonly type: "message.dispatch" }
213 >["createdBy"];
214 readonly creationSource?: Extract<
215 OrchestrationV2Command,
216 { readonly type: "message.dispatch" }
217 >["creationSource"];
218 }
219 | {
220 readonly type: "cancel_queued_run";
221 readonly targetRunIndex: number;
222 }
223 | {
224 readonly type: "await_run_status";
225 readonly targetRunIndex: number;
226 readonly status: OrchestrationV2RunStatus;
227 readonly waitForTurnItemType?: OrchestrationV2TurnItem["type"];
228 }
229 | {
230 /** Replay finishes background-held runs through the adapter's debounce receipt. */
231 readonly type: "finish_held_run";
232 readonly targetRunIndex: number;
233 readonly status: OrchestrationV2RunStatus;
234 }
235 | {
236 readonly type: "capture_shell_snapshot";
237 readonly key: string;
238 }
239 | {
240 readonly type: "release_replay_gate";
241 readonly label: string;
242 }
243 | {
244 readonly type: "steer";
245 readonly text: string;
246 readonly attachments?: ReadonlyArray<ChatAttachment>;
247 readonly targetRunIndex: number;
248 }
249 | {
250 readonly type: "restart";
251 readonly text: string;
252 readonly attachments?: ReadonlyArray<ChatAttachment>;
253 readonly targetRunIndex: number;
254 }
255 | {
256 readonly type: "interrupt";
257 readonly targetRunIndex: number;
258 readonly waitForTurnItemType?: OrchestrationV2TurnItem["type"];
259 }
260 | {
261 readonly type: "stop_background_work";
262 readonly targetRunIndex: number;
263 }
264 | {
265 readonly type: "release_replay_gate_after_waiting";
266 readonly label: string;
267 readonly targetRunIndex: number;
268 }
269 | {
270 readonly type: "approve_next_runtime_request";
271 readonly decision?: Extract<
272 OrchestrationV2Command,
273 { readonly type: "runtime-request.respond" }
274 >["decision"];
275 readonly shellSnapshotKeyWhilePending?: string;
276 }
277 | {
278 readonly type: "answer_next_user_input_request";
279 readonly answers: ProviderUserInputAnswers;
280 }
281 | {
282 readonly type: "rollback";
283 readonly checkpointScopeSuffix: string;
284 readonly checkpointSuffix: string;
285 }
286 | {
287 readonly type: "advance_clock";
288 readonly duration: Duration.Input;
289 };
290
291export interface OrchestratorFixtureInput {
292 readonly interactionMode?: ProviderInteractionMode;
293 readonly runtimeMode?: RuntimeMode;
294 /** Files committed before replay, keyed by relative path; seed the same files when recording so workspace reads match. */
295 readonly workspaceFiles?: Readonly<Record<string, string>>;
296 readonly steps: ReadonlyArray<OrchestratorFixtureInputStep>;
297}
298
299export interface ProviderOrchestratorReplayVariant {
300 readonly driver: ProviderDriverKind;
301 readonly transcriptFile: URL;
302 readonly recordedScenario?: string;
303 readonly transcriptEntriesThroughLabel?: string;
304 readonly modelSelection: ModelSelection;
305 readonly runtimePolicyOverride?: RuntimePolicyV2Override;
306 readonly runContinuationWorker?: boolean;
307 readonly expectedAbsentWorkspacePaths?: ReadonlyArray<string>;
308 readonly assertOutput: (
309 result: OrchestratorV2ScenarioResult,
310 transcript: ProviderReplayTranscript,
311 ) => void;
312}
313
314export interface OrchestratorReplayFixture {
315 readonly name: string;
316 readonly buildInput: () => OrchestratorFixtureInput;
317 readonly providers: ReadonlyArray<ProviderOrchestratorReplayVariant>;
318}
319
320export interface MaterializedOrchestratorFixtureInput {
321 readonly commands: ReadonlyArray<OrchestrationV2Command>;
322 readonly steps: ReadonlyArray<OrchestratorV2ScenarioStep>;
323 readonly projectionThreadIds: ReadonlyArray<ThreadId>;
324}
325
326export interface FixtureIds {
327 readonly threadId: ThreadId;
328 readonly projectId: ProjectId;
329}
330
331export const CODEX_MODEL_SELECTION = {
332 instanceId: ProviderInstanceId.make("codex"),
333 model: "gpt-6-luna",
334} satisfies ModelSelection;
335
336export const CLAUDE_MODEL_SELECTION = {
337 instanceId: ProviderInstanceId.make("claudeAgent"),
338 model: "claude-sonnet-4-6",
339} satisfies ModelSelection;
340
341export const CURSOR_MODEL_SELECTION = {
342 instanceId: ProviderInstanceId.make("cursor"),
343 model: "composer-2.5",
344} satisfies ModelSelection;
345
346export const MUSE_MODEL_SELECTION = {
347 instanceId: ProviderInstanceId.make("muse"),
348 model: "muse-spark-1.3-contributor",
349} satisfies ModelSelection;
350
351export const GROK_MODEL_SELECTION = {
352 instanceId: ProviderInstanceId.make("grok"),
353 model: "grok-build",
354} satisfies ModelSelection;
355
356export const OPENCODE_MODEL_SELECTION = {
357 instanceId: ProviderInstanceId.make("opencode"),
358 model: "openai/gpt-5.4-mini",
359 options: [{ id: "agent", value: "build" }],
360} satisfies ModelSelection;
361
362export const OPENCODE2_MODEL_SELECTION = {
363 instanceId: ProviderInstanceId.make("opencode"),
364 model: "opencode/space-bunny-free",
365 options: [{ id: "variant", value: "high" }],
366} satisfies ModelSelection;
367
368export const PI_MODEL_SELECTION = {
369 instanceId: ProviderInstanceId.make("pi"),
370 model: "openrouter/deepseek/deepseek-v4-flash",
371} satisfies ModelSelection;
372
373export const ACP_REGISTRY_MODEL_SELECTION = {
374 instanceId: ProviderInstanceId.make("acpRegistry"),
375 model: "default",
376} satisfies ModelSelection;
377
378export const READ_ONLY_ON_REQUEST_POLICY = {
379 approvalPolicy: "on-request",
380 sandboxPolicy: {
381 type: "readOnly",
382 access: { type: "fullAccess" },
383 networkAccess: false,
384 },
385} as const satisfies RuntimePolicyV2Override;
386
387export const READ_ONLY_NEVER_POLICY = {
388 approvalPolicy: "never",
389 sandboxPolicy: {
390 type: "readOnly",
391 access: { type: "fullAccess" },
392 networkAccess: false,
393 },
394} as const satisfies RuntimePolicyV2Override;
395
396export const WORKSPACE_NEVER_POLICY = {
397 approvalPolicy: "never",
398 sandboxPolicy: {
399 type: "workspaceWrite",
400 writableRoots: [],
401 readOnlyAccess: { type: "fullAccess" },
402 networkAccess: false,
403 },
404} as const satisfies RuntimePolicyV2Override;
405
406export const RESTRICTED_GRANULAR_POLICY = {
407 approvalPolicy: {
408 granular: {
409 mcp_elicitations: true,
410 request_permissions: true,
411 rules: true,
412 sandbox_approval: true,
413 skill_approval: true,
414 },
415 },
416 sandboxPolicy: {
417 type: "readOnly",
418 access: {
419 type: "restricted",
420 includePlatformDefaults: false,
421 readableRoots: [],
422 },
423 networkAccess: false,
424 },
425} as const satisfies RuntimePolicyV2Override;
426
427function createThreadCommand(input: {
428 readonly commandId: CommandId;
429 readonly ids: FixtureIds;
430 readonly scenario: string;
431 readonly modelSelection: ModelSelection;
432 readonly interactionMode?: ProviderInteractionMode;
433 readonly runtimeMode?: RuntimeMode;
434}): OrchestrationV2Command {
435 return {
436 type: "thread.create",
437 createdBy: "user",
438 creationSource: "web",
439 commandId: input.commandId,
440 threadId: input.ids.threadId,
441 projectId: input.ids.projectId,
442 title: `Replay fixture: ${input.scenario}`,
443 modelSelection: input.modelSelection,
444 runtimeMode: input.runtimeMode ?? "full-access",
445 interactionMode: input.interactionMode ?? "default",
446 branch: null,
447 worktreePath: null,
448 };
449}
450
451function dispatchMessageCommand(input: {
452 readonly commandId: CommandId;
453 readonly ids: FixtureIds;
454 readonly modelSelection: ModelSelection;
455 readonly messageId: MessageId;
456 readonly text: string;
457 readonly attachments?: ReadonlyArray<ChatAttachment>;
458 readonly createdBy?: Extract<
459 OrchestrationV2Command,
460 { readonly type: "message.dispatch" }
461 >["createdBy"];
462 readonly creationSource?: Extract<
463 OrchestrationV2Command,
464 { readonly type: "message.dispatch" }
465 >["creationSource"];
466 readonly dispatchMode?: Extract<
467 OrchestrationV2Command,
468 { readonly type: "message.dispatch" }
469 >["dispatchMode"];
470}): OrchestrationV2Command {
471 return {
472 type: "message.dispatch",
473 createdBy: input.createdBy ?? "user",
474 creationSource: input.creationSource ?? "web",
475 commandId: input.commandId,
476 threadId: input.ids.threadId,
477 messageId: input.messageId,
478 text: input.text,
479 attachments: [...(input.attachments ?? [])],
480 modelSelection: input.modelSelection,
481 dispatchMode: input.dispatchMode ?? { type: "start_immediately" },
482 };
483}
484
485export function materializeFixtureInput(input: {
486 readonly scenario: string;
487 readonly fixtureInput: OrchestratorFixtureInput;
488 readonly driver: ProviderDriverKind;
489 readonly modelSelection: ModelSelection;
490}): Effect.Effect<
491 MaterializedOrchestratorFixtureInput,
492 IdAllocator.IdAllocatorV2Error,
493 IdAllocator.IdAllocatorV2
494> {
495 return Effect.gen(function* () {
496 const idAllocator = yield* IdAllocator.IdAllocatorV2;
497 const projectId = yield* idAllocator.allocate.project({ fixtureName: input.scenario });
498 const threadId = yield* idAllocator.allocate.thread({
499 fixtureName: input.scenario,
500 projectId,
501 });
502 const ids = { threadId, projectId } satisfies FixtureIds;
503 const commands: Array<OrchestrationV2Command> = [];
504 const steps: Array<OrchestratorV2ScenarioStep> = [];
505 let messageIndex = 0;
506 let runIndex = 0;
507 const activeRunDispatchKeys = new Set<string>();
508
509 const runIdFor = (runOrdinal: number) =>
510 idAllocator.derive.run({ threadId: ids.threadId, ordinal: runOrdinal });
511
512 const pushDispatch = (
513 command: OrchestrationV2Command,
514 options: {
515 readonly await?: boolean;
516 readonly key?: string;
517 readonly advanceClockAfter?: boolean;
518 } = {},
519 ) => {
520 commands.push(command);
521 steps.push({
522 type: "dispatch",
523 command,
524 await: options.await ?? true,
525 ...(options.key === undefined ? {} : { key: options.key }),
526 });
527 if (options.advanceClockAfter ?? true) {
528 steps.push({ type: "advance_clock", duration: "1 millis" });
529 }
530 };
531
532 pushDispatch(
533 createThreadCommand({
534 commandId: yield* idAllocator.allocate.command({
535 fixtureName: input.scenario,
536 commandName: "thread-create",
537 }),
538 ids,
539 scenario: input.scenario,
540 modelSelection: input.modelSelection,
541 ...(input.fixtureInput.interactionMode === undefined
542 ? {}
543 : { interactionMode: input.fixtureInput.interactionMode }),
544 ...(input.fixtureInput.runtimeMode === undefined
545 ? {}
546 : { runtimeMode: input.fixtureInput.runtimeMode }),
547 }),
548 );
549
550 // Multiple requests keep runs busy between answers; wait for each request, not thread idle.
551 const answersNext = (stepIndex: number) => {
552 const next = input.fixtureInput.steps[stepIndex + 1]?.type;
553 return next === "approve_next_runtime_request" || next === "answer_next_user_input_request";
554 };
555 for (const [stepIndex, step] of input.fixtureInput.steps.entries()) {
556 switch (step.type) {
557 case "message":
558 messageIndex += 1;
559 runIndex += 1;
560 {
561 const nextStep = input.fixtureInput.steps[stepIndex + 1];
562 const shouldRunInBackground =
563 (nextStep !== undefined &&
564 ((nextStep.type === "interrupt" && nextStep.targetRunIndex === runIndex) ||
565 nextStep.type === "queue_message" ||
566 (nextStep.type === "restart" && nextStep.targetRunIndex === runIndex) ||
567 (nextStep.type === "release_replay_gate_after_waiting" &&
568 nextStep.targetRunIndex === runIndex) ||
569 // Continuations start while busy; waiting for idle would deadlock.
570 (nextStep.type === "await_run_status" && nextStep.targetRunIndex > runIndex) ||
571 // Held open until the test clock moves, so it cannot go idle first.
572 nextStep.type === "finish_held_run")) ||
573 nextStep?.type === "approve_next_runtime_request" ||
574 nextStep?.type === "answer_next_user_input_request";
575 const key = `run:${runIndex}`;
576 pushDispatch(
577 dispatchMessageCommand({
578 commandId: yield* idAllocator.allocate.command({
579 fixtureName: input.scenario,
580 commandName: `message-${messageIndex}`,
581 }),
582 ids,
583 modelSelection: input.modelSelection,
584 messageId: yield* idAllocator.allocate.message({
585 threadId: ids.threadId,
586 ordinal: messageIndex,
587 }),
588 text: step.text,
589 ...(step.attachments === undefined ? {} : { attachments: step.attachments }),
590 }),
591 shouldRunInBackground ? { await: false, key } : undefined,
592 );
593 if (shouldRunInBackground) {
594 activeRunDispatchKeys.add(key);
595 } else if (
596 !(
597 nextStep !== undefined &&
598 (nextStep.type === "steer" || nextStep.type === "restart") &&
599 nextStep.targetRunIndex === runIndex
600 )
601 ) {
602 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
603 }
604 }
605 break;
606 case "queue_message": {
607 messageIndex += 1;
608 runIndex += 1;
609 const nextStep = input.fixtureInput.steps[stepIndex + 1];
610 pushDispatch(
611 dispatchMessageCommand({
612 commandId: yield* idAllocator.allocate.command({
613 fixtureName: input.scenario,
614 commandName: `queue-message-${messageIndex}`,
615 }),
616 ids,
617 modelSelection: input.modelSelection,
618 messageId: yield* idAllocator.allocate.message({
619 threadId: ids.threadId,
620 ordinal: messageIndex,
621 }),
622 text: step.text,
623 ...(step.createdBy === undefined ? {} : { createdBy: step.createdBy }),
624 ...(step.creationSource === undefined ? {} : { creationSource: step.creationSource }),
625 ...(step.attachments === undefined ? {} : { attachments: step.attachments }),
626 dispatchMode: { type: "queue_after_active" },
627 }),
628 );
629 const shouldSkipQueueBarrier =
630 nextStep?.type === "queue_message" ||
631 (nextStep?.type === "cancel_queued_run" && nextStep.targetRunIndex === runIndex);
632 if (!shouldSkipQueueBarrier) {
633 const queueBarrierKey =
634 Array.from(activeRunDispatchKeys).at(-1) ?? `run:${runIndex - 1}`;
635 activeRunDispatchKeys.delete(queueBarrierKey);
636 steps.push({ type: "await", key: queueBarrierKey });
637 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
638 }
639 break;
640 }
641 case "cancel_queued_run":
642 pushDispatch({
643 type: "queued-run.cancel",
644 commandId: yield* idAllocator.allocate.command({
645 fixtureName: input.scenario,
646 commandName: `cancel-queued-run-${step.targetRunIndex}`,
647 }),
648 threadId: ids.threadId,
649 runId: runIdFor(step.targetRunIndex),
650 });
651 break;
652 case "await_run_status":
653 steps.push({
654 type: "await_run_status",
655 threadId: ids.threadId,
656 runId: runIdFor(step.targetRunIndex),
657 status: step.status,
658 });
659 if (step.waitForTurnItemType !== undefined) {
660 steps.push({
661 type: "await_run_turn_item",
662 threadId: ids.threadId,
663 runId: runIdFor(step.targetRunIndex),
664 itemType: step.waitForTurnItemType,
665 });
666 }
667 break;
668 case "finish_held_run":
669 steps.push({
670 type: "finish_held_run",
671 threadId: ids.threadId,
672 runId: runIdFor(step.targetRunIndex),
673 status: step.status,
674 });
675 break;
676 case "capture_shell_snapshot":
677 steps.push({ type: "capture_shell_snapshot", key: step.key });
678 break;
679 case "release_replay_gate":
680 steps.push({ type: "release_replay_gate", label: step.label });
681 break;
682 case "answer_next_user_input_request":
683 pushDispatch(
684 {
685 type: "runtime-request.respond",
686 commandId: yield* idAllocator.allocate.command({
687 fixtureName: input.scenario,
688 commandName: `answer-user-input-request-${messageIndex}`,
689 }),
690 threadId: ids.threadId,
691 requestId: yield* idAllocator.allocate.runtimeRequest({
692 driver: input.driver,
693 nativeRequestId: `fixture-placeholder-${messageIndex}`,
694 }),
695 answers: step.answers,
696 },
697 { advanceClockAfter: false },
698 );
699 steps[steps.length - 1] = {
700 type: "respond_to_next_runtime_request",
701 threadId: ids.threadId,
702 commandId: commands.at(-1)!.commandId,
703 answers: step.answers,
704 };
705 steps.push({ type: "advance_clock", duration: "1 millis" });
706 if (!answersNext(stepIndex)) {
707 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
708 }
709 break;
710 case "approve_next_runtime_request":
711 pushDispatch(
712 {
713 type: "runtime-request.respond",
714 commandId: yield* idAllocator.allocate.command({
715 fixtureName: input.scenario,
716 commandName: `approve-runtime-request-${messageIndex}`,
717 }),
718 threadId: ids.threadId,
719 requestId: yield* idAllocator.allocate.runtimeRequest({
720 driver: input.driver,
721 nativeRequestId: `fixture-placeholder-${messageIndex}`,
722 }),
723 decision: step.decision ?? "accept",
724 },
725 { advanceClockAfter: false },
726 );
727 steps[steps.length - 1] = {
728 type: "respond_to_next_runtime_request",
729 threadId: ids.threadId,
730 commandId: commands.at(-1)!.commandId,
731 decision: step.decision ?? "accept",
732 ...(step.shellSnapshotKeyWhilePending === undefined
733 ? {}
734 : { shellSnapshotKeyWhilePending: step.shellSnapshotKeyWhilePending }),
735 };
736 steps.push({ type: "advance_clock", duration: "1 millis" });
737 if (!answersNext(stepIndex)) {
738 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
739 }
740 break;
741 case "steer":
742 messageIndex += 1;
743 steps.push({
744 type: "await_run_steerable",
745 threadId: ids.threadId,
746 runId: runIdFor(step.targetRunIndex),
747 });
748 pushDispatch(
749 dispatchMessageCommand({
750 commandId: yield* idAllocator.allocate.command({
751 fixtureName: input.scenario,
752 commandName: `steer-${messageIndex}`,
753 }),
754 ids,
755 modelSelection: input.modelSelection,
756 messageId: yield* idAllocator.allocate.message({
757 threadId: ids.threadId,
758 ordinal: messageIndex,
759 }),
760 text: step.text,
761 ...(step.attachments === undefined ? {} : { attachments: step.attachments }),
762 dispatchMode: {
763 type: "steer_active",
764 targetRunId: runIdFor(step.targetRunIndex),
765 },
766 }),
767 );
768 {
769 const nextStepType = input.fixtureInput.steps[stepIndex + 1]?.type;
770 if (
771 nextStepType !== "approve_next_runtime_request" &&
772 nextStepType !== "answer_next_user_input_request"
773 ) {
774 if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
775 steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
776 }
777 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
778 }
779 }
780 break;
781 case "restart":
782 messageIndex += 1;
783 steps.push({
784 type: "await_run_steerable",
785 threadId: ids.threadId,
786 runId: runIdFor(step.targetRunIndex),
787 });
788 pushDispatch(
789 dispatchMessageCommand({
790 commandId: yield* idAllocator.allocate.command({
791 fixtureName: input.scenario,
792 commandName: `restart-${messageIndex}`,
793 }),
794 ids,
795 modelSelection: input.modelSelection,
796 messageId: yield* idAllocator.allocate.message({
797 threadId: ids.threadId,
798 ordinal: messageIndex,
799 }),
800 text: step.text,
801 ...(step.attachments === undefined ? {} : { attachments: step.attachments }),
802 dispatchMode: {
803 type: "restart_active",
804 targetRunId: runIdFor(step.targetRunIndex),
805 },
806 }),
807 );
808 {
809 const nextStepType = input.fixtureInput.steps[stepIndex + 1]?.type;
810 if (
811 nextStepType !== "approve_next_runtime_request" &&
812 nextStepType !== "answer_next_user_input_request"
813 ) {
814 if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
815 steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
816 }
817 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
818 }
819 }
820 break;
821 case "interrupt":
822 steps.push({
823 type: "await_run_steerable",
824 threadId: ids.threadId,
825 runId: runIdFor(step.targetRunIndex),
826 });
827 if (step.waitForTurnItemType !== undefined) {
828 steps.push({
829 type: "await_run_turn_item",
830 threadId: ids.threadId,
831 runId: runIdFor(step.targetRunIndex),
832 itemType: step.waitForTurnItemType,
833 });
834 }
835 pushDispatch(
836 {
837 type: "run.interrupt",
838 commandId: yield* idAllocator.allocate.command({
839 fixtureName: input.scenario,
840 commandName: `interrupt-${step.targetRunIndex}`,
841 }),
842 threadId: ids.threadId,
843 runId: runIdFor(step.targetRunIndex),
844 },
845 { advanceClockAfter: false },
846 );
847 if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
848 steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
849 }
850 steps.push({ type: "advance_clock", duration: "1 millis" });
851 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
852 break;
853 case "stop_background_work":
854 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
855 steps.push({ type: "capture_shell_snapshot", key: "before-stop" });
856 pushDispatch(
857 {
858 type: "run.interrupt",
859 commandId: yield* idAllocator.allocate.command({
860 fixtureName: input.scenario,
861 commandName: `stop-background-work-${step.targetRunIndex}`,
862 }),
863 threadId: ids.threadId,
864 runId: runIdFor(step.targetRunIndex),
865 holdQueue: true,
866 },
867 { advanceClockAfter: false },
868 );
869 steps.push({ type: "await_no_background_work", threadId: ids.threadId });
870 break;
871 case "release_replay_gate_after_waiting":
872 steps.push({
873 type: "release_replay_gate_after_waiting",
874 label: step.label,
875 threadId: ids.threadId,
876 runId: runIdFor(step.targetRunIndex),
877 });
878 break;
879 case "advance_clock":
880 steps.push({ type: "advance_clock", duration: step.duration });
881 break;
882 case "rollback":
883 {
884 const scopeId = yield* idAllocator.allocate.checkpointScope({
885 threadId: ids.threadId,
886 name: step.checkpointScopeSuffix,
887 });
888 pushDispatch({
889 type: "checkpoint.rollback",
890 restoreFiles: false,
891 commandId: yield* idAllocator.allocate.command({
892 fixtureName: input.scenario,
893 commandName: `rollback-${step.checkpointSuffix}`,
894 }),
895 threadId: ids.threadId,
896 scopeId,
897 checkpointId: yield* idAllocator.allocate.checkpoint({
898 checkpointScopeId: scopeId,
899 name: step.checkpointSuffix,
900 }),
901 });
902 }
903 break;
904 }
905 }
906
907 if (activeRunDispatchKeys.size > 0) {
908 steps.push({ type: "await_all" });
909 steps.push({ type: "await_thread_idle", threadId: ids.threadId });
910 }
911
912 return {
913 commands,
914 steps,
915 projectionThreadIds: [ids.threadId],
916 };
917 });
918}
919
920export function projectionFor(
921 result: OrchestratorV2ScenarioResult,
922 scenario: string,
923): OrchestrationV2ThreadProjection {
924 const projections = [...result.projections.values()].filter(
925 (projection) => projection.thread.lineage.parentThreadId === null,
926 );
927
928 assert.equal(projections.length, 1, `expected one root projection for ${scenario}`);
929 const projection = projections[0];
930 assert.isDefined(projection, `missing projection for ${scenario}`);
931 return projection;
932}
933
934export function assertBaseProjection(input: {
935 readonly result: OrchestratorV2ScenarioResult;
936 readonly transcript: ProviderReplayTranscript;
937 readonly runCount: number;
938 readonly providerTurnCountAtLeast?: number;
939 readonly runStatuses?: ReadonlyArray<OrchestrationV2RunStatus>;
940}) {
941 const projection = projectionFor(input.result, input.transcript.scenario);
942
943 assert.equal(
944 projection.thread.providerInstanceId,
945 ProviderInstanceId.make(input.transcript.provider),
946 );
947 assert.lengthOf(projection.runs, input.runCount);
948 assert.isAtLeast(projection.providerThreads.length, 1);
949 assert.isAtLeast(
950 projection.providerTurns.length,
951 input.providerTurnCountAtLeast ?? input.runCount,
952 `expected provider turns; runs=${projection.runs.map((run) => `${run.id}:${run.status}`).join(",")}; sessions=${projection.providerSessions.map((session) => `${session.id}:${session.status}`).join(",")}; items=${projection.turnItems.map((item) => (item.type === "error" ? `${item.type}:${item.failure.message}` : item.type)).join(",")}`,
953 );
954 assert.isAtLeast(input.result.domainEvents.length, 1);
955 assert.deepEqual(
956 input.result.storedEvents.map((stored) => stored.sequence),
957 input.result.storedEvents.map((_, index) => index + 1),
958 );
959 assert.deepEqual(
960 input.result.storedEvents.map((stored) => stored.event.id),
961 input.result.domainEvents.map((event) => event.id),
962 );
963
964 if (input.runStatuses) {
965 assert.deepEqual(
966 projection.runs.map((run) => run.status),
967 input.runStatuses,
968 );
969 }
970}
971
972export function assertRunOrdinals(
973 projection: OrchestrationV2ThreadProjection,
974 expectedOrdinals: ReadonlyArray<number>,
975) {
976 assert.deepEqual(
977 projection.runs.map((run) => run.ordinal),
978 expectedOrdinals,
979 );
980}
981
982function assertRunsHaveRootNodes(projection: OrchestrationV2ThreadProjection) {
983 for (const run of projection.runs) {
984 assert.isNotNull(run.rootNodeId, `run ${run.id} must have a root node`);
985 assert.isTrue(
986 projection.nodes.some((node) => node.id === run.rootNodeId && node.kind === "root_turn"),
987 `run ${run.id} root node must exist`,
988 );
989 }
990}
991
992function assertRootNodesCountForRuns(projection: OrchestrationV2ThreadProjection) {
993 const rootNodes = projection.nodes.filter((node) => node.kind === "root_turn");
994 assert.isAtLeast(rootNodes.length, projection.runs.length);
995 for (const node of rootNodes) {
996 assert.equal(node.countsForRun, true, `root node ${node.id} must count for its app run`);
997 }
998}
999
1000function assertProviderTurnsReferenceNodes(projection: OrchestrationV2ThreadProjection) {
1001 for (const providerTurn of projection.providerTurns) {
1002 assert.isTrue(
1003 projection.nodes.some((node) => node.id === providerTurn.nodeId),
1004 `provider turn ${providerTurn.id} must reference an execution node`,
1005 );
1006 assert.isTrue(
1007 projection.providerThreads.some((thread) => thread.id === providerTurn.providerThreadId),
1008 `provider turn ${providerTurn.id} must reference a provider thread`,
1009 );
1010 }
1011}
1012
1013function assertTurnItemsAreOrdered(projection: OrchestrationV2ThreadProjection) {
1014 const ordinals = projection.turnItems.map((item) => item.ordinal);
1015 assert.deepEqual(
1016 ordinals,
1017 [...ordinals].toSorted((left, right) => left - right),
1018 );
1019}
1020
1021function assertTurnItemsReferenceProjection(projection: OrchestrationV2ThreadProjection) {
1022 for (const item of projection.turnItems) {
1023 if (item.runId !== null) {
1024 assert.isTrue(
1025 projection.runs.some((run) => run.id === item.runId),
1026 `turn item ${item.id} must reference an existing run`,
1027 );
1028 }
1029 if (item.nodeId !== null) {
1030 assert.isTrue(
1031 projection.nodes.some((node) => node.id === item.nodeId),
1032 `turn item ${item.id} must reference an existing node`,
1033 );
1034 }
1035 if (item.providerTurnId !== null) {
1036 assert.isTrue(
1037 projection.providerTurns.some((turn) => turn.id === item.providerTurnId),
1038 `turn item ${item.id} must reference an existing provider turn`,
1039 );
1040 }
1041 }
1042}
1043
1044export function assertVisibleTurnItemsMirrorLocalTurnItems(
1045 projection: OrchestrationV2ThreadProjection,
1046) {
1047 assert.lengthOf(
1048 projection.visibleTurnItems,
1049 projection.turnItems.length,
1050 "non-fork visible turn items must mirror local canonical turn items",
1051 );
1052
1053 for (const [index, item] of projection.turnItems.entries()) {
1054 const visibleItem = projection.visibleTurnItems[index];
1055 assert.isDefined(visibleItem, `missing visible turn item at position ${index}`);
1056 assert.equal(visibleItem.position, index);
1057 assert.equal(visibleItem.visibility, "local");
1058 assert.equal(visibleItem.sourceThreadId, item.threadId);
1059 assert.equal(visibleItem.sourceItemId, item.id);
1060 assert.deepEqual(visibleItem.item, item);
1061 }
1062}
1063
1064function assertMessagesReferenceProjection(projection: OrchestrationV2ThreadProjection) {
1065 for (const message of projection.messages) {
1066 if (message.runId !== null) {
1067 assert.isTrue(
1068 projection.runs.some((run) => run.id === message.runId),
1069 `message ${message.id} must reference an existing run`,
1070 );
1071 }
1072 if (message.nodeId !== null) {
1073 assert.isTrue(
1074 projection.nodes.some((node) => node.id === message.nodeId),
1075 `message ${message.id} must reference an existing node`,
1076 );
1077 }
1078 }
1079}
1080
1081function assertRuntimeRequestsReferenceProjection(projection: OrchestrationV2ThreadProjection) {
1082 for (const request of projection.runtimeRequests) {
1083 const requestNode = projection.nodes.find((node) => node.id === request.nodeId);
1084 assert.isTrue(
1085 requestNode !== undefined,
1086 `runtime request ${request.id} must reference an existing node`,
1087 );
1088 if (
1089 requestNode !== undefined &&
1090 (request.kind === "command" || request.kind === "file-read" || request.kind === "file-change")
1091 ) {
1092 assert.equal(
1093 requestNode.kind,
1094 "approval_request",
1095 `runtime request ${request.id} must reference an approval request node`,
1096 );
1097 }
1098 if (request.providerTurnId !== null) {
1099 assert.isTrue(
1100 projection.providerTurns.some((turn) => turn.id === request.providerTurnId),
1101 `runtime request ${request.id} must reference an existing provider turn`,
1102 );
1103 }
1104 }
1105}
1106
1107export function assertSemanticProjectionIntegrity(projection: OrchestrationV2ThreadProjection) {
1108 assertRunsHaveRootNodes(projection);
1109 assertRootNodesCountForRuns(projection);
1110 assertProviderTurnsReferenceNodes(projection);
1111 assertTurnItemsAreOrdered(projection);
1112 assertTurnItemsReferenceProjection(projection);
1113 assertMessagesReferenceProjection(projection);
1114 assertRuntimeRequestsReferenceProjection(projection);
1115}
1116
1117export function assertRunProviderTurnCardinality(input: {
1118 readonly projection: OrchestrationV2ThreadProjection;
1119 readonly rootRunCount: number;
1120 readonly providerTurnCountAtLeast?: number;
1121}) {
1122 assert.lengthOf(input.projection.runs, input.rootRunCount);
1123 assert.isAtLeast(
1124 input.projection.providerTurns.length,
1125 input.providerTurnCountAtLeast ?? input.rootRunCount,
1126 );
1127}
1128
1129export function assertNoExtraAppRunsForProviderChildren(input: {
1130 readonly projection: OrchestrationV2ThreadProjection;
1131 readonly expectedAppRuns: number;
1132}) {
1133 assert.lengthOf(
1134 input.projection.runs,
1135 input.expectedAppRuns,
1136 "provider child activity must not create additional app runs",
1137 );
1138}
1139
1140export function assertProviderNativeSubagentRootTurns(result: OrchestratorV2ScenarioResult) {
1141 const activity = (statuses: ReadonlyArray<OrchestrationV2ExecutionNode["status"]>) =>
1142 statuses
1143 .map((status) => (isOrchestrationV2WorkActive(status) ? "active" : status))
1144 .filter((status, index, all) => status !== all[index - 1]);
1145 for (const projection of result.projections.values()) {
1146 for (const subagent of projection.subagents) {
1147 if (subagent.origin !== "provider_native" || subagent.childThreadId === null) continue;
1148 const childThreadId = subagent.childThreadId;
1149 const child = result.projections.get(childThreadId);
1150 assert.isDefined(child, `missing child thread for subagent ${subagent.id}`);
1151 assert.equal(child.thread.creationSource, "provider");
1152 assert.deepEqual(child.thread.forkedFrom, { type: "node", nodeId: subagent.id });
1153 assert.lengthOf(child.runs, 0);
1154 const roots = child.nodes.filter((node) => node.kind === "root_turn");
1155 assert.isNotEmpty(roots, `child ${childThreadId} must have a root turn`);
1156 for (const root of roots) assert.isNull(root.runId);
1157
1158 const runByChildUpdate = new Map<string, string | undefined>();
1159 for (const event of result.domainEvents) {
1160 if (event.threadId !== childThreadId) continue;
1161 const update = `${event.type}:${JSON.stringify(event.payload)}`;
1162 const storedBy = runByChildUpdate.get(update);
1163 if (runByChildUpdate.has(update) && storedBy !== event.runId) {
1164 assert.fail(
1165 `child ${childThreadId} stored ${event.type} in ${storedBy} and ${event.runId}`,
1166 );
1167 }
1168 runByChildUpdate.set(update, event.runId);
1169 }
1170
1171 const rootEvents = result.domainEvents.flatMap((event, index) =>
1172 event.type === "node.updated" &&
1173 event.payload.threadId === childThreadId &&
1174 event.payload.kind === "root_turn"
1175 ? [{ index, status: event.payload.status }]
1176 : [],
1177 );
1178 const firstItemIndex = result.domainEvents.findIndex(
1179 (event) =>
1180 event.type === "turn-item.updated" &&
1181 event.payload.threadId === childThreadId &&
1182 event.payload.type !== "user_message",
1183 );
1184 assert.equal(rootEvents[0]?.status, "running");
1185 if (firstItemIndex !== -1) {
1186 assert.isBelow(
1187 rootEvents[0]?.index ?? Infinity,
1188 firstItemIndex,
1189 `child ${childThreadId} must be working before its first item`,
1190 );
1191 }
1192 const subagentStatuses = result.domainEvents.flatMap((event) =>
1193 event.type === "subagent.updated" && event.payload.id === subagent.id
1194 ? [event.payload.status]
1195 : [],
1196 );
1197 const rootActivity = activity(rootEvents.map((event) => event.status));
1198 const subagentActivity = activity(subagentStatuses);
1199 const wokenAfterEnd =
1200 child.subagents.length > 0 && rootActivity.length > subagentActivity.length;
1201 assert.deepEqual(
1202 wokenAfterEnd ? rootActivity.slice(0, subagentActivity.length) : rootActivity,
1203 subagentActivity,
1204 `child ${childThreadId} root turn must follow subagent ${subagent.id}`,
1205 );
1206 if (wokenAfterEnd) {
1207 assert.notEqual(rootActivity.at(-1), "active", `child ${childThreadId} must end its turns`);
1208 const childSubagentIds = new Set(child.subagents.map((nested) => nested.id));
1209 const nestedEndIndexes = result.domainEvents.flatMap((event, index) =>
1210 event.type === "subagent.updated" &&
1211 childSubagentIds.has(event.payload.id) &&
1212 !isOrchestrationV2WorkActive(event.payload.status)
1213 ? [index]
1214 : [],
1215 );
1216 const subagentEndIndex = result.domainEvents.findLastIndex(
1217 (event) =>
1218 event.type === "subagent.updated" &&
1219 event.payload.id === subagent.id &&
1220 !isOrchestrationV2WorkActive(event.payload.status),
1221 );
1222 const wakeStarts = rootEvents.filter(
1223 (event, position) =>
1224 event.index > subagentEndIndex &&
1225 isOrchestrationV2WorkActive(event.status) &&
1226 !isOrchestrationV2WorkActive(rootEvents[position - 1]?.status ?? "completed"),
1227 );
1228 assert.isNotEmpty(wakeStarts, `child ${childThreadId} woke without a new turn`);
1229 assert.isAtMost(
1230 wakeStarts.length,
1231 nestedEndIndexes.length,
1232 `child ${childThreadId} woke more often than its subagents ended`,
1233 );
1234 for (const wake of wakeStarts) {
1235 assert.isTrue(
1236 nestedEndIndexes.some((endIndex) => endIndex < wake.index),
1237 `child ${childThreadId} woke before any of its subagents ended`,
1238 );
1239 }
1240 }
1241 }
1242 }
1243}
1244
1245export function assertExecutionNodeKinds(
1246 projection: OrchestrationV2ThreadProjection,
1247 expectedKinds: ReadonlyArray<OrchestrationV2ExecutionNode["kind"]>,
1248) {
1249 const kinds = projection.nodes.map((node) => node.kind);
1250 for (const expectedKind of expectedKinds) {
1251 assert.include(kinds, expectedKind);
1252 }
1253}
1254
1255export function assertTurnItemTypes(
1256 projection: OrchestrationV2ThreadProjection,
1257 expectedTypes: ReadonlyArray<OrchestrationV2TurnItem["type"]>,
1258) {
1259 const actualTypes = projection.turnItems.map((item) => item.type);
1260 for (const expectedType of expectedTypes) {
1261 assert.include(actualTypes, expectedType);
1262 }
1263}
1264
1265export function assertTurnItemTypeSequence(
1266 projection: OrchestrationV2ThreadProjection,
1267 expectedTypes: ReadonlyArray<OrchestrationV2TurnItem["type"]>,
1268) {
1269 assert.deepEqual(
1270 projection.turnItems.map((item) => item.type),
1271 expectedTypes,
1272 );
1273}
1274
1275export function assertVisibleTurnItemTypeSequence(
1276 projection: OrchestrationV2ThreadProjection,
1277 expectedTypes: ReadonlyArray<OrchestrationV2TurnItem["type"]>,
1278) {
1279 assert.deepEqual(
1280 projection.visibleTurnItems.map((row) => row.item.type),
1281 expectedTypes,
1282 );
1283}
1284
1285export function assertAssistantTextIncludes(
1286 projection: OrchestrationV2ThreadProjection,
1287 expectedText: string,
1288) {
1289 assert.isTrue(
1290 projection.turnItems.some(
1291 (item) => item.type === "assistant_message" && item.text.includes(expectedText),
1292 ),
1293 `expected assistant output to include ${JSON.stringify(expectedText)}`,
1294 );
1295}
1296
1297export function assertRuntimeRequestCounts(
1298 projection: OrchestrationV2ThreadProjection,
1299 expected: { readonly total: number; readonly resolved?: number },
1300) {
1301 assert.lengthOf(projection.runtimeRequests, expected.total);
1302 if (expected.resolved !== undefined) {
1303 assert.equal(
1304 projection.runtimeRequests.filter((request) => request.status === "resolved").length,
1305 expected.resolved,
1306 );
1307 }
1308}
1309
1310function countReplayLabelsWithPrefix(transcript: ProviderReplayTranscript, prefix: string): number {
1311 return transcript.entries.filter(
1312 (entry) => entry.type !== "runtime_exit" && (entry.label?.startsWith(prefix) ?? false),
1313 ).length;
1314}
1315
1316export function assertReplayLabelPrefixCount(
1317 transcript: ProviderReplayTranscript,
1318 prefix: string,
1319 expected: number,
1320) {
1321 assert.equal(countReplayLabelsWithPrefix(transcript, prefix), expected);
1322}
1323
1324export function assertRuntimeRequestKinds(
1325 projection: OrchestrationV2ThreadProjection,
1326 expectedKinds: ReadonlyArray<string>,
1327) {
1328 assert.deepEqual(
1329 projection.runtimeRequests.map((request) => request.kind),
1330 expectedKinds,
1331 );
1332}
1333
1334export function assertAllRuntimeRequestsResolved(projection: OrchestrationV2ThreadProjection) {
1335 assert.deepEqual(
1336 projection.runtimeRequests.map((request) => request.status),
1337 projection.runtimeRequests.map(() => "resolved"),
1338 );
1339}
1340
1341export function assertConversationMessageRoles(
1342 projection: OrchestrationV2ThreadProjection,
1343 expectedRoles: ReadonlyArray<string>,
1344) {
1345 assert.deepEqual(
1346 projection.messages.map((message) => message.role),
1347 expectedRoles,
1348 );
1349}
1350
1351export function assertNoAcpClientFileOrTerminalRequests(transcript: ProviderReplayTranscript) {
1352 const frames = transcript.entries.flatMap((entry) =>
1353 entry.type === "runtime_exit"
1354 ? []
1355 : [entry.frame as { method?: unknown; params?: { clientCapabilities?: unknown } }],
1356 );
1357 assert.deepInclude(
1358 frames.find((frame) => frame.method === "initialize")?.params?.clientCapabilities ?? {},
1359 { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
1360 "T3 must not advertise client fs or terminals",
1361 );
1362 assert.deepEqual(
1363 frames.flatMap((frame) =>
1364 typeof frame.method === "string" && /^(fs|terminal)\//u.test(frame.method)
1365 ? [frame.method]
1366 : [],
1367 ),
1368 [],
1369 "the agent must not route file or terminal work through T3",
1370 );
1371}
1372
1373export function assertUserMessagesInclude(
1374 projection: OrchestrationV2ThreadProjection,
1375 expectedTexts: ReadonlyArray<string>,
1376) {
1377 for (const expectedText of expectedTexts) {
1378 assert.isTrue(
1379 projection.turnItems.some(
1380 (item) => item.type === "user_message" && item.text.includes(expectedText),
1381 ),
1382 `expected user input to include ${JSON.stringify(expectedText)}`,
1383 );
1384 }
1385}
1386
1387function assertUserMessagesExclude(
1388 projection: OrchestrationV2ThreadProjection,
1389 rejectedTexts: ReadonlyArray<string>,
1390) {
1391 for (const rejectedText of rejectedTexts) {
1392 assert.isFalse(
1393 projection.turnItems.some(
1394 (item) => item.type === "user_message" && item.text.includes(rejectedText),
1395 ),
1396 `expected user input to exclude ${JSON.stringify(rejectedText)}`,
1397 );
1398 }
1399}
1400
1401export function assertVisibleUserMessagesInclude(
1402 projection: OrchestrationV2ThreadProjection,
1403 expectedTexts: ReadonlyArray<string>,
1404) {
1405 for (const expectedText of expectedTexts) {
1406 assert.isTrue(
1407 projection.visibleTurnItems.some(
1408 (row) => row.item.type === "user_message" && row.item.text.includes(expectedText),
1409 ),
1410 `expected visible user input to include ${JSON.stringify(expectedText)}`,
1411 );
1412 }
1413}
1414
1415export function assertVisibleUserMessagesExclude(
1416 projection: OrchestrationV2ThreadProjection,
1417 rejectedTexts: ReadonlyArray<string>,
1418) {
1419 for (const rejectedText of rejectedTexts) {
1420 assert.isFalse(
1421 projection.visibleTurnItems.some(
1422 (row) => row.item.type === "user_message" && row.item.text.includes(rejectedText),
1423 ),
1424 `expected visible user input to exclude ${JSON.stringify(rejectedText)}`,
1425 );
1426 }
1427}
1428
1429export function assertUserMessageInputIntents(
1430 projection: OrchestrationV2ThreadProjection,
1431 expectedIntents: ReadonlyArray<OrchestrationV2UserMessageInputIntent>,
1432) {
1433 assert.deepEqual(
1434 projection.turnItems
1435 .filter((item) => item.type === "user_message")
1436 .map((item) => item.inputIntent),
1437 expectedIntents,
1438 );
1439}
1440
1441export function backgroundNotifications(projection: OrchestrationV2ThreadProjection) {
1442 return projection.turnItems.flatMap((item) =>
1443 item.type === "notification"
1444 ? [{ summary: item.summary, outcome: item.outcome, source: item.source }]
1445 : [],
1446 );
1447}