Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 type ModelSelection,
6 type OrchestrationV2Command,
7 type OrchestrationV2ProviderCapabilities,
8 type OrchestrationV2ProviderSession,
9 type OrchestrationV2ProviderThread,
10 ProjectId,
11 ProviderInstanceId,
12 ProviderThreadId,
13 ProviderTurnId,
14 ThreadId,
15 TurnItemId,
16 ProviderDriverKind,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as PubSub from "effect/PubSub";
22import * as Ref from "effect/Ref";
23import * as Stream from "effect/Stream";
24import * as SqlClient from "effect/unstable/sql/SqlClient";
25
26import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
27import { ClaudeProviderCapabilitiesV2 } from "../Adapters/ClaudeAdapterV2.ts";
28import { CodexProviderCapabilitiesV2 } from "../Adapters/CodexAdapterV2.ts";
29import { CursorProviderCapabilitiesV2 } from "../Adapters/CursorAdapterV2.ts";
30import { layer as eventSinkLayer } from "../EventSink.ts";
31import { layer as eventStoreLayer } from "../EventStore.ts";
32import {
33 LegacyV1ThreadImporter,
34 layer as legacyV1ThreadImporterLayer,
35} from "../LegacyV1ThreadImporter.ts";
36import { OrchestratorV2 } from "../Orchestrator.ts";
37import {
38 ProjectionMaintenanceV2,
39 layer as projectionMaintenanceLayer,
40} from "../ProjectionMaintenance.ts";
41import { layer as projectionStoreLayer } from "../ProjectionStore.ts";
42import {
43 type ProviderAdapterV2Event,
44 ProviderAdapterProtocolError,
45 type ProviderAdapterV2Shape,
46} from "../ProviderAdapter.ts";
47import { makeLayer as makeProviderAdapterRegistryLayer } from "../ProviderAdapterRegistry.ts";
48import { makeProviderFailure } from "../ProviderFailure.ts";
49import {
50 CLAUDE_MODEL_SELECTION,
51 CODEX_MODEL_SELECTION,
52 CURSOR_MODEL_SELECTION,
53} from "./fixtures/shared.ts";
54import { makeOrchestratorV2ReplayLayerWithRegistry } from "./ProviderReplayHarness.ts";
55import { checkpointWorkspace } from "./ReplayFixtureWorkspace.ts";
56
57const threadId = ThreadId.make("thread:provider-switch");
58const projectId = ProjectId.make("project:provider-switch");
59const firstPrompt = "Respond with exactly: codex before switch";
60const claudePrompt = "Respond with exactly: claude switched response";
61const returnPrompt = "Respond with exactly: codex after return";
62const CODEX_DRIVER = ProviderDriverKind.make("codex");
63const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
64const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
65
66interface CapturedTurn {
67 readonly driver: ProviderDriverKind;
68 readonly threadId: ThreadId;
69 readonly providerThreadId: ProviderThreadId;
70 readonly text: string;
71}
72
73function unimplemented(driver: ProviderDriverKind, detail: string) {
74 return Effect.fail(new ProviderAdapterProtocolError({ driver, detail }));
75}
76
77function makeTestAdapter(input: {
78 readonly instanceId: ProviderInstanceId;
79 readonly driver: ProviderDriverKind;
80 readonly capabilities: OrchestrationV2ProviderCapabilities;
81 readonly modelSelection: ModelSelection;
82 readonly responseByRunOrdinal: Readonly<Record<number, string>>;
83 readonly responseByThreadId?: Readonly<Record<string, Readonly<Record<number, string>>>>;
84 readonly capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>;
85 readonly failResume?: boolean;
86 readonly failedRunOrdinals?: ReadonlySet<number>;
87}): ProviderAdapterV2Shape {
88 return {
89 instanceId: input.instanceId,
90 driver: input.driver,
91 getCapabilities: () => Effect.succeed(input.capabilities),
92 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
93 openSession: (sessionInput) =>
94 Effect.gen(function* () {
95 const events = yield* PubSub.unbounded<ProviderAdapterV2Event>();
96 const now = yield* DateTime.now;
97 const providerSession: OrchestrationV2ProviderSession = {
98 id: sessionInput.providerSessionId,
99 driver: input.driver,
100 providerInstanceId: input.instanceId,
101 status: "ready",
102 cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(),
103 model: input.modelSelection.model,
104 capabilities: input.capabilities,
105 createdAt: now,
106 updatedAt: now,
107 lastError: null,
108 };
109
110 return {
111 instanceId: input.instanceId,
112 driver: input.driver,
113 providerSessionId: sessionInput.providerSessionId,
114 providerSession,
115 events: Stream.fromPubSub(events),
116 ensureThread: (threadInput) =>
117 Effect.gen(function* () {
118 const createdAt = yield* DateTime.now;
119 const nativeThreadId = `${input.driver}:${threadInput.threadId}`;
120 return {
121 id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`),
122 driver: input.driver,
123 providerInstanceId: input.instanceId,
124 providerSessionId: sessionInput.providerSessionId,
125 appThreadId: threadInput.threadId,
126 ownerNodeId: null,
127 nativeThreadRef: {
128 driver: input.driver,
129 nativeId: nativeThreadId,
130 strength: "strong",
131 },
132 nativeConversationHeadRef: null,
133 status: "idle",
134 firstRunOrdinal: null,
135 lastRunOrdinal: null,
136 handoffIds: [],
137 forkedFrom: null,
138 createdAt,
139 updatedAt: createdAt,
140 } satisfies OrchestrationV2ProviderThread;
141 }),
142 resumeThread: ({ providerThread }) =>
143 input.failResume
144 ? unimplemented(input.driver, "simulated native resume failure")
145 : Effect.succeed(providerThread),
146 startTurn: (turnInput) =>
147 Effect.gen(function* () {
148 yield* Effect.yieldNow;
149 yield* Ref.update(input.capturedTurns, (turns) => [
150 ...turns,
151 {
152 driver: input.driver,
153 threadId: turnInput.threadId,
154 providerThreadId: turnInput.providerThread.id,
155 text: turnInput.message.text,
156 },
157 ]);
158 const eventTime = yield* DateTime.now;
159 const providerTurnId = ProviderTurnId.make(
160 `provider-turn:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}`,
161 );
162 if (input.failedRunOrdinals?.has(turnInput.runOrdinal) === true) {
163 yield* PubSub.publish(events, {
164 type: "provider_turn.updated",
165 driver: input.driver,
166 providerTurn: {
167 id: providerTurnId,
168 providerThreadId: turnInput.providerThread.id,
169 nodeId: turnInput.rootNodeId,
170 runAttemptId: turnInput.attemptId,
171 nativeTurnRef: {
172 driver: input.driver,
173 nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
174 strength: "strong",
175 },
176 ordinal: turnInput.runOrdinal,
177 status: "failed",
178 startedAt: eventTime,
179 completedAt: eventTime,
180 },
181 });
182 yield* PubSub.publish(events, {
183 type: "turn.terminal",
184 driver: input.driver,
185 providerThreadId: turnInput.providerThread.id,
186 providerTurnId,
187 runOrdinal: turnInput.runOrdinal,
188 failureItemOrdinal: turnInput.runOrdinal * 100 + 1,
189 status: "failed",
190 failure: makeProviderFailure({
191 message: "Simulated provider failure.",
192 code: "simulated_failure",
193 class: "provider_error",
194 }),
195 threadDisposition: "reusable",
196 });
197 return;
198 }
199 const response =
200 input.responseByThreadId?.[turnInput.threadId]?.[turnInput.runOrdinal] ??
201 input.responseByRunOrdinal[turnInput.runOrdinal] ??
202 `${input.driver} response for run ${turnInput.runOrdinal}`;
203 const providerEvents: ReadonlyArray<ProviderAdapterV2Event> = [
204 {
205 type: "provider_turn.updated",
206 driver: input.driver,
207 providerTurn: {
208 id: providerTurnId,
209 providerThreadId: turnInput.providerThread.id,
210 nodeId: turnInput.rootNodeId,
211 runAttemptId: turnInput.attemptId,
212 nativeTurnRef: {
213 driver: input.driver,
214 nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
215 strength: "strong",
216 },
217 ordinal: turnInput.runOrdinal,
218 status: "completed",
219 startedAt: eventTime,
220 completedAt: eventTime,
221 },
222 },
223 {
224 type: "turn_item.updated",
225 driver: input.driver,
226 turnItem: {
227 id: TurnItemId.make(
228 `turn-item:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
229 ),
230 threadId: turnInput.threadId,
231 runId: turnInput.runId,
232 nodeId: turnInput.rootNodeId,
233 providerThreadId: turnInput.providerThread.id,
234 providerTurnId,
235 nativeItemRef: null,
236 parentItemId: null,
237 ordinal: turnInput.runOrdinal * 100 + 1,
238 status: "completed",
239 title: null,
240 startedAt: eventTime,
241 completedAt: eventTime,
242 updatedAt: eventTime,
243 type: "assistant_message",
244 messageId: MessageId.make(
245 `message:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
246 ),
247 text: response,
248 streaming: false,
249 },
250 },
251 {
252 type: "turn.terminal",
253 driver: input.driver,
254 providerThreadId: turnInput.providerThread.id,
255 providerTurnId,
256 runOrdinal: turnInput.runOrdinal,
257 status: "completed",
258 failure: null,
259 threadDisposition: "reusable",
260 },
261 ];
262 for (const event of providerEvents) {
263 yield* PubSub.publish(events, event);
264 }
265 }),
266 steerTurn: () => Effect.void,
267 interruptTurn: () => Effect.void,
268 respondToRuntimeRequest: () => Effect.void,
269 readThreadSnapshot: () =>
270 unimplemented(input.driver, "readThreadSnapshot unused in provider switch test"),
271 rollbackThread: () =>
272 unimplemented(input.driver, "rollbackThread unused in provider switch test"),
273 forkThread: () =>
274 unimplemented(input.driver, "forkThread unused in provider switch test"),
275 };
276 }),
277 };
278}
279
280const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
281 targetThreadId: ThreadId,
282) {
283 const orchestrator = yield* OrchestratorV2;
284 for (let attempt = 0; attempt < 1_000; attempt += 1) {
285 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
286 if (
287 projection.runs.every(
288 (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
289 )
290 ) {
291 return projection;
292 }
293 yield* Effect.sleep("5 millis");
294 }
295 return yield* Effect.die(new Error("Provider switch test timed out waiting for idle"));
296});
297
298describe("orchestration v2 provider switching", () => {
299 it.live("reissues imported v1 context when switching after the first provider fails", () =>
300 Effect.scoped(
301 Effect.gen(function* () {
302 const importedThreadId = ThreadId.make("thread:provider-switch:legacy-import");
303 const importedProjectId = ProjectId.make("project:provider-switch:legacy-import");
304 const failedPrompt = "This first provider attempt should fail.";
305 const recoveryPrompt = "What was the imported release marker?";
306 const cwd = yield* checkpointWorkspace("provider-switch-legacy-import");
307 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
308 const registryLayer = makeProviderAdapterRegistryLayer([
309 makeTestAdapter({
310 instanceId: ProviderInstanceId.make("codex"),
311 driver: CODEX_DRIVER,
312 capabilities: CodexProviderCapabilitiesV2,
313 modelSelection: CODEX_MODEL_SELECTION,
314 responseByRunOrdinal: {},
315 capturedTurns,
316 failedRunOrdinals: new Set([1]),
317 }),
318 makeTestAdapter({
319 instanceId: ProviderInstanceId.make("claudeAgent"),
320 driver: CLAUDE_DRIVER,
321 capabilities: ClaudeProviderCapabilitiesV2,
322 modelSelection: CLAUDE_MODEL_SELECTION,
323 responseByRunOrdinal: { 2: "The imported release marker is violet." },
324 capturedTurns,
325 }),
326 ]);
327 const databaseLayer = SqlitePersistenceMemory;
328 const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer));
329 const projectionStoreProvided = projectionStoreLayer.pipe(
330 Layer.provideMerge(databaseLayer),
331 );
332 const storesProvided = Layer.mergeAll(
333 databaseLayer,
334 eventStoreProvided,
335 projectionStoreProvided,
336 );
337 const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesProvided));
338 const importerProvided = legacyV1ThreadImporterLayer.pipe(
339 Layer.provide(Layer.mergeAll(storesProvided, eventSinkProvided)),
340 );
341 const maintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesProvided));
342 const orchestratorProvided = makeOrchestratorV2ReplayLayerWithRegistry(
343 {
344 name: "provider-switch-legacy-import",
345 runtimePolicyOverride: {
346 cwd,
347 approvalPolicy: "never",
348 sandboxPolicy: {
349 type: "readOnly",
350 access: { type: "fullAccess" },
351 networkAccess: false,
352 },
353 },
354 },
355 registryLayer,
356 { databaseLayer },
357 );
358 const testLayer = Layer.mergeAll(
359 storesProvided,
360 importerProvided,
361 maintenanceProvided,
362 orchestratorProvided,
363 );
364
365 const projection = yield* Effect.gen(function* () {
366 const sql = yield* SqlClient.SqlClient;
367 const importer = yield* LegacyV1ThreadImporter;
368 const maintenance = yield* ProjectionMaintenanceV2;
369 const orchestrator = yield* OrchestratorV2;
370
371 yield* sql`
372 INSERT INTO projection_projects (
373 project_id,
374 title,
375 workspace_root,
376 default_model_selection_json,
377 scripts_json,
378 created_at,
379 updated_at,
380 deleted_at
381 ) VALUES (
382 ${importedProjectId},
383 'Imported provider switch project',
384 ${cwd},
385 '{"instanceId":"codex","model":"gpt-5.4"}',
386 '[]',
387 '2026-01-01T00:00:00.000Z',
388 '2026-01-01T00:00:00.000Z',
389 NULL
390 )
391 `;
392 yield* sql`
393 INSERT INTO projection_threads (
394 thread_id,
395 project_id,
396 title,
397 model_selection_json,
398 runtime_mode,
399 interaction_mode,
400 branch,
401 worktree_path,
402 latest_turn_id,
403 created_at,
404 updated_at,
405 archived_at,
406 settled_override,
407 settled_at,
408 deleted_at
409 ) VALUES (
410 ${importedThreadId},
411 ${importedProjectId},
412 'Imported provider switch thread',
413 '{"instanceId":"codex","model":"gpt-5.4"}',
414 'full-access',
415 'default',
416 'main',
417 ${cwd},
418 NULL,
419 '2026-01-01T00:00:00.000Z',
420 '2026-01-01T00:00:00.000Z',
421 NULL,
422 NULL,
423 NULL,
424 NULL
425 )
426 `;
427 yield* sql`
428 INSERT INTO projection_thread_messages (
429 message_id,
430 thread_id,
431 turn_id,
432 role,
433 text,
434 attachments_json,
435 is_streaming,
436 created_at,
437 updated_at
438 ) VALUES
439 (
440 'message:provider-switch:legacy-import:user',
441 ${importedThreadId},
442 NULL,
443 'user',
444 'Remember that the imported release marker is violet.',
445 '[]',
446 0,
447 '2026-01-01T01:00:00.000Z',
448 '2026-01-01T01:00:00.000Z'
449 ),
450 (
451 'message:provider-switch:legacy-import:assistant',
452 ${importedThreadId},
453 NULL,
454 'assistant',
455 'I will remember violet.',
456 '[]',
457 0,
458 '2026-01-01T01:01:00.000Z',
459 '2026-01-01T01:01:00.000Z'
460 )
461 `;
462
463 yield* importer.reconcileShells;
464 yield* maintenance.rebuild;
465 yield* importer.ensureTranscript(importedThreadId);
466
467 yield* orchestrator.dispatch({
468 type: "message.dispatch",
469 createdBy: "user",
470 creationSource: "web",
471 commandId: CommandId.make("command:provider-switch:legacy-import:failed"),
472 threadId: importedThreadId,
473 messageId: MessageId.make("message:provider-switch:legacy-import:failed"),
474 text: failedPrompt,
475 attachments: [],
476 modelSelection: CODEX_MODEL_SELECTION,
477 dispatchMode: { type: "start_immediately" },
478 });
479 yield* waitForIdle(importedThreadId);
480 yield* orchestrator.dispatch({
481 type: "message.dispatch",
482 createdBy: "user",
483 creationSource: "web",
484 commandId: CommandId.make("command:provider-switch:legacy-import:recovery"),
485 threadId: importedThreadId,
486 messageId: MessageId.make("message:provider-switch:legacy-import:recovery"),
487 text: recoveryPrompt,
488 attachments: [],
489 modelSelection: CLAUDE_MODEL_SELECTION,
490 dispatchMode: { type: "start_immediately" },
491 });
492 return yield* waitForIdle(importedThreadId);
493 }).pipe(Effect.provide(testLayer));
494
495 const turns = yield* Ref.get(capturedTurns);
496 assert.deepEqual(
497 projection.runs.map((run) => [run.providerInstanceId, run.status]),
498 [
499 ["codex", "failed"],
500 ["claudeAgent", "completed"],
501 ],
502 );
503 assert.deepEqual(
504 projection.contextHandoffs.map((handoff) => [
505 handoff.targetRunId,
506 handoff.strategy,
507 handoff.status,
508 ]),
509 [
510 [projection.runs[0]?.id, "manual_context", "ready"],
511 [projection.runs[1]?.id, "manual_context", "ready"],
512 ],
513 );
514 assert.equal(projection.runs[1]?.contextHandoffId, projection.contextHandoffs[1]?.id);
515 assert.include(turns[1]?.text ?? "", "Context handoff (manual_context):");
516 assert.include(turns[1]?.text ?? "", "imported release marker is violet");
517 assert.include(turns[1]?.text ?? "", "I will remember violet.");
518 assert.include(turns[1]?.text ?? "", recoveryPrompt);
519 assert.notInclude(turns[1]?.text ?? "", failedPrompt);
520 }),
521 ),
522 );
523
524 it.live("uses portable fallback when native resume fails after a provider switch", () =>
525 Effect.scoped(
526 Effect.gen(function* () {
527 const cwd = yield* checkpointWorkspace("provider-switch");
528 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
529 const registryLayer = makeProviderAdapterRegistryLayer([
530 makeTestAdapter({
531 instanceId: ProviderInstanceId.make("codex"),
532 driver: CODEX_DRIVER,
533 capabilities: CodexProviderCapabilitiesV2,
534 modelSelection: CODEX_MODEL_SELECTION,
535 responseByRunOrdinal: {
536 1: "codex before switch",
537 3: "codex after return",
538 },
539 capturedTurns,
540 failResume: true,
541 }),
542 makeTestAdapter({
543 instanceId: ProviderInstanceId.make("claudeAgent"),
544 driver: CLAUDE_DRIVER,
545 capabilities: ClaudeProviderCapabilitiesV2,
546 modelSelection: CLAUDE_MODEL_SELECTION,
547 responseByRunOrdinal: { 2: "claude switched response" },
548 capturedTurns,
549 }),
550 ]);
551 const commands = [
552 {
553 type: "thread.create",
554 createdBy: "user",
555 creationSource: "web",
556 commandId: CommandId.make("command:provider-switch:create"),
557 threadId,
558 projectId,
559 title: "Provider switch",
560 modelSelection: CODEX_MODEL_SELECTION,
561 runtimeMode: "full-access",
562 interactionMode: "default",
563 branch: null,
564 worktreePath: null,
565 },
566 {
567 type: "message.dispatch",
568 createdBy: "user",
569 creationSource: "web",
570 commandId: CommandId.make("command:provider-switch:codex"),
571 threadId,
572 messageId: MessageId.make("message:provider-switch:codex"),
573 text: firstPrompt,
574 attachments: [],
575 modelSelection: CODEX_MODEL_SELECTION,
576 dispatchMode: { type: "start_immediately" },
577 },
578 {
579 type: "message.dispatch",
580 createdBy: "user",
581 creationSource: "web",
582 commandId: CommandId.make("command:provider-switch:claude"),
583 threadId,
584 messageId: MessageId.make("message:provider-switch:claude"),
585 text: claudePrompt,
586 attachments: [],
587 modelSelection: CLAUDE_MODEL_SELECTION,
588 dispatchMode: { type: "start_immediately" },
589 },
590 {
591 type: "message.dispatch",
592 createdBy: "user",
593 creationSource: "web",
594 commandId: CommandId.make("command:provider-switch:return"),
595 threadId,
596 messageId: MessageId.make("message:provider-switch:return"),
597 text: returnPrompt,
598 attachments: [],
599 modelSelection: CODEX_MODEL_SELECTION,
600 dispatchMode: { type: "start_immediately" },
601 },
602 ] satisfies ReadonlyArray<OrchestrationV2Command>;
603
604 const projection = yield* Effect.gen(function* () {
605 const orchestrator = yield* OrchestratorV2;
606 yield* orchestrator.dispatch(commands[0]!);
607 yield* orchestrator.dispatch(commands[1]!);
608 yield* waitForIdle(threadId);
609 yield* orchestrator.dispatch(commands[2]!);
610 yield* waitForIdle(threadId);
611 yield* orchestrator.dispatch(commands[3]!);
612 return yield* waitForIdle(threadId);
613 }).pipe(
614 Effect.provide(
615 makeOrchestratorV2ReplayLayerWithRegistry(
616 {
617 name: "provider-switch",
618 runtimePolicyOverride: {
619 cwd,
620 approvalPolicy: "never",
621 sandboxPolicy: {
622 type: "readOnly",
623 access: { type: "fullAccess" },
624 networkAccess: false,
625 },
626 },
627 },
628 registryLayer,
629 ),
630 ),
631 );
632 const turns = yield* Ref.get(capturedTurns);
633
634 assert.deepEqual(
635 projection.runs.map((run) => [run.providerInstanceId, run.status]),
636 [
637 ["codex", "completed"],
638 ["claudeAgent", "completed"],
639 ["codex", "completed"],
640 ],
641 );
642 assert.lengthOf(projection.providerThreads, 2);
643 assert.equal(projection.runs[0]?.providerThreadId, projection.runs[2]?.providerThreadId);
644 assert.notEqual(projection.runs[0]?.providerThreadId, projection.runs[1]?.providerThreadId);
645 assert.deepEqual(
646 projection.contextHandoffs.map((handoff) => handoff.strategy),
647 ["full_thread_summary", "delta_since_target_last_seen"],
648 );
649 assert.deepEqual(
650 projection.contextTransfers.map((transfer) => [
651 transfer.type,
652 transfer.status,
653 transfer.resolution?.strategy,
654 ]),
655 [
656 ["provider_handoff", "consumed", "portable_context"],
657 ["provider_handoff", "consumed", "delta_context"],
658 ],
659 );
660 assert.deepEqual(
661 projection.turnItems
662 .filter((item) => item.type === "user_message")
663 .map((item) => item.text),
664 [firstPrompt, claudePrompt, returnPrompt],
665 );
666 assert.deepEqual(
667 projection.providerThreads.map((providerThread) => [
668 providerThread.driver,
669 providerThread.status,
670 providerThread.handoffIds.length,
671 ]),
672 [
673 ["codex", "idle", 1],
674 ["claudeAgent", "idle", 1],
675 ],
676 );
677 assert.equal(turns[0]?.text, firstPrompt);
678 assert.include(turns[1]?.text ?? "", "Context handoff (full_thread_summary):");
679 assert.include(turns[1]?.text ?? "", "codex before switch");
680 assert.include(turns[1]?.text ?? "", claudePrompt);
681 assert.include(turns[2]?.text ?? "", "Context handoff (delta_since_target_last_seen):");
682 assert.include(turns[2]?.text ?? "", "claude switched response");
683 assert.include(turns[2]?.text ?? "", returnPrompt);
684 assert.notInclude(turns[2]?.text ?? "", "codex before switch");
685 assert.equal(turns[0]?.providerThreadId, turns[2]?.providerThreadId);
686 }),
687 ),
688 );
689
690 it.live("resolves a Claude fork into portable Codex context on first dispatch", () =>
691 Effect.scoped(
692 Effect.gen(function* () {
693 const sourceThreadId = ThreadId.make("thread:cross-provider-fork:source");
694 const targetThreadId = ThreadId.make("thread:cross-provider-fork:target");
695 const sourcePrompt = "Remember that the release color is violet.";
696 const targetPrompt = "What release color did we choose?";
697 const cwd = yield* checkpointWorkspace("cross-provider-fork");
698 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
699 const registryLayer = makeProviderAdapterRegistryLayer([
700 makeTestAdapter({
701 instanceId: ProviderInstanceId.make("codex"),
702 driver: CODEX_DRIVER,
703 capabilities: CodexProviderCapabilitiesV2,
704 modelSelection: CODEX_MODEL_SELECTION,
705 responseByRunOrdinal: { 1: "The release color is violet." },
706 capturedTurns,
707 }),
708 makeTestAdapter({
709 instanceId: ProviderInstanceId.make("claudeAgent"),
710 driver: CLAUDE_DRIVER,
711 capabilities: ClaudeProviderCapabilitiesV2,
712 modelSelection: CLAUDE_MODEL_SELECTION,
713 responseByRunOrdinal: { 1: "I will remember violet." },
714 capturedTurns,
715 }),
716 ]);
717 const commands = [
718 {
719 type: "thread.create",
720 createdBy: "user",
721 creationSource: "web",
722 commandId: CommandId.make("command:cross-provider-fork:create"),
723 threadId: sourceThreadId,
724 projectId,
725 title: "Cross-provider fork source",
726 modelSelection: CLAUDE_MODEL_SELECTION,
727 runtimeMode: "full-access",
728 interactionMode: "default",
729 branch: null,
730 worktreePath: null,
731 },
732 {
733 type: "message.dispatch",
734 createdBy: "user",
735 creationSource: "web",
736 commandId: CommandId.make("command:cross-provider-fork:source"),
737 threadId: sourceThreadId,
738 messageId: MessageId.make("message:cross-provider-fork:source"),
739 text: sourcePrompt,
740 attachments: [],
741 modelSelection: CLAUDE_MODEL_SELECTION,
742 dispatchMode: { type: "start_immediately" },
743 },
744 {
745 type: "thread.fork",
746 createdBy: "user",
747 creationSource: "web",
748 commandId: CommandId.make("command:cross-provider-fork:fork"),
749 sourceThreadId,
750 targetThreadId,
751 sourcePoint: { type: "latest_stable" },
752 title: "Cross-provider fork target",
753 },
754 {
755 type: "message.dispatch",
756 createdBy: "user",
757 creationSource: "web",
758 commandId: CommandId.make("command:cross-provider-fork:target"),
759 threadId: targetThreadId,
760 messageId: MessageId.make("message:cross-provider-fork:target"),
761 text: targetPrompt,
762 attachments: [],
763 modelSelection: CODEX_MODEL_SELECTION,
764 dispatchMode: { type: "start_immediately" },
765 },
766 ] satisfies ReadonlyArray<OrchestrationV2Command>;
767
768 const targetProjection = yield* Effect.gen(function* () {
769 const orchestrator = yield* OrchestratorV2;
770 yield* orchestrator.dispatch(commands[0]!);
771 yield* orchestrator.dispatch(commands[1]!);
772 yield* waitForIdle(sourceThreadId);
773 yield* orchestrator.dispatch(commands[2]!);
774 yield* orchestrator.dispatch(commands[3]!);
775 return yield* waitForIdle(targetThreadId);
776 }).pipe(
777 Effect.provide(
778 makeOrchestratorV2ReplayLayerWithRegistry(
779 {
780 name: "cross-provider-fork",
781 runtimePolicyOverride: {
782 cwd,
783 approvalPolicy: "never",
784 sandboxPolicy: {
785 type: "readOnly",
786 access: { type: "fullAccess" },
787 networkAccess: false,
788 },
789 },
790 },
791 registryLayer,
792 ),
793 ),
794 );
795 const turns = yield* Ref.get(capturedTurns);
796 const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
797
798 assert.deepEqual(
799 targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
800 [["codex", "completed"]],
801 );
802 assert.lengthOf(targetProjection.providerThreads, 1);
803 assert.equal(targetProjection.providerThreads[0]?.driver, "codex");
804 assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
805 assert.deepEqual(
806 targetProjection.contextTransfers.map((transfer) => [
807 transfer.type,
808 transfer.status,
809 transfer.resolution?.strategy,
810 ]),
811 [["fork", "consumed", "portable_context"]],
812 );
813 assert.deepEqual(
814 targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
815 ["full_thread_summary"],
816 );
817 assert.equal(
818 targetProjection.runs[0]?.contextHandoffId,
819 targetProjection.contextHandoffs[0]?.id,
820 );
821 assert.include(targetTurn?.text ?? "", "Context handoff (full_thread_summary):");
822 assert.include(targetTurn?.text ?? "", sourcePrompt);
823 assert.include(targetTurn?.text ?? "", "I will remember violet.");
824 assert.include(targetTurn?.text ?? "", targetPrompt);
825 }),
826 ),
827 );
828
829 it.live("resolves a same-provider Cursor fork with portable context", () =>
830 Effect.scoped(
831 Effect.gen(function* () {
832 const sourceThreadId = ThreadId.make("thread:cursor-portable-fork:source");
833 const targetThreadId = ThreadId.make("thread:cursor-portable-fork:target");
834 const sourcePrompt = "Remember that the deployment marker is indigo.";
835 const sourceResponse = "I will remember indigo.";
836 const targetPrompt = "What deployment marker did we choose?";
837 const cwd = yield* checkpointWorkspace("cursor-portable-fork");
838 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
839 const registryLayer = makeProviderAdapterRegistryLayer([
840 makeTestAdapter({
841 instanceId: ProviderInstanceId.make("cursor"),
842 driver: CURSOR_DRIVER,
843 capabilities: CursorProviderCapabilitiesV2,
844 modelSelection: CURSOR_MODEL_SELECTION,
845 responseByRunOrdinal: {},
846 responseByThreadId: {
847 [sourceThreadId]: { 1: sourceResponse },
848 [targetThreadId]: { 1: "The deployment marker is indigo." },
849 },
850 capturedTurns,
851 }),
852 ]);
853 const commands = [
854 {
855 type: "thread.create",
856 createdBy: "user",
857 creationSource: "web",
858 commandId: CommandId.make("command:cursor-portable-fork:create"),
859 threadId: sourceThreadId,
860 projectId,
861 title: "Cursor portable fork source",
862 modelSelection: CURSOR_MODEL_SELECTION,
863 runtimeMode: "full-access",
864 interactionMode: "default",
865 branch: null,
866 worktreePath: null,
867 },
868 {
869 type: "message.dispatch",
870 createdBy: "user",
871 creationSource: "web",
872 commandId: CommandId.make("command:cursor-portable-fork:source"),
873 threadId: sourceThreadId,
874 messageId: MessageId.make("message:cursor-portable-fork:source"),
875 text: sourcePrompt,
876 attachments: [],
877 modelSelection: CURSOR_MODEL_SELECTION,
878 dispatchMode: { type: "start_immediately" },
879 },
880 {
881 type: "thread.fork",
882 createdBy: "user",
883 creationSource: "web",
884 commandId: CommandId.make("command:cursor-portable-fork:fork"),
885 sourceThreadId,
886 targetThreadId,
887 sourcePoint: { type: "latest_stable" },
888 title: "Cursor portable fork target",
889 },
890 {
891 type: "message.dispatch",
892 createdBy: "user",
893 creationSource: "web",
894 commandId: CommandId.make("command:cursor-portable-fork:target"),
895 threadId: targetThreadId,
896 messageId: MessageId.make("message:cursor-portable-fork:target"),
897 text: targetPrompt,
898 attachments: [],
899 modelSelection: CURSOR_MODEL_SELECTION,
900 dispatchMode: { type: "start_immediately" },
901 },
902 ] satisfies ReadonlyArray<OrchestrationV2Command>;
903
904 const targetProjection = yield* Effect.gen(function* () {
905 const orchestrator = yield* OrchestratorV2;
906 yield* orchestrator.dispatch(commands[0]!);
907 yield* orchestrator.dispatch(commands[1]!);
908 yield* waitForIdle(sourceThreadId);
909 yield* orchestrator.dispatch(commands[2]!);
910 yield* orchestrator.dispatch(commands[3]!);
911 return yield* waitForIdle(targetThreadId);
912 }).pipe(
913 Effect.provide(
914 makeOrchestratorV2ReplayLayerWithRegistry(
915 {
916 name: "cursor-portable-fork",
917 runtimePolicyOverride: {
918 cwd,
919 approvalPolicy: "never",
920 sandboxPolicy: {
921 type: "readOnly",
922 access: { type: "fullAccess" },
923 networkAccess: false,
924 },
925 },
926 },
927 registryLayer,
928 ),
929 ),
930 );
931 const turns = yield* Ref.get(capturedTurns);
932 const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
933
934 assert.deepEqual(
935 targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
936 [["cursor", "completed"]],
937 );
938 assert.lengthOf(targetProjection.providerThreads, 1);
939 assert.equal(targetProjection.providerThreads[0]?.driver, "cursor");
940 assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
941 assert.deepEqual(
942 targetProjection.contextTransfers.map((transfer) => [
943 transfer.type,
944 transfer.status,
945 transfer.resolution?.strategy,
946 ]),
947 [["fork", "consumed", "portable_context"]],
948 );
949 assert.deepEqual(
950 targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
951 ["full_thread_summary"],
952 );
953 assert.include(targetTurn?.text ?? "", "Context handoff (full_thread_summary):");
954 assert.include(targetTurn?.text ?? "", sourcePrompt);
955 assert.include(targetTurn?.text ?? "", sourceResponse);
956 assert.include(targetTurn?.text ?? "", targetPrompt);
957 }),
958 ),
959 );
960
961 it.live("switches providers while consuming a pending cross-provider merge-back", () =>
962 Effect.scoped(
963 Effect.gen(function* () {
964 const sourceThreadId = ThreadId.make("thread:cross-provider-merge:source");
965 const forkThreadId = ThreadId.make("thread:cross-provider-merge:fork");
966 const firstSourcePrompt = "Remember that the first source marker is amber.";
967 const secondSourcePrompt = "Remember that the second source marker is violet.";
968 const forkPrompt = "Remember that the fork marker is cobalt.";
969 const mergePrompt = "Report all three remembered markers.";
970 const cwd = yield* checkpointWorkspace("cross-provider-merge");
971 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
972 const registryLayer = makeProviderAdapterRegistryLayer([
973 makeTestAdapter({
974 instanceId: ProviderInstanceId.make("codex"),
975 driver: CODEX_DRIVER,
976 capabilities: CodexProviderCapabilitiesV2,
977 modelSelection: CODEX_MODEL_SELECTION,
978 responseByRunOrdinal: {},
979 responseByThreadId: {
980 [sourceThreadId]: {
981 1: "I will remember amber.",
982 3: "The markers are amber, violet, and cobalt.",
983 },
984 [forkThreadId]: {
985 1: "I will remember cobalt.",
986 },
987 },
988 capturedTurns,
989 }),
990 makeTestAdapter({
991 instanceId: ProviderInstanceId.make("claudeAgent"),
992 driver: CLAUDE_DRIVER,
993 capabilities: ClaudeProviderCapabilitiesV2,
994 modelSelection: CLAUDE_MODEL_SELECTION,
995 responseByRunOrdinal: { 2: "I will remember violet." },
996 capturedTurns,
997 }),
998 ]);
999 const commands = [
1000 {
1001 type: "thread.create",
1002 createdBy: "user",
1003 creationSource: "web",
1004 commandId: CommandId.make("command:cross-provider-merge:create"),
1005 threadId: sourceThreadId,
1006 projectId,
1007 title: "Cross-provider merge source",
1008 modelSelection: CODEX_MODEL_SELECTION,
1009 runtimeMode: "full-access",
1010 interactionMode: "default",
1011 branch: null,
1012 worktreePath: null,
1013 },
1014 {
1015 type: "message.dispatch",
1016 createdBy: "user",
1017 creationSource: "web",
1018 commandId: CommandId.make("command:cross-provider-merge:first-source"),
1019 threadId: sourceThreadId,
1020 messageId: MessageId.make("message:cross-provider-merge:first-source"),
1021 text: firstSourcePrompt,
1022 attachments: [],
1023 modelSelection: CODEX_MODEL_SELECTION,
1024 dispatchMode: { type: "start_immediately" },
1025 },
1026 {
1027 type: "message.dispatch",
1028 createdBy: "user",
1029 creationSource: "web",
1030 commandId: CommandId.make("command:cross-provider-merge:second-source"),
1031 threadId: sourceThreadId,
1032 messageId: MessageId.make("message:cross-provider-merge:second-source"),
1033 text: secondSourcePrompt,
1034 attachments: [],
1035 modelSelection: CLAUDE_MODEL_SELECTION,
1036 dispatchMode: { type: "start_immediately" },
1037 },
1038 {
1039 type: "thread.fork",
1040 createdBy: "user",
1041 creationSource: "web",
1042 commandId: CommandId.make("command:cross-provider-merge:fork"),
1043 sourceThreadId,
1044 targetThreadId: forkThreadId,
1045 sourcePoint: { type: "latest_stable" },
1046 title: "Cross-provider merge fork",
1047 },
1048 {
1049 type: "message.dispatch",
1050 createdBy: "user",
1051 creationSource: "web",
1052 commandId: CommandId.make("command:cross-provider-merge:fork-turn"),
1053 threadId: forkThreadId,
1054 messageId: MessageId.make("message:cross-provider-merge:fork-turn"),
1055 text: forkPrompt,
1056 attachments: [],
1057 modelSelection: CODEX_MODEL_SELECTION,
1058 dispatchMode: { type: "start_immediately" },
1059 },
1060 {
1061 type: "thread.merge_back",
1062 createdBy: "user",
1063 creationSource: "web",
1064 commandId: CommandId.make("command:cross-provider-merge:merge"),
1065 sourceThreadId: forkThreadId,
1066 targetThreadId: sourceThreadId,
1067 sourcePoint: { type: "latest_stable" },
1068 },
1069 {
1070 type: "message.dispatch",
1071 createdBy: "user",
1072 creationSource: "web",
1073 commandId: CommandId.make("command:cross-provider-merge:consume"),
1074 threadId: sourceThreadId,
1075 messageId: MessageId.make("message:cross-provider-merge:consume"),
1076 text: mergePrompt,
1077 attachments: [],
1078 modelSelection: CODEX_MODEL_SELECTION,
1079 dispatchMode: { type: "start_immediately" },
1080 },
1081 ] satisfies ReadonlyArray<OrchestrationV2Command>;
1082
1083 const projection = yield* Effect.gen(function* () {
1084 const orchestrator = yield* OrchestratorV2;
1085 yield* orchestrator.dispatch(commands[0]!);
1086 yield* orchestrator.dispatch(commands[1]!);
1087 yield* waitForIdle(sourceThreadId);
1088 yield* orchestrator.dispatch(commands[2]!);
1089 yield* waitForIdle(sourceThreadId);
1090 yield* orchestrator.dispatch(commands[3]!);
1091 yield* orchestrator.dispatch(commands[4]!);
1092 yield* waitForIdle(forkThreadId);
1093 yield* orchestrator.dispatch(commands[5]!);
1094 yield* orchestrator.dispatch(commands[6]!);
1095 return yield* waitForIdle(sourceThreadId);
1096 }).pipe(
1097 Effect.provide(
1098 makeOrchestratorV2ReplayLayerWithRegistry(
1099 {
1100 name: "cross-provider-merge",
1101 runtimePolicyOverride: {
1102 cwd,
1103 approvalPolicy: "never",
1104 sandboxPolicy: {
1105 type: "readOnly",
1106 access: { type: "fullAccess" },
1107 networkAccess: false,
1108 },
1109 },
1110 },
1111 registryLayer,
1112 ),
1113 ),
1114 );
1115 const turns = yield* Ref.get(capturedTurns);
1116 const mergedTurn = turns.findLast(
1117 (turn) => turn.threadId === sourceThreadId && turn.driver === "codex",
1118 );
1119 const mergeTransfer = projection.contextTransfers.find(
1120 (transfer) => transfer.type === "merge_back",
1121 );
1122
1123 assert.isDefined(mergedTurn);
1124 assert.include(mergedTurn.text, "Context handoff (full_thread_summary):");
1125 assert.include(mergedTurn.text, firstSourcePrompt);
1126 assert.include(mergedTurn.text, "I will remember amber.");
1127 assert.include(mergedTurn.text, secondSourcePrompt);
1128 assert.include(mergedTurn.text, "I will remember violet.");
1129 assert.include(mergedTurn.text, "Context handoff (merge_back / fork_delta_summary):");
1130 assert.include(mergedTurn.text, forkPrompt);
1131 assert.include(mergedTurn.text, "I will remember cobalt.");
1132 assert.include(mergedTurn.text, mergePrompt);
1133 assert.isDefined(mergeTransfer);
1134 assert.equal(mergeTransfer.status, "consumed");
1135 assert.equal(mergeTransfer.targetProviderInstanceId, "codex");
1136 assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
1137 }),
1138 ),
1139 );
1140
1141 it.live("routes two custom instances of the same driver independently", () =>
1142 Effect.scoped(
1143 Effect.gen(function* () {
1144 const personalThreadId = ThreadId.make("thread:custom-codex-personal");
1145 const workThreadId = ThreadId.make("thread:custom-codex-work");
1146 const personalSelection = {
1147 instanceId: ProviderInstanceId.make("codex_personal"),
1148 model: "gpt-5.4",
1149 } satisfies ModelSelection;
1150 const workSelection = {
1151 instanceId: ProviderInstanceId.make("codex_work"),
1152 model: "gpt-5.4",
1153 } satisfies ModelSelection;
1154 const cwd = yield* checkpointWorkspace("custom-codex-instances");
1155 const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1156 const registryLayer = makeProviderAdapterRegistryLayer([
1157 makeTestAdapter({
1158 instanceId: personalSelection.instanceId,
1159 driver: CODEX_DRIVER,
1160 capabilities: CodexProviderCapabilitiesV2,
1161 modelSelection: personalSelection,
1162 responseByRunOrdinal: { 1: "personal response" },
1163 capturedTurns,
1164 }),
1165 makeTestAdapter({
1166 instanceId: workSelection.instanceId,
1167 driver: CODEX_DRIVER,
1168 capabilities: CodexProviderCapabilitiesV2,
1169 modelSelection: workSelection,
1170 responseByRunOrdinal: { 1: "work response" },
1171 capturedTurns,
1172 }),
1173 ]);
1174
1175 const [personal, work] = yield* Effect.gen(function* () {
1176 const orchestrator = yield* OrchestratorV2;
1177 for (const [targetThreadId, selection, suffix] of [
1178 [personalThreadId, personalSelection, "personal"],
1179 [workThreadId, workSelection, "work"],
1180 ] as const) {
1181 yield* orchestrator.dispatch({
1182 type: "thread.create",
1183 createdBy: "user",
1184 creationSource: "web",
1185 commandId: CommandId.make(`command:custom-codex:${suffix}:create`),
1186 threadId: targetThreadId,
1187 projectId,
1188 title: `Custom Codex ${suffix}`,
1189 modelSelection: selection,
1190 runtimeMode: "full-access",
1191 interactionMode: "default",
1192 branch: null,
1193 worktreePath: null,
1194 });
1195 yield* orchestrator.dispatch({
1196 type: "message.dispatch",
1197 createdBy: "user",
1198 creationSource: "web",
1199 commandId: CommandId.make(`command:custom-codex:${suffix}:message`),
1200 threadId: targetThreadId,
1201 messageId: MessageId.make(`message:custom-codex:${suffix}`),
1202 text: `${suffix} prompt`,
1203 attachments: [],
1204 modelSelection: selection,
1205 dispatchMode: { type: "start_immediately" },
1206 });
1207 yield* waitForIdle(targetThreadId);
1208 }
1209 return yield* Effect.all([
1210 orchestrator.getThreadProjection(personalThreadId),
1211 orchestrator.getThreadProjection(workThreadId),
1212 ]);
1213 }).pipe(
1214 Effect.provide(
1215 makeOrchestratorV2ReplayLayerWithRegistry(
1216 {
1217 name: "custom-codex-instances",
1218 runtimePolicyOverride: {
1219 cwd,
1220 approvalPolicy: "never",
1221 sandboxPolicy: {
1222 type: "readOnly",
1223 access: { type: "fullAccess" },
1224 networkAccess: false,
1225 },
1226 },
1227 },
1228 registryLayer,
1229 ),
1230 ),
1231 );
1232
1233 assert.equal(personal.runs[0]?.providerInstanceId, personalSelection.instanceId);
1234 assert.equal(
1235 personal.providerSessions[0]?.providerInstanceId,
1236 personalSelection.instanceId,
1237 );
1238 assert.equal(work.runs[0]?.providerInstanceId, workSelection.instanceId);
1239 assert.equal(work.providerSessions[0]?.providerInstanceId, workSelection.instanceId);
1240 assert.notEqual(personal.providerSessions[0]?.id, work.providerSessions[0]?.id);
1241 assert.deepEqual(
1242 (yield* Ref.get(capturedTurns)).map((turn) => [turn.threadId, turn.text]),
1243 [
1244 [personalThreadId, "personal prompt"],
1245 [workThreadId, "work prompt"],
1246 ],
1247 );
1248 }),
1249 ),
1250 );
1251});