Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointId,
4 CheckpointRef,
5 CheckpointScopeId,
6 CommandId,
7 EventId,
8 MessageId,
9 NodeId,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ProviderThreadId,
14 ProviderTurnId,
15 RunAttemptId,
16 RunId,
17 ThreadId,
18 TurnItemId,
19} from "@t3tools/contracts";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Statement from "effect/sql/Statement";
23import * as TestClock from "effect/testing/TestClock";
24
25import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
26import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts";
27import * as EffectWorker from "./EffectWorker.ts";
28import * as EventSink from "./EventSink.ts";
29import * as Orchestrator from "./Orchestrator.ts";
30import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
31import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
32import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
33
34const forkCases = (
35 [
36 ["codex", "interrupted"],
37 ["claudeAgent", "failed"],
38 ] as const
39).map(([driverName, status]) => {
40 const driver = ProviderDriverKind.make(driverName);
41 const instanceId = ProviderInstanceId.make(driver);
42 const modelSelection = { instanceId, model: "test-model" };
43 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
44 instanceId,
45 driver,
46 getCapabilities: () =>
47 Effect.succeed(
48 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
49 ),
50 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
51 openSession: () => Effect.die("Execution is paused after dispatch for handoff inspection"),
52 };
53 const layer = ProviderReplayHarness.layerWithRegistry(
54 { name: `fork-boundary-${driver}` },
55 ProviderAdapterRegistry.layerFromAdapters([adapter]),
56 { runEffectWorker: false },
57 );
58
59 return { driver, status, instanceId, modelSelection, layer };
60});
61
62it.effect("a persisted fork leaves PR watching with its parent until explicitly opted in", () =>
63 Effect.gen(function* () {
64 const orchestrator = yield* Orchestrator.OrchestratorV2;
65 const eventSink = yield* EventSink.EventSinkV2;
66 const now = yield* DateTime.now;
67 const { instanceId, modelSelection } = forkCases[0]!;
68 const sourceThreadId = ThreadId.make("fork-watch-source");
69 const targetThreadId = ThreadId.make("fork-watch-target");
70 const sourceRunId = RunId.make("fork-watch-source-run");
71 const key = { host: "github.com", repository: "example/repo", number: 1 };
72 const link = { url: "https://github.com/example/repo/pull/1", source: "agent" as const };
73
74 yield* orchestrator.dispatch({
75 type: "thread.create",
76 commandId: CommandId.make("fork-watch-create"),
77 threadId: sourceThreadId,
78 projectId: ProjectId.make("fork-watch-project"),
79 title: "Watching source",
80 modelSelection,
81 runtimeMode: "full-access",
82 interactionMode: "default",
83 branch: null,
84 worktreePath: null,
85 createdBy: "user",
86 creationSource: "web",
87 });
88 yield* eventSink.write({
89 events: [
90 {
91 id: EventId.make("fork-watch-source-run"),
92 type: "run.created",
93 threadId: sourceThreadId,
94 runId: sourceRunId,
95 occurredAt: now,
96 payload: {
97 id: sourceRunId,
98 threadId: sourceThreadId,
99 ordinal: 1,
100 providerInstanceId: instanceId,
101 modelSelection,
102 providerThreadId: null,
103 userMessageId: MessageId.make("fork-watch-source-message"),
104 rootNodeId: null,
105 activeAttemptId: null,
106 status: "completed",
107 requestedAt: now,
108 startedAt: now,
109 completedAt: now,
110 checkpointId: null,
111 contextHandoffId: null,
112 },
113 },
114 ],
115 });
116 yield* orchestrator.dispatch({
117 type: "thread.pull-request.watch",
118 commandId: CommandId.make("fork-watch-parent-start"),
119 threadId: sourceThreadId,
120 ...key,
121 watching: true,
122 link,
123 });
124 const parentBefore = yield* orchestrator.getThreadShell(sourceThreadId);
125 const parentWatch = parentBefore?.pullRequests?.[0]?.watch;
126 assert.isDefined(parentWatch);
127 assert.lengthOf(parentBefore?.pendingBackgroundTasks ?? [], 1);
128
129 yield* orchestrator.dispatch({
130 type: "thread.fork",
131 commandId: CommandId.make("fork-watch-fork"),
132 sourceThreadId,
133 targetThreadId,
134 sourcePoint: { type: "run", runId: sourceRunId },
135 createdBy: "user",
136 creationSource: "mcp",
137 });
138 const fork = yield* orchestrator.getThreadShell(targetThreadId);
139 assert.isNotNull(fork);
140 assert.deepEqual(fork.pullRequests, [
141 {
142 ...key,
143 ...link,
144 linkedAt: parentWatch.startedAt,
145 snapshot: null,
146 stack: null,
147 },
148 ]);
149 assert.deepEqual(fork.pendingBackgroundTasks, []);
150 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
151
152 const stale = yield* orchestrator
153 .dispatch({
154 type: "thread.pull-request-watch.sync",
155 commandId: CommandId.make("fork-watch-stale-sync"),
156 threadId: targetThreadId,
157 ...key,
158 startedAt: parentWatch.startedAt,
159 watch: parentWatch,
160 wake: {
161 messageId: MessageId.make("fork-watch-unwanted-wake"),
162 text: "A check failed",
163 notification: {
164 source: { kind: "monitor" },
165 outcome: "updated",
166 summary: "A check failed",
167 },
168 },
169 })
170 .pipe(Effect.flip);
171 assert.equal(stale._tag, "OrchestratorDispatchError");
172 assert.deepEqual((yield* orchestrator.getThreadProjection(targetThreadId)).runs, []);
173
174 yield* TestClock.adjust("1 second");
175 yield* orchestrator.dispatch({
176 type: "thread.pull-request.watch",
177 commandId: CommandId.make("fork-watch-opt-in"),
178 threadId: targetThreadId,
179 ...key,
180 watching: true,
181 link,
182 });
183 const watchingFork = yield* orchestrator.getThreadShell(targetThreadId);
184 assert.isDefined(watchingFork?.pullRequests?.[0]?.watch);
185 assert.notEqual(watchingFork.pullRequests[0].watch.startedAt, parentWatch.startedAt);
186 assert.lengthOf(watchingFork.pendingBackgroundTasks ?? [], 1);
187 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
188
189 yield* orchestrator.dispatch({
190 type: "thread.pull-request.watch",
191 commandId: CommandId.make("fork-watch-opt-out"),
192 threadId: targetThreadId,
193 ...key,
194 watching: false,
195 });
196 const stoppedFork = yield* orchestrator.getThreadShell(targetThreadId);
197 const [forkLink] = fork.pullRequests ?? [];
198 assert.isDefined(forkLink);
199 assert.deepEqual(stoppedFork?.pullRequests, [
200 { ...forkLink, endedWatch: watchingFork.pullRequests[0].watch },
201 ]);
202 assert.deepEqual(stoppedFork?.pendingBackgroundTasks, []);
203 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
204 }).pipe(Effect.provide(forkCases[0]!.layer)),
205);
206
207it.effect.each(forkCases)(
208 "bounds $driver context when continuing a fork of a $status run",
209 ({ driver, status, instanceId, modelSelection, layer }) =>
210 Effect.gen(function* () {
211 const orchestrator = yield* Orchestrator.OrchestratorV2;
212 const eventSink = yield* EventSink.EventSinkV2;
213 const now = yield* DateTime.now;
214 const sourceThreadId = ThreadId.make("fork-boundary-source");
215 const targetThreadId = ThreadId.make("fork-boundary-target");
216 const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
217 const sourceRunId = RunId.make("fork-boundary-source-run");
218 const attemptId = RunAttemptId.make("interrupted-source-attempt");
219 const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
220 const rootNodeId = NodeId.make("interrupted-source-root");
221 const grandparentThreadId = ThreadId.make("fork-boundary-grandparent");
222 const grandparentRunId = RunId.make("fork-boundary-grandparent-run");
223
224 yield* orchestrator.dispatch({
225 type: "thread.create",
226 commandId: CommandId.make("create-grandparent"),
227 threadId: grandparentThreadId,
228 projectId: ProjectId.make("fork-boundary-project"),
229 title: "Fork boundary grandparent",
230 modelSelection,
231 runtimeMode: "full-access",
232 interactionMode: "default",
233 branch: null,
234 worktreePath: null,
235 createdBy: "user",
236 creationSource: "web",
237 });
238 yield* writeParentRun({
239 threadId: grandparentThreadId,
240 runId: RunId.make("fork-boundary-grandparent-rolled-back-run"),
241 ordinal: 1,
242 status: "rolled_back",
243 text: "ROLLED_BACK_MARKER",
244 });
245 yield* writeParentRun({
246 threadId: grandparentThreadId,
247 runId: grandparentRunId,
248 ordinal: 2,
249 status: "completed",
250 text: "GRANDPARENT_MARKER",
251 });
252 yield* orchestrator.dispatch({
253 type: "thread.fork",
254 commandId: CommandId.make("fork-grandparent"),
255 sourceThreadId: grandparentThreadId,
256 targetThreadId: sourceThreadId,
257 sourcePoint: { type: "run", runId: grandparentRunId },
258 createdBy: "user",
259 creationSource: "web",
260 });
261 yield* eventSink.write({
262 events: [
263 {
264 id: EventId.make("source-provider-thread"),
265 type: "provider-thread.updated",
266 threadId: sourceThreadId,
267 occurredAt: now,
268 payload: {
269 id: providerThreadId,
270 driver,
271 providerInstanceId: instanceId,
272 providerSessionId: null,
273 appThreadId: sourceThreadId,
274 ownerNodeId: null,
275 nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
276 nativeConversationHeadRef: null,
277 status: "idle",
278 firstRunOrdinal: 2,
279 lastRunOrdinal: 3,
280 handoffIds: [],
281 forkedFrom: null,
282 createdAt: now,
283 updatedAt: now,
284 },
285 },
286 ],
287 });
288 if (status === "interrupted") {
289 yield* eventSink.write({
290 events: [
291 {
292 id: EventId.make("source-attempt"),
293 type: "run-attempt.created",
294 threadId: sourceThreadId,
295 runId: sourceRunId,
296 occurredAt: now,
297 payload: {
298 id: attemptId,
299 runId: sourceRunId,
300 attemptOrdinal: 1,
301 rootNodeId,
302 providerInstanceId: instanceId,
303 providerThreadId,
304 providerTurnId,
305 reason: "initial",
306 status,
307 startedAt: now,
308 completedAt: now,
309 },
310 },
311 {
312 id: EventId.make("source-provider-turn"),
313 type: "provider-turn.updated",
314 threadId: sourceThreadId,
315 occurredAt: now,
316 payload: {
317 id: providerTurnId,
318 providerThreadId,
319 nodeId: rootNodeId,
320 runAttemptId: attemptId,
321 nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
322 ordinal: 1,
323 status,
324 startedAt: now,
325 completedAt: now,
326 },
327 },
328 ],
329 });
330 }
331 yield* writeParentRun({
332 threadId: sourceThreadId,
333 runId: RunId.make("fork-boundary-source-rolled-back-run"),
334 ordinal: 1,
335 status: "rolled_back",
336 text: "SOURCE_ROLLED_BACK_MARKER",
337 });
338 for (const ordinal of [2, 3]) {
339 const runId = ordinal === 2 ? sourceRunId : RunId.make("later-run");
340 const messageId = MessageId.make(`source-message-${ordinal}`);
341 yield* eventSink.write({
342 events: [
343 {
344 id: EventId.make(`run-${ordinal}`),
345 type: "run.created",
346 threadId: sourceThreadId,
347 runId,
348 occurredAt: now,
349 payload: {
350 id: runId,
351 threadId: sourceThreadId,
352 ordinal,
353 providerInstanceId: instanceId,
354 modelSelection,
355 providerThreadId,
356 userMessageId: messageId,
357 rootNodeId: null,
358 activeAttemptId: ordinal === 2 && status === "interrupted" ? attemptId : null,
359 status: ordinal === 2 ? status : "completed",
360 queuePosition: null,
361 requestedAt: now,
362 startedAt: now,
363 completedAt: now,
364 checkpointId: null,
365 contextHandoffId: null,
366 },
367 },
368 {
369 id: EventId.make(`item-${ordinal}`),
370 type: "turn-item.updated",
371 threadId: sourceThreadId,
372 runId,
373 occurredAt: now,
374 payload: {
375 id: TurnItemId.make(`item-${ordinal}`),
376 threadId: sourceThreadId,
377 runId,
378 nodeId: null,
379 providerThreadId,
380 providerTurnId: null,
381 nativeItemRef: null,
382 parentItemId: null,
383 ordinal,
384 status: "completed",
385 title: null,
386 startedAt: now,
387 completedAt: now,
388 updatedAt: now,
389 type: "user_message",
390 createdBy: "user",
391 creationSource: "web",
392 inputIntent: "turn_start",
393 messageId,
394 text: ordinal === 2 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
395 attachments: [],
396 },
397 },
398 ],
399 });
400 }
401 yield* orchestrator.dispatch({
402 type: "thread.fork",
403 commandId: CommandId.make("fork-source"),
404 sourceThreadId,
405 targetThreadId,
406 sourcePoint: { type: "run", runId: sourceRunId },
407 createdBy: "user",
408 creationSource: "web",
409 });
410 yield* orchestrator.dispatch({
411 type: "message.dispatch",
412 commandId: CommandId.make("continue-fork"),
413 threadId: targetThreadId,
414 messageId: MessageId.make("continue-fork"),
415 text: "Continue from the selected source run",
416 attachments: [],
417 modelSelection,
418 dispatchMode: { type: "start_immediately" },
419 createdBy: "user",
420 creationSource: "web",
421 });
422 const target = yield* orchestrator.getThreadProjection(targetThreadId);
423 assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
424 assert.lengthOf(target.contextHandoffs, 1);
425 const handoff = target.contextHandoffs[0]!;
426 const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
427 assert.include(`${handoff.summaryText}\n${history}`, "GRANDPARENT_MARKER");
428 assert.notInclude(`${handoff.summaryText}\n${history}`, "SOURCE_ROLLED_BACK_MARKER");
429 assert.notInclude(`${handoff.summaryText}\n${history}`, "ROLLED_BACK_MARKER");
430 assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
431 assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
432 assert.isNull(target.providerThreads[0]?.forkedFrom);
433 }).pipe(Effect.provide(layer)),
434);
435
436it.effect.each([
437 { execution: "portable_context", rejected: true },
438 { execution: "native_fork", rejected: false },
439] as const)(
440 "a $execution fork's first /compact is rejected only when no history reaches it: $rejected",
441 ({ execution, rejected }) => {
442 const opened: Array<ProviderInstanceId> = [];
443 const adapter = (driverName: "claudeAgent" | "codex") => {
444 const driver = ProviderDriverKind.make(driverName);
445 const instanceId = ProviderInstanceId.make(driverName);
446 return {
447 instanceId,
448 driver,
449 getCapabilities: () =>
450 Effect.succeed(
451 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
452 ),
453 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
454 openSession: (input) =>
455 Effect.sync(() => opened.push(instanceId)).pipe(
456 Effect.andThen(
457 new ProviderAdapter.ProviderAdapterOpenSessionError({
458 driver,
459 providerSessionId: input.providerSessionId,
460 }),
461 ),
462 ),
463 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
464 };
465 const claude = adapter("claudeAgent");
466 const target = execution === "portable_context" ? adapter("codex") : claude;
467 return Effect.gen(function* () {
468 const orchestrator = yield* Orchestrator.OrchestratorV2;
469 const eventSink = yield* EventSink.EventSinkV2;
470 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
471 const now = yield* DateTime.now;
472 const sourceThreadId = ThreadId.make("fork-compact-source");
473 const targetThreadId = ThreadId.make("fork-compact-target");
474 const providerThreadId = ProviderThreadId.make("fork-compact-native-thread");
475 const sourceRunId = RunId.make("fork-compact-source-run");
476 const userMessageId = MessageId.make("fork-compact-source-message");
477 const sourceSelection = { instanceId: claude.instanceId, model: "test-model" };
478
479 yield* orchestrator.dispatch({
480 type: "thread.create",
481 commandId: CommandId.make("fork-compact-create-source"),
482 threadId: sourceThreadId,
483 projectId: ProjectId.make("fork-compact-project"),
484 title: "Fork compact source",
485 modelSelection: sourceSelection,
486 runtimeMode: "full-access",
487 interactionMode: "default",
488 branch: null,
489 worktreePath: null,
490 createdBy: "user",
491 creationSource: "web",
492 });
493 const item = {
494 threadId: sourceThreadId,
495 runId: sourceRunId,
496 nodeId: null,
497 providerThreadId,
498 providerTurnId: null,
499 nativeItemRef: null,
500 parentItemId: null,
501 status: "completed",
502 title: null,
503 startedAt: now,
504 completedAt: now,
505 updatedAt: now,
506 } as const;
507 yield* eventSink.write({
508 events: [
509 {
510 id: EventId.make("fork-compact-provider-thread"),
511 type: "provider-thread.updated",
512 threadId: sourceThreadId,
513 occurredAt: now,
514 payload: {
515 id: providerThreadId,
516 driver: claude.driver,
517 providerInstanceId: claude.instanceId,
518 providerSessionId: null,
519 appThreadId: sourceThreadId,
520 ownerNodeId: null,
521 nativeThreadRef: {
522 driver: claude.driver,
523 nativeId: "native-fork-compact-source",
524 strength: "strong",
525 },
526 nativeConversationHeadRef: null,
527 status: "idle",
528 firstRunOrdinal: 1,
529 lastRunOrdinal: 1,
530 handoffIds: [],
531 forkedFrom: null,
532 createdAt: now,
533 updatedAt: now,
534 },
535 },
536 {
537 id: EventId.make("fork-compact-source-run"),
538 type: "run.created",
539 threadId: sourceThreadId,
540 runId: sourceRunId,
541 occurredAt: now,
542 payload: {
543 id: sourceRunId,
544 threadId: sourceThreadId,
545 ordinal: 1,
546 providerInstanceId: claude.instanceId,
547 modelSelection: sourceSelection,
548 providerThreadId,
549 userMessageId,
550 rootNodeId: null,
551 activeAttemptId: null,
552 status: "completed",
553 queuePosition: null,
554 requestedAt: now,
555 startedAt: now,
556 completedAt: now,
557 checkpointId: null,
558 contextHandoffId: null,
559 },
560 },
561 // Each message alone exceeds the default 16k handoff budget, so a
562 // portable handoff omits both whole items.
563 {
564 id: EventId.make("fork-compact-user-item"),
565 type: "turn-item.updated",
566 threadId: sourceThreadId,
567 runId: sourceRunId,
568 occurredAt: now,
569 payload: {
570 ...item,
571 id: TurnItemId.make("fork-compact-user-item"),
572 ordinal: 1,
573 type: "user_message",
574 createdBy: "user",
575 creationSource: "web",
576 inputIntent: "turn_start",
577 messageId: userMessageId,
578 text: "u".repeat(17_000),
579 attachments: [],
580 },
581 },
582 {
583 id: EventId.make("fork-compact-assistant-item"),
584 type: "turn-item.updated",
585 threadId: sourceThreadId,
586 runId: sourceRunId,
587 occurredAt: now,
588 payload: {
589 ...item,
590 id: TurnItemId.make("fork-compact-assistant-item"),
591 ordinal: 2,
592 type: "assistant_message",
593 messageId: MessageId.make("fork-compact-assistant-message"),
594 text: "a".repeat(17_000),
595 streaming: false,
596 },
597 },
598 ],
599 });
600 yield* orchestrator.dispatch({
601 type: "thread.fork",
602 commandId: CommandId.make("fork-compact-fork"),
603 sourceThreadId,
604 targetThreadId,
605 sourcePoint: { type: "run", runId: sourceRunId },
606 createdBy: "user",
607 creationSource: "web",
608 });
609 yield* orchestrator.dispatch({
610 type: "message.dispatch",
611 commandId: CommandId.make("fork-compact-compact"),
612 threadId: targetThreadId,
613 messageId: MessageId.make("fork-compact-compact"),
614 text: "/compact",
615 attachments: [],
616 modelSelection: { instanceId: target.instanceId, model: "test-model" },
617 dispatchMode: { type: "start_immediately" },
618 createdBy: "user",
619 creationSource: "web",
620 });
621 yield* worker.drain();
622
623 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
624 if (execution === "portable_context") {
625 assert.equal(projection.contextTransfers[0]?.resolution?.strategy, "portable_context");
626 assert.deepEqual(projection.contextHandoffs[0]?.history?.messages, []);
627 } else {
628 assert.isEmpty(projection.contextHandoffs);
629 }
630 const emptyCompaction = projection.turnItems.some(
631 (turnItem) =>
632 turnItem.type === "error" &&
633 turnItem.failure.message === "Start a conversation before compacting this thread.",
634 );
635 assert.equal(emptyCompaction, rejected);
636 assert.deepEqual(opened, rejected ? [] : [target.instanceId]);
637 }).pipe(
638 Effect.provide(
639 ProviderReplayHarness.layerWithRegistry(
640 { name: `fork-compact-${execution}` },
641 ProviderAdapterRegistry.layerFromAdapters(
642 target === claude ? [claude] : [claude, target],
643 ),
644 ),
645 ),
646 );
647 },
648);
649
650const writeParentRun = (input: {
651 readonly threadId: ThreadId;
652 readonly runId: RunId;
653 readonly ordinal: number;
654 /** Preparing, failed, and interrupted runs asked for a new worktree. */
655 readonly status:
656 | "preparing"
657 | "running"
658 | "queued"
659 | "completed"
660 | "rolled_back"
661 | "failed"
662 | "interrupted";
663 readonly text: string;
664 /** A checkpointed run on a native provider thread, which `latest_stable` forks start from. */
665 readonly stable?: boolean;
666}) =>
667 Effect.gen(function* () {
668 const eventSink = yield* EventSink.EventSinkV2;
669 const now = yield* DateTime.now;
670 const { driver, instanceId, modelSelection } = forkCases[0]!;
671 const messageId = MessageId.make(`${input.runId}:message`);
672 const providerThreadId = input.stable
673 ? ProviderThreadId.make(`${input.runId}:provider-thread`)
674 : null;
675 yield* eventSink.write({
676 events: [
677 ...(providerThreadId === null
678 ? []
679 : [
680 {
681 id: EventId.make(`${input.runId}:provider-thread`),
682 type: "provider-thread.updated" as const,
683 threadId: input.threadId,
684 occurredAt: now,
685 payload: {
686 id: providerThreadId,
687 driver,
688 providerInstanceId: instanceId,
689 providerSessionId: null,
690 appThreadId: input.threadId,
691 ownerNodeId: null,
692 nativeThreadRef: {
693 driver,
694 nativeId: `${input.runId}:native`,
695 strength: "strong" as const,
696 },
697 nativeConversationHeadRef: null,
698 status: "idle" as const,
699 firstRunOrdinal: input.ordinal,
700 lastRunOrdinal: input.ordinal,
701 handoffIds: [],
702 forkedFrom: null,
703 createdAt: now,
704 updatedAt: now,
705 },
706 },
707 ]),
708 {
709 id: EventId.make(`${input.runId}:created`),
710 type: "run.created",
711 threadId: input.threadId,
712 runId: input.runId,
713 occurredAt: now,
714 payload: {
715 id: input.runId,
716 threadId: input.threadId,
717 ordinal: input.ordinal,
718 providerInstanceId: instanceId,
719 modelSelection,
720 providerThreadId,
721 userMessageId: messageId,
722 rootNodeId: null,
723 activeAttemptId: null,
724 status: input.status,
725 queuePosition: null,
726 requestedAt: now,
727 startedAt: now,
728 completedAt: input.status === "completed" ? now : null,
729 checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null,
730 contextHandoffId: null,
731 ...(input.status === "preparing" ||
732 input.status === "failed" ||
733 input.status === "interrupted"
734 ? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } }
735 : {}),
736 },
737 },
738 {
739 id: EventId.make(`${input.runId}:item`),
740 type: "turn-item.updated",
741 threadId: input.threadId,
742 runId: input.runId,
743 occurredAt: now,
744 payload: {
745 id: TurnItemId.make(`${input.runId}:item`),
746 threadId: input.threadId,
747 runId: input.runId,
748 nodeId: null,
749 providerThreadId,
750 providerTurnId: null,
751 nativeItemRef: null,
752 parentItemId: null,
753 ordinal: input.ordinal * 100,
754 status: "completed",
755 title: null,
756 startedAt: now,
757 completedAt: now,
758 updatedAt: now,
759 type: "user_message",
760 createdBy: "user",
761 creationSource: "web",
762 inputIntent: "turn_start",
763 messageId,
764 text: input.text,
765 attachments: [],
766 },
767 },
768 ],
769 });
770 });
771
772/** Marks `threadId` as imported from V1 and gives it one runless imported user message. */
773const writeImportedHistory = (threadId: ThreadId, text: string) =>
774 Effect.gen(function* () {
775 const orchestrator = yield* Orchestrator.OrchestratorV2;
776 const eventSink = yield* EventSink.EventSinkV2;
777 const now = yield* DateTime.now;
778 const { thread } = yield* orchestrator.getThreadProjection(threadId);
779 yield* eventSink.write({
780 events: [
781 {
782 id: EventId.make(`${threadId}:imported`),
783 type: "thread.metadata-updated",
784 threadId,
785 occurredAt: now,
786 payload: { ...thread, historyOrigin: "v1_import" },
787 },
788 {
789 id: EventId.make(`${threadId}:imported-item`),
790 type: "turn-item.updated",
791 threadId,
792 occurredAt: now,
793 payload: {
794 id: TurnItemId.make(`${threadId}:imported-item`),
795 threadId,
796 runId: null,
797 nodeId: null,
798 providerThreadId: null,
799 providerTurnId: null,
800 nativeItemRef: null,
801 parentItemId: null,
802 ordinal: 1,
803 status: "completed",
804 title: null,
805 startedAt: now,
806 completedAt: now,
807 updatedAt: now,
808 type: "user_message",
809 createdBy: "user",
810 creationSource: "web",
811 inputIntent: "turn_start",
812 messageId: MessageId.make(`${threadId}:imported-message`),
813 text,
814 attachments: [],
815 },
816 },
817 ],
818 });
819 });
820
821const createParent = (threadId: ThreadId) =>
822 Effect.gen(function* () {
823 const orchestrator = yield* Orchestrator.OrchestratorV2;
824 yield* orchestrator.dispatch({
825 type: "thread.create",
826 commandId: CommandId.make(`${threadId}:create`),
827 threadId,
828 projectId: ProjectId.make("side-chat-project"),
829 title: "Side chat parent",
830 modelSelection: forkCases[0]!.modelSelection,
831 runtimeMode: "full-access",
832 interactionMode: "default",
833 branch: null,
834 worktreePath: null,
835 createdBy: "user",
836 creationSource: "web",
837 });
838 });
839
840const forkSideChat = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
841 Effect.gen(function* () {
842 const orchestrator = yield* Orchestrator.OrchestratorV2;
843 return yield* orchestrator.dispatch({
844 type: "thread.fork",
845 commandId: CommandId.make(commandId),
846 sourceThreadId,
847 targetThreadId,
848 sourcePoint: { type: "latest_stable" },
849 sideChat: true,
850 createdBy: "user",
851 creationSource: "web",
852 });
853 });
854
855const askSideChat = (threadId: ThreadId, commandId: string) =>
856 Effect.gen(function* () {
857 const orchestrator = yield* Orchestrator.OrchestratorV2;
858 yield* orchestrator.dispatch({
859 type: "message.dispatch",
860 commandId: CommandId.make(commandId),
861 threadId,
862 messageId: MessageId.make(commandId),
863 text: "What is the main thread doing?",
864 attachments: [],
865 dispatchMode: { type: "start_immediately" },
866 createdBy: "user",
867 creationSource: "web",
868 });
869 });
870
871it.effect("resolves an explicit checkpoint fork to its source run", () =>
872 Effect.gen(function* () {
873 const orchestrator = yield* Orchestrator.OrchestratorV2;
874 const eventSink = yield* EventSink.EventSinkV2;
875 const now = yield* DateTime.now;
876 const parentId = ThreadId.make("checkpoint-fork-parent");
877 const childId = ThreadId.make("checkpoint-fork-child");
878 const runId = RunId.make("checkpoint-fork-run");
879 const checkpointId = CheckpointId.make("checkpoint-fork-checkpoint");
880 yield* createParent(parentId);
881 yield* writeParentRun({
882 threadId: parentId,
883 runId,
884 ordinal: 1,
885 status: "completed",
886 text: "Work",
887 });
888 yield* eventSink.write({
889 events: [
890 {
891 id: EventId.make("checkpoint-fork-captured"),
892 type: "checkpoint.captured",
893 threadId: parentId,
894 occurredAt: now,
895 payload: {
896 id: checkpointId,
897 threadId: parentId,
898 scopeId: CheckpointScopeId.make("checkpoint-fork-scope"),
899 runId,
900 nodeId: NodeId.make("checkpoint-fork-node"),
901 parentCheckpointId: null,
902 ordinalWithinScope: 1,
903 appRunOrdinal: 1,
904 ref: CheckpointRef.make("refs/t3/checkpoint-fork/1"),
905 status: "ready",
906 files: [],
907 capturedAt: now,
908 },
909 },
910 ],
911 });
912 yield* orchestrator.dispatch({
913 type: "thread.fork",
914 commandId: CommandId.make("checkpoint-fork"),
915 sourceThreadId: parentId,
916 targetThreadId: childId,
917 sourcePoint: { type: "checkpoint", checkpointId },
918 createdBy: "user",
919 creationSource: "mcp",
920 });
921 const child = yield* orchestrator.getThreadShell(childId);
922 assert.deepEqual(child?.forkedFrom, { type: "run", threadId: parentId, runId });
923 }).pipe(Effect.provide(forkCases[0]!.layer)),
924);
925
926it.effect("a side chat of an idle parent still starts with the framing note", () =>
927 Effect.gen(function* () {
928 const orchestrator = yield* Orchestrator.OrchestratorV2;
929 const parentId = ThreadId.make("side-chat-idle-parent");
930 const sideChatId = ThreadId.make("side-chat-idle-child");
931 yield* createParent(parentId);
932 yield* writeParentRun({
933 threadId: parentId,
934 runId: RunId.make("side-chat-idle-parent-run"),
935 ordinal: 1,
936 status: "completed",
937 text: "Parent work",
938 stable: true,
939 });
940
941 const reads: Array<string> = [];
942 const recordReads: Statement.Transformer = (statement) => {
943 const [query] = statement.compile();
944 if (/^\s*SELECT/i.test(query)) reads.push(query);
945 return Effect.succeed(statement);
946 };
947 yield* forkSideChat("side-chat-idle-fork", parentId, sideChatId).pipe(
948 Effect.provideService(Statement.CurrentTransformer, recordReads),
949 );
950 assert.isEmpty(
951 reads.filter(
952 (query) =>
953 query.includes("FROM orchestration_v2_projection_checkpoints") ||
954 query.includes("FROM orchestration_v2_projection_context_transfers"),
955 ),
956 );
957 yield* askSideChat(sideChatId, "side-chat-idle-first-message");
958
959 const started = yield* orchestrator.getThreadProjection(sideChatId);
960 assert.isNotNull(started.providerThreads[0]?.forkedFrom);
961 assert.lengthOf(started.contextHandoffs, 1);
962 const [handoff] = started.contextHandoffs;
963 assert.isTrue(
964 handoff!.summaryText.startsWith("You are in a side chat beside the main thread."),
965 );
966 assert.notInclude(handoff!.summaryText, "Main thread activity");
967 }).pipe(Effect.provide(forkCases[0]!.layer)),
968);
969
970it.effect("a side chat waits for the parent's new worktree, also after its setup ended", () =>
971 Effect.gen(function* () {
972 for (const status of ["preparing", "failed", "interrupted"] as const) {
973 const parentId = ThreadId.make(`side-chat-worktree-parent-${status}`);
974 yield* createParent(parentId);
975 yield* writeParentRun({
976 threadId: parentId,
977 runId: RunId.make(`side-chat-worktree-parent-run-${status}`),
978 ordinal: 1,
979 status,
980 text: "Parent work",
981 });
982
983 const rejected = yield* forkSideChat(
984 `side-chat-worktree-fork-${status}`,
985 parentId,
986 ThreadId.make(`side-chat-worktree-child-${status}`),
987 ).pipe(Effect.flip);
988 assert.include(String(rejected.cause), "has no worktree yet", status);
989 }
990 }).pipe(Effect.provide(forkCases[0]!.layer)),
991);
992
993it.effect("closing a side chat deletes it only while unused; a deleted parent takes no more", () =>
994 Effect.gen(function* () {
995 const orchestrator = yield* Orchestrator.OrchestratorV2;
996 const parentId = ThreadId.make("side-chat-close-parent");
997 const unused = ThreadId.make("side-chat-close-unused");
998 const used = ThreadId.make("side-chat-close-used");
999 yield* createParent(parentId);
1000 yield* writeParentRun({
1001 threadId: parentId,
1002 runId: RunId.make("side-chat-close-parent-run"),
1003 ordinal: 1,
1004 status: "completed",
1005 text: "Parent work",
1006 stable: true,
1007 });
1008 yield* forkSideChat("side-chat-close-fork-unused", parentId, unused);
1009 yield* forkSideChat("side-chat-close-fork-used", parentId, used);
1010 yield* askSideChat(used, "side-chat-close-used-message");
1011 const close = (threadId: ThreadId) =>
1012 orchestrator.dispatch({
1013 type: "thread.delete",
1014 commandId: CommandId.make(`side-chat-close:${threadId}`),
1015 threadId,
1016 onlyIfUnused: true,
1017 });
1018
1019 yield* close(unused);
1020 yield* close(used);
1021 assert.isNotNull((yield* orchestrator.getThreadProjection(unused)).thread.deletedAt);
1022 assert.isNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
1023
1024 yield* orchestrator.dispatch({
1025 type: "thread.delete",
1026 commandId: CommandId.make("side-chat-close-delete-parent"),
1027 threadId: parentId,
1028 });
1029 assert.isNotNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
1030 const orphan = yield* forkSideChat(
1031 "side-chat-close-orphan",
1032 parentId,
1033 ThreadId.make("side-chat-close-orphan"),
1034 ).pipe(Effect.flip);
1035 assert.include(String(orphan.cause), "was deleted");
1036 }).pipe(Effect.provide(forkCases[0]!.layer)),
1037);
1038
1039it.effect("a side chat opened during the parent's first turn starts from a digest", () =>
1040 Effect.gen(function* () {
1041 const orchestrator = yield* Orchestrator.OrchestratorV2;
1042 const grandparentId = ThreadId.make("side-chat-busy-grandparent");
1043 const grandparentRunId = RunId.make("side-chat-busy-grandparent-run");
1044 const parentId = ThreadId.make("side-chat-busy-parent");
1045 const sideChatId = ThreadId.make("side-chat-busy-child");
1046 yield* createParent(grandparentId);
1047 yield* writeParentRun({
1048 threadId: grandparentId,
1049 runId: grandparentRunId,
1050 ordinal: 1,
1051 status: "completed",
1052 text: "GRANDPARENT_MARKER",
1053 stable: true,
1054 });
1055 yield* orchestrator.dispatch({
1056 type: "thread.fork",
1057 commandId: CommandId.make("side-chat-busy-parent-fork"),
1058 sourceThreadId: grandparentId,
1059 targetThreadId: parentId,
1060 sourcePoint: { type: "run", runId: grandparentRunId },
1061 createdBy: "user",
1062 creationSource: "web",
1063 });
1064 yield* writeImportedHistory(parentId, "PARENT_IMPORTED_MARKER");
1065 yield* writeParentRun({
1066 threadId: parentId,
1067 runId: RunId.make("side-chat-rewound-parent-run"),
1068 ordinal: 1,
1069 status: "rolled_back",
1070 text: "PARENT_ROLLED_BACK_MARKER",
1071 });
1072 yield* writeParentRun({
1073 threadId: parentId,
1074 runId: RunId.make("side-chat-busy-parent-run"),
1075 ordinal: 2,
1076 status: "running",
1077 text: "PARENT_RUNNING_MARKER",
1078 });
1079 yield* writeParentRun({
1080 threadId: parentId,
1081 runId: RunId.make("side-chat-queued-parent-run"),
1082 ordinal: 3,
1083 status: "queued",
1084 text: "PARENT_QUEUED_MARKER",
1085 });
1086 const fork = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
1087 orchestrator.dispatch({
1088 type: "thread.fork",
1089 commandId: CommandId.make(commandId),
1090 sourceThreadId,
1091 targetThreadId,
1092 sourcePoint: { type: "latest_stable" },
1093 sideChat: true,
1094 createdBy: "user",
1095 creationSource: "web",
1096 });
1097
1098 yield* fork("side-chat-busy-fork", parentId, sideChatId);
1099 const created = yield* orchestrator.getThreadProjection(sideChatId);
1100 assert.isTrue(created.thread.lineage.sideChat);
1101 assert.equal(created.thread.runtimeMode, "approval-required");
1102 assert.isNull(created.thread.forkedFrom);
1103 assert.deepEqual(created.contextTransfers[0]?.sourcePoint, { threadId: parentId });
1104
1105 const nested = yield* fork(
1106 "side-chat-busy-nested",
1107 sideChatId,
1108 ThreadId.make("side-chat-busy-nested"),
1109 ).pipe(Effect.flip);
1110 assert.equal(nested._tag, "OrchestratorDispatchError");
1111 // Either would take the side chat's lock before the parent's, against the delete cascade.
1112 const ontoParent = yield* fork("side-chat-busy-onto-parent", sideChatId, parentId).pipe(
1113 Effect.flip,
1114 );
1115 assert.equal(ontoParent._tag, "OrchestratorThreadAlreadyExistsError");
1116 const ontoExisting = yield* fork("side-chat-busy-onto-existing", parentId, sideChatId).pipe(
1117 Effect.flip,
1118 );
1119 assert.equal(ontoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1120 const plainOntoExisting = yield* orchestrator
1121 .dispatch({
1122 type: "thread.fork",
1123 commandId: CommandId.make("side-chat-busy-plain-onto-existing"),
1124 sourceThreadId: parentId,
1125 targetThreadId: sideChatId,
1126 sourcePoint: { type: "latest_stable" },
1127 createdBy: "user",
1128 creationSource: "web",
1129 })
1130 .pipe(Effect.flip);
1131 assert.equal(plainOntoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1132 const busyMergeBack = yield* orchestrator
1133 .dispatch({
1134 type: "thread.merge_back",
1135 commandId: CommandId.make("side-chat-busy-merge-back"),
1136 sourceThreadId: sideChatId,
1137 targetThreadId: parentId,
1138 sourcePoint: { type: "latest_stable" },
1139 createdBy: "user",
1140 creationSource: "web",
1141 })
1142 .pipe(Effect.flip);
1143 assert.include(String(busyMergeBack.cause), "active work");
1144
1145 yield* orchestrator.dispatch({
1146 type: "message.dispatch",
1147 commandId: CommandId.make("side-chat-busy-first-message"),
1148 threadId: sideChatId,
1149 messageId: MessageId.make("side-chat-busy-first-message"),
1150 text: "What is the main thread doing?",
1151 attachments: [],
1152 dispatchMode: { type: "start_immediately" },
1153 createdBy: "user",
1154 creationSource: "web",
1155 });
1156 const started = yield* orchestrator.getThreadProjection(sideChatId);
1157 const [handoff] = started.contextHandoffs;
1158 assert.lengthOf(started.contextHandoffs, 1);
1159 assert.deepEqual(started.contextTransfers[0]?.resolution, {
1160 strategy: "portable_context",
1161 contextHandoffId: handoff!.id,
1162 });
1163 assert.include(handoff!.summaryText, "You are in a side chat beside the main thread.");
1164 // Inherited rows come first, so the cap truncates them first.
1165 assert.isAbove(
1166 handoff!.summaryText.indexOf("- User: PARENT_IMPORTED_MARKER"),
1167 handoff!.summaryText.indexOf("- User: GRANDPARENT_MARKER"),
1168 );
1169 assert.include(handoff!.summaryText, "- User: GRANDPARENT_MARKER");
1170 assert.notInclude(handoff!.summaryText, "PARENT_ROLLED_BACK_MARKER");
1171 assert.notInclude(handoff!.summaryText, "PARENT_QUEUED_MARKER");
1172 assert.include(handoff!.summaryText, "- User: PARENT_IMPORTED_MARKER");
1173 assert.include(handoff!.summaryText, "- User: PARENT_RUNNING_MARKER");
1174 assert.include(handoff!.summaryText, `t3_thread_read on thread ${parentId}`);
1175 assert.equal(
1176 started.messages.find((message) => message.role === "user")?.text,
1177 "What is the main thread doing?",
1178 );
1179
1180 yield* orchestrator.dispatch({
1181 type: "thread.delete",
1182 commandId: CommandId.make("side-chat-busy-delete-parent"),
1183 threadId: parentId,
1184 });
1185 assert.isNotNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);
1186 }).pipe(Effect.provide(forkCases[0]!.layer)),
1187);
1188
1189it.effect("merge-back rejects a second fork's context until the first is consumed", () =>
1190 Effect.gen(function* () {
1191 const orchestrator = yield* Orchestrator.OrchestratorV2;
1192 const parentId = ThreadId.make("merge-back-guard-parent");
1193 const parentRunId = RunId.make("merge-back-guard-parent-run");
1194 yield* createParent(parentId);
1195 yield* writeParentRun({
1196 threadId: parentId,
1197 runId: parentRunId,
1198 ordinal: 1,
1199 status: "completed",
1200 text: "Parent work",
1201 });
1202 const forkAndRun = (name: string) =>
1203 Effect.gen(function* () {
1204 const threadId = ThreadId.make(`merge-back-guard-${name}`);
1205 const runId = RunId.make(`merge-back-guard-${name}-run`);
1206 yield* orchestrator.dispatch({
1207 type: "thread.fork",
1208 commandId: CommandId.make(`merge-back-guard-fork-${name}`),
1209 sourceThreadId: parentId,
1210 targetThreadId: threadId,
1211 sourcePoint: { type: "run", runId: parentRunId },
1212 sideChat: true,
1213 createdBy: "user",
1214 creationSource: "web",
1215 });
1216 yield* writeParentRun({ threadId, runId, ordinal: 1, status: "completed", text: name });
1217 return { threadId, runId };
1218 });
1219 const mergeBack = (commandId: string, fork: { threadId: ThreadId; runId: RunId }) =>
1220 orchestrator.dispatch({
1221 type: "thread.merge_back",
1222 commandId: CommandId.make(commandId),
1223 sourceThreadId: fork.threadId,
1224 targetThreadId: parentId,
1225 sourcePoint: { type: "run", runId: fork.runId },
1226 createdBy: "user",
1227 creationSource: "web",
1228 });
1229 const first = yield* forkAndRun("first");
1230 const second = yield* forkAndRun("second");
1231
1232 yield* mergeBack("merge-back-guard-first", first);
1233 const rejected = yield* mergeBack("merge-back-guard-second", second).pipe(Effect.flip);
1234 assert.include(String(rejected.cause), "pending context from another side chat or fork");
1235 yield* mergeBack("merge-back-guard-first-again", first);
1236 // That pending merge-back targets the parent, so it does not block one into `first`.
1237 const nested = { threadId: ThreadId.make("merge-back-guard-nested") };
1238 const nestedRunId = RunId.make("merge-back-guard-nested-run");
1239 yield* orchestrator.dispatch({
1240 type: "thread.fork",
1241 commandId: CommandId.make("merge-back-guard-fork-nested"),
1242 sourceThreadId: first.threadId,
1243 targetThreadId: nested.threadId,
1244 sourcePoint: { type: "run", runId: first.runId },
1245 createdBy: "user",
1246 creationSource: "web",
1247 });
1248 yield* writeParentRun({
1249 threadId: nested.threadId,
1250 runId: nestedRunId,
1251 ordinal: 1,
1252 status: "completed",
1253 text: "nested",
1254 });
1255 yield* orchestrator.dispatch({
1256 type: "thread.merge_back",
1257 commandId: CommandId.make("merge-back-guard-nested"),
1258 sourceThreadId: nested.threadId,
1259 targetThreadId: first.threadId,
1260 sourcePoint: { type: "run", runId: nestedRunId },
1261 createdBy: "user",
1262 creationSource: "web",
1263 });
1264
1265 const parent = yield* orchestrator.getThreadProjection(parentId);
1266 assert.deepEqual(
1267 parent.contextTransfers
1268 .filter((transfer) => transfer.type === "merge_back")
1269 .map((transfer) => [transfer.sourceThreadId, transfer.status]),
1270 [
1271 [first.threadId, "superseded"],
1272 [first.threadId, "pending"],
1273 ],
1274 );
1275 }).pipe(Effect.provide(forkCases[0]!.layer)),
1276);