Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shared.ts

1,458 lines59.1 KB

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