Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 type ApplicationStoredEvent,
5 CommandId,
6 ContextTransferId,
7 EventId,
8 MessageId,
9 type ModelSelection,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ProviderThreadId,
14 RunId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as DateTime from "effect/DateTime";
19import * as Layer from "effect/Layer";
20import * as Queue from "effect/Queue";
21import * as Stream from "effect/Stream";
22import * as TestClock from "effect/testing/TestClock";
23import * as SqlClient from "effect/unstable/sql/SqlClient";
24
25import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
26import { ServerConfig } from "../config.ts";
27import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
28import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
29import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
30import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
31import { OrchestrationEventStore } from "../persistence/Services/OrchestrationEventStore.ts";
32import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts";
33import { ServerSettingsService } from "../serverSettings.ts";
34import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts";
35import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts";
36import type { ProviderInstance } from "../provider/ProviderDriver.ts";
37import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
38import * as VcsProcess from "../vcs/VcsProcess.ts";
39import { LegacyV1ThreadImporter, LegacyV1ThreadImportError } from "./LegacyV1ThreadImporter.ts";
40import {
41 OrchestratorDispatchError,
42 OrchestratorProjectionError,
43 OrchestratorV2,
44} from "./Orchestrator.ts";
45import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts";
46import { EventSinkV2 } from "./EventSink.ts";
47import { ProjectionMaintenanceV2 } from "./ProjectionMaintenance.ts";
48import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
49import { OrchestrationV2EventSinkLayerLive, OrchestrationV2LayerLive } from "./runtimeLayer.ts";
50import { shellStreamItemFromThreadShell } from "./ShellStream.ts";
51import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
52import { ThreadManagementService } from "./ThreadManagementService.ts";
53
54const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
55 prefix: "t3-orchestration-v2-runtime-layer-",
56});
57
58const modelSelection = {
59 instanceId: ProviderInstanceId.make("codex"),
60 model: "gpt-5.4",
61} satisfies ModelSelection;
62
63const VcsDriverRegistryTestLayer = VcsDriverRegistry.layer.pipe(
64 Layer.provide(VcsProcess.layer),
65 Layer.provide(ServerConfigLayer),
66 Layer.provide(NodeServices.layer),
67);
68
69const CheckpointStoreTestLayer = CheckpointStore.layer.pipe(
70 Layer.provide(VcsDriverRegistryTestLayer),
71);
72
73const driver = ProviderDriverKind.make("codex");
74const orchestrationAdapter = {
75 instanceId: modelSelection.instanceId,
76 driver,
77 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
78 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
79 openSession: () => Effect.die("sessions are not used by lifecycle tests"),
80} as ProviderAdapterV2Shape;
81const providerInstance = {
82 instanceId: modelSelection.instanceId,
83 driverKind: driver,
84 continuationIdentity: {
85 driverKind: driver,
86 continuationKey: "codex:test",
87 },
88 displayName: "Codex test",
89 enabled: true,
90 snapshot: {} as ProviderInstance["snapshot"],
91 orchestrationAdapter,
92 textGeneration: {} as ProviderInstance["textGeneration"],
93} satisfies ProviderInstance;
94
95const TestProviderInstanceRegistry = Layer.succeed(ProviderInstanceRegistry, {
96 getInstance: (instanceId) =>
97 Effect.succeed(instanceId === providerInstance.instanceId ? providerInstance : undefined),
98 listInstances: Effect.succeed([providerInstance]),
99 listUnavailable: Effect.succeed([]),
100 streamChanges: Stream.empty,
101 subscribeChanges: Effect.never,
102});
103
104const TestLayer = Layer.merge(OrchestrationV2LayerLive, OrchestrationV2EventSinkLayerLive).pipe(
105 Layer.provide(mcpSessionRegistryTestLayer),
106 Layer.provide(SqlitePersistenceMemory),
107 Layer.provide(CheckpointStoreTestLayer),
108 Layer.provide(ServerConfigLayer),
109 Layer.provide(ServerSettingsService.layerTest()),
110 Layer.provide(TestProviderInstanceRegistry),
111 Layer.provide(NodeServices.layer),
112);
113
114const LegacyImportTestLayer = OrchestrationV2LayerLive.pipe(
115 Layer.provide(mcpSessionRegistryTestLayer),
116 Layer.provideMerge(SqlitePersistenceMemory),
117 Layer.provide(CheckpointStoreTestLayer),
118 Layer.provide(ServerConfigLayer),
119 Layer.provide(ServerSettingsService.layerTest()),
120 Layer.provide(TestProviderInstanceRegistry),
121 Layer.provide(NodeServices.layer),
122);
123
124const SharedApplicationDataPlaneTestLayer = Layer.merge(
125 OrchestrationLayerLive,
126 OrchestrationV2LayerLive,
127).pipe(
128 Layer.provide(
129 Layer.succeed(ProjectEnrichmentService, {
130 peek: () =>
131 Effect.succeed({
132 repositoryIdentity: null,
133 faviconPath: null,
134 repositoryIdentityResolved: false,
135 }),
136 request: () => Effect.void,
137 getAvailable: () =>
138 Effect.succeed({
139 repositoryIdentity: null,
140 faviconPath: null,
141 repositoryIdentityResolved: false,
142 }),
143 invalidate: () => Effect.void,
144 subscribeChanges: Effect.never,
145 }),
146 ),
147 Layer.provide(mcpSessionRegistryTestLayer),
148 Layer.provideMerge(SqlitePersistenceMemory),
149 Layer.provide(CheckpointStoreTestLayer),
150 Layer.provide(ServerConfigLayer),
151 Layer.provide(ServerSettingsService.layerTest()),
152 Layer.provide(TestProviderInstanceRegistry),
153 Layer.provide(NodeServices.layer),
154);
155
156it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
157 it.effect("creates and reads a thread through the production V2 composition", () =>
158 Effect.gen(function* () {
159 const orchestrator = yield* OrchestratorV2;
160 const threadId = ThreadId.make("runtime-layer-thread");
161 const projectId = ProjectId.make("runtime-layer-project");
162
163 const result = yield* orchestrator.dispatch({
164 type: "thread.create",
165 createdBy: "user",
166 creationSource: "web",
167 commandId: CommandId.make("runtime-layer-create"),
168 threadId,
169 projectId,
170 title: "Runtime layer thread",
171 modelSelection: modelSelection,
172 runtimeMode: "full-access",
173 interactionMode: "default",
174 branch: null,
175 worktreePath: null,
176 });
177
178 const projection = yield* orchestrator.getThreadProjection(threadId);
179
180 assert.equal(result.sequence, 1);
181 assert.equal(projection.thread.id, threadId);
182 assert.equal(projection.thread.projectId, projectId);
183 assert.equal(projection.thread.providerInstanceId, "codex");
184 assert.deepEqual(projection.runs, []);
185 }),
186 );
187
188 it.effect("merges an explicit provider-finished run while checkpoint capture is pending", () =>
189 Effect.gen(function* () {
190 const orchestrator = yield* OrchestratorV2;
191 const eventSink = yield* EventSinkV2;
192 const now = yield* DateTime.now;
193 const projectId = ProjectId.make("runtime-layer-waiting-merge-project");
194 const targetThreadId = ThreadId.make("runtime-layer-waiting-merge-target");
195 const sourceThreadId = ThreadId.make("runtime-layer-waiting-merge-source");
196 const baseRunId = RunId.make("runtime-layer-waiting-merge-base-run");
197 const sourceRunId = RunId.make("runtime-layer-waiting-merge-source-run");
198 const sourceProviderThreadId = ProviderThreadId.make(
199 "runtime-layer-waiting-merge-provider-thread",
200 );
201 const forkTransferId = ContextTransferId.make("runtime-layer-waiting-merge-fork-transfer");
202
203 yield* orchestrator.dispatch({
204 type: "thread.create",
205 createdBy: "user",
206 creationSource: "web",
207 commandId: CommandId.make("runtime-layer-waiting-merge-create-target"),
208 threadId: targetThreadId,
209 projectId,
210 title: "Waiting merge target",
211 modelSelection,
212 runtimeMode: "full-access",
213 interactionMode: "default",
214 branch: null,
215 worktreePath: null,
216 });
217 const target = yield* orchestrator.getThreadProjection(targetThreadId);
218
219 yield* eventSink.write({
220 commandId: CommandId.make("runtime-layer-waiting-merge-seed"),
221 events: [
222 {
223 id: EventId.make("runtime-layer-waiting-merge-source-thread-event"),
224 type: "thread.created",
225 threadId: sourceThreadId,
226 providerInstanceId: modelSelection.instanceId,
227 occurredAt: now,
228 payload: {
229 ...target.thread,
230 id: sourceThreadId,
231 title: "Waiting merge source",
232 activeProviderThreadId: null,
233 lineage: {
234 parentThreadId: targetThreadId,
235 relationshipToParent: "fork",
236 rootThreadId: targetThreadId,
237 },
238 forkedFrom: {
239 type: "run",
240 threadId: targetThreadId,
241 runId: baseRunId,
242 },
243 createdAt: now,
244 updatedAt: now,
245 },
246 },
247 {
248 id: EventId.make("runtime-layer-waiting-merge-fork-transfer-event"),
249 type: "context-transfer.created",
250 threadId: sourceThreadId,
251 providerInstanceId: modelSelection.instanceId,
252 occurredAt: now,
253 payload: {
254 id: forkTransferId,
255 type: "fork",
256 sourceThreadId: targetThreadId,
257 targetThreadId: sourceThreadId,
258 sourcePoint: { threadId: targetThreadId, runId: baseRunId },
259 basePoint: null,
260 sourceProviderInstanceId: modelSelection.instanceId,
261 targetProviderInstanceId: modelSelection.instanceId,
262 targetRunId: null,
263 status: "consumed",
264 resolution: null,
265 createdBy: "user",
266 error: null,
267 createdAt: now,
268 updatedAt: now,
269 consumedAt: now,
270 },
271 },
272 {
273 id: EventId.make("runtime-layer-waiting-merge-provider-thread-event"),
274 type: "provider-thread.updated",
275 threadId: sourceThreadId,
276 driver,
277 providerInstanceId: modelSelection.instanceId,
278 occurredAt: now,
279 payload: {
280 id: sourceProviderThreadId,
281 driver,
282 providerInstanceId: modelSelection.instanceId,
283 providerSessionId: null,
284 appThreadId: sourceThreadId,
285 ownerNodeId: null,
286 nativeThreadRef: {
287 driver,
288 nativeId: "native-waiting-merge-source",
289 strength: "strong",
290 },
291 nativeConversationHeadRef: null,
292 status: "idle",
293 firstRunOrdinal: 1,
294 lastRunOrdinal: 1,
295 handoffIds: [],
296 forkedFrom: null,
297 createdAt: now,
298 updatedAt: now,
299 },
300 },
301 {
302 id: EventId.make("runtime-layer-waiting-merge-source-run-event"),
303 type: "run.created",
304 threadId: sourceThreadId,
305 runId: sourceRunId,
306 providerInstanceId: modelSelection.instanceId,
307 occurredAt: now,
308 payload: {
309 id: sourceRunId,
310 threadId: sourceThreadId,
311 ordinal: 1,
312 providerInstanceId: modelSelection.instanceId,
313 modelSelection,
314 providerThreadId: sourceProviderThreadId,
315 userMessageId: MessageId.make("runtime-layer-waiting-merge-message"),
316 rootNodeId: null,
317 activeAttemptId: null,
318 status: "waiting",
319 queuePosition: null,
320 requestedAt: now,
321 startedAt: now,
322 completedAt: null,
323 checkpointId: null,
324 contextHandoffId: null,
325 },
326 },
327 ],
328 });
329
330 yield* orchestrator.dispatch({
331 type: "thread.merge_back",
332 createdBy: "user",
333 creationSource: "mobile",
334 commandId: CommandId.make("runtime-layer-waiting-merge"),
335 sourceThreadId,
336 targetThreadId,
337 sourcePoint: { type: "run", runId: sourceRunId },
338 createdAt: now,
339 });
340
341 const mergedTarget = yield* orchestrator.getThreadProjection(targetThreadId);
342 const transfer = mergedTarget.contextTransfers.find(
343 (candidate) => candidate.type === "merge_back",
344 );
345 assert.isDefined(transfer);
346 assert.equal(transfer.status, "pending");
347 assert.equal(transfer.sourceThreadId, sourceThreadId);
348 assert.equal(transfer.targetThreadId, targetThreadId);
349 assert.equal(transfer.sourcePoint.runId, sourceRunId);
350 assert.isUndefined(transfer.sourcePoint.checkpointId);
351 assert.equal(transfer.sourcePoint.providerThreadRef?.nativeId, "native-waiting-merge-source");
352 assert.equal(transfer.basePoint?.runId, baseRunId);
353 assert.isNull(transfer.error);
354 }),
355 );
356});
357
358it.layer(LegacyImportTestLayer)("OrchestrationV2 legacy import", (it) => {
359 it.effect("hydrates imported transcripts before commands and propagates hydration failures", () =>
360 Effect.gen(function* () {
361 const sql = yield* SqlClient.SqlClient;
362 const importer = yield* LegacyV1ThreadImporter;
363 const maintenance = yield* ProjectionMaintenanceV2;
364 const orchestrator = yield* OrchestratorV2;
365 const threadManagement = yield* ThreadManagementService;
366 const metadataThreadId = ThreadId.make("runtime-layer-legacy-metadata-thread");
367 const failureThreadId = ThreadId.make("runtime-layer-legacy-failure-thread");
368 const projectId = ProjectId.make("runtime-layer-legacy-project");
369
370 yield* sql`
371 INSERT INTO projection_projects (
372 project_id,
373 title,
374 workspace_root,
375 default_model_selection_json,
376 scripts_json,
377 created_at,
378 updated_at,
379 deleted_at
380 ) VALUES (
381 ${projectId},
382 'Legacy project',
383 '/tmp/runtime-layer-legacy-project',
384 '{"instanceId":"codex","model":"gpt-5.4"}',
385 '[]',
386 '2026-01-01T00:00:00.000Z',
387 '2026-01-04T00:00:00.000Z',
388 NULL
389 )
390 `;
391 yield* sql`
392 INSERT INTO projection_threads (
393 thread_id,
394 project_id,
395 title,
396 model_selection_json,
397 runtime_mode,
398 interaction_mode,
399 branch,
400 worktree_path,
401 latest_turn_id,
402 created_at,
403 updated_at,
404 archived_at,
405 settled_override,
406 settled_at,
407 deleted_at
408 ) VALUES
409 (
410 ${metadataThreadId},
411 ${projectId},
412 'Legacy metadata title',
413 '{"instanceId":"codex","model":"gpt-5.4"}',
414 'full-access',
415 'default',
416 'main',
417 '/tmp/runtime-layer-legacy-project',
418 NULL,
419 '2026-01-01T00:00:00.000Z',
420 '2026-01-04T00:00:00.000Z',
421 NULL,
422 NULL,
423 NULL,
424 NULL
425 ),
426 (
427 ${failureThreadId},
428 ${projectId},
429 'Legacy failure title',
430 '{"instanceId":"codex","model":"gpt-5.4"}',
431 'full-access',
432 'default',
433 'main',
434 '/tmp/runtime-layer-legacy-project',
435 NULL,
436 '2026-01-01T00:00:00.000Z',
437 '2026-01-04T00:00:00.000Z',
438 NULL,
439 NULL,
440 NULL,
441 NULL
442 )
443 `;
444 yield* sql`
445 INSERT INTO projection_thread_messages (
446 message_id,
447 thread_id,
448 turn_id,
449 role,
450 text,
451 attachments_json,
452 is_streaming,
453 created_at,
454 updated_at
455 ) VALUES
456 (
457 'message:runtime-layer-legacy:1',
458 ${metadataThreadId},
459 NULL,
460 'user',
461 'First imported question',
462 '[]',
463 0,
464 '2026-01-01T01:00:00.000Z',
465 '2026-01-01T01:00:00.000Z'
466 ),
467 (
468 'message:runtime-layer-legacy:2',
469 ${metadataThreadId},
470 NULL,
471 'assistant',
472 'First imported answer',
473 '[]',
474 0,
475 '2026-01-02T01:00:00.000Z',
476 '2026-01-02T01:00:00.000Z'
477 ),
478 (
479 'message:runtime-layer-legacy:3',
480 ${metadataThreadId},
481 NULL,
482 'user',
483 'Latest imported question',
484 '[]',
485 0,
486 '2026-01-03T01:00:00.000Z',
487 '2026-01-03T01:00:00.000Z'
488 ),
489 (
490 'message:runtime-layer-legacy:failure',
491 ${failureThreadId},
492 NULL,
493 'user',
494 'Imported context must load before archive',
495 '[]',
496 0,
497 '2026-01-03T01:00:00.000Z',
498 '2026-01-03T01:00:00.000Z'
499 )
500 `;
501
502 yield* importer.reconcileShells;
503 const rebuilt = yield* maintenance.rebuild;
504 assert.isTrue(rebuilt.valid);
505
506 yield* threadManagement.dispatch({
507 type: "thread.metadata.update",
508 commandId: CommandId.make("runtime-layer-legacy-metadata-update"),
509 threadId: metadataThreadId,
510 title: "Updated after import",
511 });
512 const updatedProjection = yield* threadManagement.getThreadProjection(metadataThreadId);
513 assert.equal(updatedProjection.thread.title, "Updated after import");
514 assert.deepEqual(
515 updatedProjection.messages.map((message) => message.text),
516 ["First imported question", "First imported answer", "Latest imported question"],
517 );
518
519 yield* sql`
520 ALTER TABLE projection_thread_messages
521 RENAME TO projection_thread_messages_unavailable
522 `;
523 const { projectionFailure, hydrationFailure } = yield* Effect.all({
524 projectionFailure: threadManagement.getThreadProjection(failureThreadId).pipe(Effect.flip),
525 hydrationFailure: threadManagement
526 .dispatch({
527 type: "thread.archive",
528 commandId: CommandId.make("runtime-layer-legacy-failed-archive"),
529 threadId: failureThreadId,
530 })
531 .pipe(Effect.flip),
532 }).pipe(
533 Effect.ensuring(
534 sql`
535 ALTER TABLE projection_thread_messages_unavailable
536 RENAME TO projection_thread_messages
537 `.pipe(Effect.orDie),
538 ),
539 );
540 assert.instanceOf(projectionFailure, OrchestratorProjectionError);
541 assert.instanceOf(projectionFailure.cause, LegacyV1ThreadImportError);
542 assert.instanceOf(hydrationFailure, OrchestratorDispatchError);
543 assert.instanceOf(hydrationFailure.cause, LegacyV1ThreadImportError);
544
545 const projectionAfterFailure = yield* orchestrator.getThreadProjection(failureThreadId);
546 assert.isNull(projectionAfterFailure.thread.archivedAt);
547
548 yield* threadManagement.dispatch({
549 type: "thread.archive",
550 commandId: CommandId.make("runtime-layer-legacy-retried-archive"),
551 threadId: failureThreadId,
552 });
553 const projectionAfterRetry = yield* threadManagement.getThreadProjection(failureThreadId);
554 assert.isNotNull(projectionAfterRetry.thread.archivedAt);
555 }),
556 );
557});
558
559it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
560 it.effect("applies lifecycle commands idempotently and emits archive/removal shell deltas", () =>
561 Effect.gen(function* () {
562 const orchestrator = yield* OrchestratorV2;
563 const threadId = ThreadId.make("runtime-layer-lifecycle-thread");
564 const create = {
565 type: "thread.create" as const,
566 createdBy: "user" as const,
567 creationSource: "web" as const,
568 commandId: CommandId.make("runtime-layer-lifecycle-create"),
569 threadId,
570 projectId: ProjectId.make("runtime-layer-lifecycle-project"),
571 title: "Lifecycle thread",
572 modelSelection,
573 runtimeMode: "full-access" as const,
574 interactionMode: "default" as const,
575 branch: null,
576 worktreePath: null,
577 };
578
579 const firstCreate = yield* orchestrator.dispatch(create);
580 const retriedCreate = yield* orchestrator.dispatch(create);
581 assert.equal(retriedCreate.sequence, firstCreate.sequence);
582 assert.lengthOf(retriedCreate.storedEvents, 1);
583
584 yield* orchestrator.dispatch({
585 type: "thread.metadata.update",
586 commandId: CommandId.make("runtime-layer-lifecycle-metadata"),
587 threadId,
588 title: "Renamed lifecycle thread",
589 branch: "feature/v2",
590 worktreePath: "/tmp/t3-v2-worktree",
591 });
592 const staleWorkspaceUpdate = yield* orchestrator
593 .dispatch({
594 type: "thread.metadata.update",
595 commandId: CommandId.make("runtime-layer-lifecycle-stale-workspace"),
596 threadId,
597 branch: "feature/stale",
598 worktreePath: "/tmp/stale-worktree",
599 expectedWorktreePath: null,
600 })
601 .pipe(Effect.flip);
602 assert.instanceOf(staleWorkspaceUpdate, OrchestratorDispatchError);
603 const projectionAfterStaleWorkspaceUpdate = yield* orchestrator.getThreadProjection(threadId);
604 assert.equal(projectionAfterStaleWorkspaceUpdate.thread.branch, "feature/v2");
605 assert.equal(projectionAfterStaleWorkspaceUpdate.thread.worktreePath, "/tmp/t3-v2-worktree");
606 yield* orchestrator.dispatch({
607 type: "thread.runtime-mode.set",
608 commandId: CommandId.make("runtime-layer-lifecycle-runtime"),
609 threadId,
610 runtimeMode: "approval-required",
611 });
612 yield* orchestrator.dispatch({
613 type: "thread.interaction-mode.set",
614 commandId: CommandId.make("runtime-layer-lifecycle-interaction"),
615 threadId,
616 interactionMode: "plan",
617 });
618 yield* orchestrator.dispatch({
619 type: "thread.model-selection.set",
620 commandId: CommandId.make("runtime-layer-lifecycle-model"),
621 threadId,
622 modelSelection: { ...modelSelection, model: "gpt-5.5" },
623 });
624
625 yield* orchestrator.dispatch({
626 type: "thread.settle",
627 commandId: CommandId.make("runtime-layer-lifecycle-settle"),
628 threadId,
629 });
630 const settledProjection = yield* orchestrator.getThreadProjection(threadId);
631 assert.equal(settledProjection.thread.settledOverride, "settled");
632 assert.isNotNull(settledProjection.thread.settledAt);
633
634 yield* orchestrator.dispatch({
635 type: "thread.unsettle",
636 commandId: CommandId.make("runtime-layer-lifecycle-unsettle"),
637 threadId,
638 reason: "user",
639 });
640 const activeProjection = yield* orchestrator.getThreadProjection(threadId);
641 assert.equal(activeProjection.thread.settledOverride, "active");
642 assert.isNull(activeProjection.thread.settledAt);
643
644 const archive = yield* orchestrator.dispatch({
645 type: "thread.archive",
646 commandId: CommandId.make("runtime-layer-lifecycle-archive"),
647 threadId,
648 });
649 const archivedShell = yield* orchestrator.getShellSnapshot();
650 assert.notInclude(
651 archivedShell.threads.map((thread) => thread.id),
652 threadId,
653 );
654 assert.include(
655 archivedShell.archivedThreads.map((thread) => thread.id),
656 threadId,
657 );
658 assert.deepEqual(
659 shellStreamItemFromThreadShell({
660 stored: archive.storedEvents[0]!,
661 shell: yield* orchestrator.getThreadShell(threadId),
662 }),
663 {
664 kind: "thread.updated",
665 sequence: archive.sequence,
666 location: "archive",
667 thread: archivedShell.archivedThreads[0]!,
668 },
669 );
670
671 const remove = yield* orchestrator.dispatch({
672 type: "thread.delete",
673 commandId: CommandId.make("runtime-layer-lifecycle-delete"),
674 threadId,
675 });
676 const deletedShell = yield* orchestrator.getShellSnapshot();
677 assert.notInclude(
678 deletedShell.threads.map((thread) => thread.id),
679 threadId,
680 );
681 assert.notInclude(
682 deletedShell.archivedThreads.map((thread) => thread.id),
683 threadId,
684 );
685 assert.deepEqual(
686 shellStreamItemFromThreadShell({
687 stored: remove.storedEvents[0]!,
688 shell: yield* orchestrator.getThreadShell(threadId),
689 }),
690 {
691 kind: "thread.removed",
692 sequence: remove.sequence,
693 location: "archive",
694 threadId,
695 },
696 );
697
698 const projection = yield* orchestrator.getThreadProjection(threadId);
699 assert.equal(projection.thread.title, "Renamed lifecycle thread");
700 assert.equal(projection.thread.branch, "feature/v2");
701 assert.equal(projection.thread.worktreePath, "/tmp/t3-v2-worktree");
702 assert.equal(projection.thread.runtimeMode, "approval-required");
703 assert.equal(projection.thread.interactionMode, "plan");
704 assert.equal(projection.thread.modelSelection.model, "gpt-5.5");
705 assert.isNotNull(projection.thread.archivedAt);
706 assert.isNotNull(projection.thread.deletedAt);
707 }),
708 );
709
710 it.effect("persists rejected command receipts across retries", () =>
711 Effect.gen(function* () {
712 const orchestrator = yield* OrchestratorV2;
713 const command = {
714 type: "thread.archive" as const,
715 commandId: CommandId.make("runtime-layer-rejected-command"),
716 threadId: ThreadId.make("runtime-layer-missing-thread"),
717 };
718
719 const first = yield* orchestrator.dispatch(command).pipe(Effect.flip);
720 const retry = yield* orchestrator.dispatch(command).pipe(Effect.flip);
721
722 assert.equal(first._tag, "OrchestratorProjectionError");
723 assert.equal(retry._tag, "OrchestratorCommandPreviouslyRejectedError");
724 }),
725 );
726
727 it.effect("rejects settling a thread while a run is active", () =>
728 Effect.gen(function* () {
729 const orchestrator = yield* OrchestratorV2;
730 const threadId = ThreadId.make("runtime-layer-active-settle-thread");
731
732 yield* orchestrator.dispatch({
733 type: "thread.create",
734 createdBy: "user",
735 creationSource: "web",
736 commandId: CommandId.make("runtime-layer-active-settle-create"),
737 threadId,
738 projectId: ProjectId.make("runtime-layer-active-settle-project"),
739 title: "Active settle",
740 modelSelection,
741 runtimeMode: "full-access",
742 interactionMode: "default",
743 branch: null,
744 worktreePath: "/tmp/runtime-layer-active-settle",
745 });
746 yield* orchestrator.dispatch({
747 type: "thread.settle",
748 commandId: CommandId.make("runtime-layer-active-settle-initial"),
749 threadId,
750 });
751 yield* orchestrator.dispatch({
752 type: "message.dispatch",
753 createdBy: "user",
754 creationSource: "web",
755 commandId: CommandId.make("runtime-layer-active-settle-message"),
756 threadId,
757 messageId: MessageId.make("runtime-layer-active-settle-message"),
758 text: "Keep this run active.",
759 attachments: [],
760 modelSelection,
761 dispatchMode: { type: "start_immediately" },
762 });
763
764 const error = yield* orchestrator
765 .dispatch({
766 type: "thread.settle",
767 commandId: CommandId.make("runtime-layer-active-settle"),
768 threadId,
769 })
770 .pipe(Effect.flip);
771
772 assert.equal(error._tag, "OrchestratorDispatchError");
773 const projection = yield* orchestrator.getThreadProjection(threadId);
774 assert.equal(projection.runs[0]?.status, "starting");
775 assert.isNull(projection.thread.settledOverride);
776 assert.isNull(projection.thread.settledAt);
777 }),
778 );
779
780 it.effect("cancels queued work when a thread is archived", () =>
781 Effect.gen(function* () {
782 const orchestrator = yield* OrchestratorV2;
783 const threadId = ThreadId.make("runtime-layer-archive-queued-thread");
784
785 yield* orchestrator.dispatch({
786 type: "thread.create",
787 createdBy: "user",
788 creationSource: "web",
789 commandId: CommandId.make("runtime-layer-archive-queued-create"),
790 threadId,
791 projectId: ProjectId.make("runtime-layer-archive-queued-project"),
792 title: "Archive queued work",
793 modelSelection,
794 runtimeMode: "full-access",
795 interactionMode: "default",
796 branch: null,
797 worktreePath: "/tmp/runtime-layer-archive-queued",
798 });
799 yield* orchestrator.dispatch({
800 type: "message.dispatch",
801 createdBy: "user",
802 creationSource: "web",
803 commandId: CommandId.make("runtime-layer-archive-queued-active-message"),
804 threadId,
805 messageId: MessageId.make("runtime-layer-archive-queued-active-message"),
806 text: "Keep the provider occupied.",
807 attachments: [],
808 modelSelection,
809 dispatchMode: { type: "start_immediately" },
810 });
811 yield* orchestrator.dispatch({
812 type: "message.dispatch",
813 createdBy: "user",
814 creationSource: "web",
815 commandId: CommandId.make("runtime-layer-archive-queued-next-message"),
816 threadId,
817 messageId: MessageId.make("runtime-layer-archive-queued-next-message"),
818 text: "Do not run this after archive.",
819 attachments: [],
820 modelSelection,
821 dispatchMode: { type: "queue_after_active" },
822 });
823
824 const beforeArchive = yield* orchestrator.getThreadProjection(threadId);
825 const activeRun = beforeArchive.runs.find((run) => run.status === "starting");
826 const queuedRun = beforeArchive.runs.find((run) => run.status === "queued");
827 assert.isDefined(activeRun);
828 assert.isDefined(queuedRun);
829
830 yield* orchestrator.dispatch({
831 type: "thread.archive",
832 commandId: CommandId.make("runtime-layer-archive-queued-archive"),
833 threadId,
834 });
835
836 const archived = yield* orchestrator.getThreadProjection(threadId);
837 assert.isNotNull(archived.thread.archivedAt);
838 assert.equal(archived.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
839 assert.equal(
840 archived.attempts.find((attempt) => attempt.runId === queuedRun.id)?.status,
841 "cancelled",
842 );
843 assert.equal(archived.nodes.find((node) => node.runId === queuedRun.id)?.status, "cancelled");
844 assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
845
846 const promoteError = yield* orchestrator
847 .dispatch({
848 type: "queued-message.promote-to-steer",
849 commandId: CommandId.make("runtime-layer-archive-queued-promote"),
850 threadId,
851 queuedRunId: queuedRun.id,
852 targetRunId: activeRun.id,
853 })
854 .pipe(Effect.flip);
855 assert.equal(promoteError._tag, "OrchestratorDispatchError");
856
857 const afterPromotion = yield* orchestrator.getThreadProjection(threadId);
858 assert.equal(afterPromotion.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
859 }),
860 );
861
862 it.effect("promotes only one queued run after each terminal run", () =>
863 Effect.gen(function* () {
864 const orchestrator = yield* OrchestratorV2;
865 const eventSink = yield* EventSinkV2;
866 const threadId = ThreadId.make("runtime-layer-serialized-queue-thread");
867
868 yield* orchestrator.dispatch({
869 type: "thread.create",
870 createdBy: "user",
871 creationSource: "web",
872 commandId: CommandId.make("runtime-layer-serialized-queue-create"),
873 threadId,
874 projectId: ProjectId.make("runtime-layer-serialized-queue-project"),
875 title: "Serialized queue",
876 modelSelection,
877 runtimeMode: "full-access",
878 interactionMode: "default",
879 branch: null,
880 worktreePath: process.cwd(),
881 });
882 yield* orchestrator.dispatch({
883 type: "message.dispatch",
884 createdBy: "user",
885 creationSource: "web",
886 commandId: CommandId.make("runtime-layer-serialized-queue-active"),
887 threadId,
888 messageId: MessageId.make("runtime-layer-serialized-queue-active"),
889 text: "Active",
890 attachments: [],
891 modelSelection,
892 dispatchMode: { type: "start_immediately" },
893 });
894 yield* orchestrator.dispatch({
895 type: "message.dispatch",
896 createdBy: "user",
897 creationSource: "web",
898 commandId: CommandId.make("runtime-layer-serialized-queue-first"),
899 threadId,
900 messageId: MessageId.make("runtime-layer-serialized-queue-first"),
901 text: "First queued",
902 attachments: [],
903 modelSelection,
904 dispatchMode: { type: "queue_after_active" },
905 });
906 yield* orchestrator.dispatch({
907 type: "message.dispatch",
908 createdBy: "user",
909 creationSource: "web",
910 commandId: CommandId.make("runtime-layer-serialized-queue-second"),
911 threadId,
912 messageId: MessageId.make("runtime-layer-serialized-queue-second"),
913 text: "Second queued",
914 attachments: [],
915 modelSelection,
916 dispatchMode: { type: "queue_after_active" },
917 });
918
919 const before = yield* orchestrator.getThreadProjection(threadId);
920 const activeRun = before.runs.find((run) => run.status === "starting");
921 const queuedRuns = before.runs
922 .filter((run) => run.status === "queued")
923 .toSorted((left, right) => left.ordinal - right.ordinal);
924 const firstQueuedRun = queuedRuns[0];
925 const secondQueuedRun = queuedRuns[1];
926 assert.isDefined(activeRun);
927 assert.isDefined(firstQueuedRun);
928 assert.isDefined(secondQueuedRun);
929 assert.isFalse(
930 before.turnItems.some(
931 (item) =>
932 item.type === "user_message" &&
933 (item.messageId === firstQueuedRun.userMessageId ||
934 item.messageId === secondQueuedRun.userMessageId),
935 ),
936 "queued messages must not exist as turn items before dispatch",
937 );
938
939 const promotedRunIds = yield* Queue.unbounded<RunId>();
940 const afterSequence = yield* orchestrator.getThreadEventSequence(threadId);
941 yield* eventSink.stream({ threadId, afterSequence }).pipe(
942 Stream.runForEach((stored) =>
943 stored.event.type === "run.updated" && stored.event.payload.status === "starting"
944 ? Queue.offer(promotedRunIds, stored.event.payload.id)
945 : Effect.void,
946 ),
947 Effect.forkScoped,
948 );
949 yield* Effect.yieldNow;
950
951 const activeCompletedAt = yield* DateTime.now;
952 yield* eventSink.write({
953 events: [
954 {
955 id: EventId.make("runtime-layer-serialized-queue-active-completed"),
956 type: "run.updated",
957 threadId,
958 runId: activeRun.id,
959 ...(activeRun.rootNodeId === null ? {} : { nodeId: activeRun.rootNodeId }),
960 providerInstanceId: activeRun.providerInstanceId,
961 occurredAt: activeCompletedAt,
962 payload: {
963 ...activeRun,
964 status: "completed",
965 completedAt: activeCompletedAt,
966 },
967 },
968 ],
969 });
970
971 assert.equal(yield* Queue.take(promotedRunIds), firstQueuedRun.id);
972 const afterFirstPromotion = yield* orchestrator.getThreadProjection(threadId);
973 assert.equal(
974 afterFirstPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status,
975 "starting",
976 );
977 assert.equal(
978 afterFirstPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status,
979 "queued",
980 );
981 const promotedMessageItem = afterFirstPromotion.turnItems.find(
982 (item) => item.type === "user_message" && item.messageId === firstQueuedRun.userMessageId,
983 );
984 assert.isDefined(promotedMessageItem);
985 if (promotedMessageItem.type !== "user_message") {
986 assert.fail("promoted queue item must be a user message");
987 }
988 assert.equal(promotedMessageItem.inputIntent, "queued_turn");
989 assert.isTrue(
990 promotedMessageItem.startedAt !== null &&
991 DateTime.toEpochMillis(promotedMessageItem.startedAt) >=
992 DateTime.toEpochMillis(activeCompletedAt),
993 );
994
995 const promotedFirst = afterFirstPromotion.runs.find((run) => run.id === firstQueuedRun.id);
996 assert.isDefined(promotedFirst);
997 const firstCompletedAt = yield* DateTime.now;
998 yield* eventSink.write({
999 events: [
1000 {
1001 id: EventId.make("runtime-layer-serialized-queue-first-completed"),
1002 type: "run.updated",
1003 threadId,
1004 runId: promotedFirst.id,
1005 ...(promotedFirst.rootNodeId === null ? {} : { nodeId: promotedFirst.rootNodeId }),
1006 providerInstanceId: promotedFirst.providerInstanceId,
1007 occurredAt: firstCompletedAt,
1008 payload: {
1009 ...promotedFirst,
1010 status: "completed",
1011 completedAt: firstCompletedAt,
1012 },
1013 },
1014 ],
1015 });
1016
1017 assert.equal(yield* Queue.take(promotedRunIds), secondQueuedRun.id);
1018 const afterSecondPromotion = yield* orchestrator.getThreadProjection(threadId);
1019 assert.equal(
1020 afterSecondPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status,
1021 "completed",
1022 );
1023 assert.equal(
1024 afterSecondPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status,
1025 "starting",
1026 );
1027 }),
1028 );
1029
1030 it.effect("edits and removes queued runs", () =>
1031 Effect.gen(function* () {
1032 const orchestrator = yield* OrchestratorV2;
1033 const threadId = ThreadId.make("runtime-layer-queued-edit-thread");
1034
1035 yield* orchestrator.dispatch({
1036 type: "thread.create",
1037 createdBy: "user",
1038 creationSource: "web",
1039 commandId: CommandId.make("runtime-layer-queued-edit-create"),
1040 threadId,
1041 projectId: ProjectId.make("runtime-layer-queued-edit-project"),
1042 title: "Edit queued work",
1043 modelSelection,
1044 runtimeMode: "full-access",
1045 interactionMode: "default",
1046 branch: null,
1047 worktreePath: "/tmp/runtime-layer-queued-edit",
1048 });
1049 yield* orchestrator.dispatch({
1050 type: "message.dispatch",
1051 createdBy: "user",
1052 creationSource: "web",
1053 commandId: CommandId.make("runtime-layer-queued-edit-active-message"),
1054 threadId,
1055 messageId: MessageId.make("runtime-layer-queued-edit-active-message"),
1056 text: "Keep the provider occupied.",
1057 attachments: [],
1058 modelSelection,
1059 dispatchMode: { type: "start_immediately" },
1060 });
1061 yield* orchestrator.dispatch({
1062 type: "message.dispatch",
1063 createdBy: "user",
1064 creationSource: "web",
1065 commandId: CommandId.make("runtime-layer-queued-edit-queued-message"),
1066 threadId,
1067 messageId: MessageId.make("runtime-layer-queued-edit-queued-message"),
1068 text: "Original queued text.",
1069 attachments: [],
1070 modelSelection,
1071 dispatchMode: { type: "queue_after_active" },
1072 });
1073
1074 const before = yield* orchestrator.getThreadProjection(threadId);
1075 const queuedRun = before.runs.find((run) => run.status === "queued");
1076 assert.isDefined(queuedRun);
1077
1078 yield* orchestrator.dispatch({
1079 type: "queued-run.edit",
1080 commandId: CommandId.make("runtime-layer-queued-edit-edit"),
1081 threadId,
1082 runId: queuedRun.id,
1083 text: "Updated queued text.",
1084 });
1085
1086 const afterEdit = yield* orchestrator.getThreadProjection(threadId);
1087 assert.equal(
1088 afterEdit.messages.find((message) => message.id === queuedRun.userMessageId)?.text,
1089 "Updated queued text.",
1090 );
1091 const editedItem = afterEdit.turnItems.find(
1092 (item) => item.type === "user_message" && item.messageId === queuedRun.userMessageId,
1093 );
1094 assert.isUndefined(editedItem, "editing queue state must not create a timeline turn item");
1095
1096 const emptyEditError = yield* orchestrator
1097 .dispatch({
1098 type: "queued-run.edit",
1099 commandId: CommandId.make("runtime-layer-queued-edit-empty"),
1100 threadId,
1101 runId: queuedRun.id,
1102 text: " ",
1103 })
1104 .pipe(Effect.flip);
1105 assert.equal(emptyEditError._tag, "OrchestratorDispatchError");
1106
1107 yield* orchestrator.dispatch({
1108 type: "queued-run.cancel",
1109 commandId: CommandId.make("runtime-layer-queued-edit-cancel"),
1110 threadId,
1111 runId: queuedRun.id,
1112 });
1113
1114 const afterCancel = yield* orchestrator.getThreadProjection(threadId);
1115 assert.equal(afterCancel.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
1116 assert.equal(
1117 afterCancel.attempts.find((attempt) => attempt.runId === queuedRun.id)?.status,
1118 "cancelled",
1119 );
1120 assert.equal(
1121 afterCancel.nodes.find((node) => node.runId === queuedRun.id)?.status,
1122 "cancelled",
1123 );
1124 assert.isFalse(
1125 afterCancel.visibleTurnItems.some(
1126 (row) => row.item.type === "user_message" && row.item.runId === queuedRun.id,
1127 ),
1128 "removed queued message must not surface as a transcript row",
1129 );
1130 assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
1131
1132 const cancelAgainError = yield* orchestrator
1133 .dispatch({
1134 type: "queued-run.cancel",
1135 commandId: CommandId.make("runtime-layer-queued-edit-cancel-again"),
1136 threadId,
1137 runId: queuedRun.id,
1138 })
1139 .pipe(Effect.flip);
1140 assert.equal(cancelAgainError._tag, "OrchestratorDispatchError");
1141 }),
1142 );
1143});
1144
1145it.layer(SharedApplicationDataPlaneTestLayer)("pending provider interruption", (it) => {
1146 it.effect("interrupts a pending provider start without launching provider work", () =>
1147 Effect.gen(function* () {
1148 const applicationEngine = yield* OrchestrationEngineService;
1149 const orchestrator = yield* OrchestratorV2;
1150 const threadManagement = yield* ThreadManagementService;
1151 const effectWorker = yield* OrchestrationEffectWorkerV2;
1152 const projectId = ProjectId.make("runtime-layer-pending-interrupt-project");
1153 const threadId = ThreadId.make("runtime-layer-pending-interrupt-thread");
1154
1155 yield* applicationEngine.dispatch({
1156 type: "project.create",
1157 commandId: CommandId.make("runtime-layer-pending-interrupt-project-create"),
1158 projectId,
1159 title: "Pending interrupt project",
1160 workspaceRoot: "/tmp/runtime-layer-pending-interrupt-project",
1161 defaultModelSelection: modelSelection,
1162 scripts: [],
1163 createdAt: "2026-06-22T00:00:00.000Z",
1164 });
1165 yield* orchestrator.dispatch({
1166 type: "thread.create",
1167 createdBy: "user",
1168 creationSource: "web",
1169 commandId: CommandId.make("runtime-layer-pending-interrupt-create"),
1170 threadId,
1171 projectId,
1172 title: "Pending interrupt",
1173 modelSelection,
1174 runtimeMode: "full-access",
1175 interactionMode: "default",
1176 branch: null,
1177 worktreePath: null,
1178 });
1179 yield* orchestrator.dispatch({
1180 type: "message.dispatch",
1181 createdBy: "user",
1182 creationSource: "web",
1183 commandId: CommandId.make("runtime-layer-pending-interrupt-message"),
1184 threadId,
1185 messageId: MessageId.make("runtime-layer-pending-interrupt-message"),
1186 text: "Do not reach the provider.",
1187 attachments: [],
1188 modelSelection,
1189 dispatchMode: { type: "start_immediately" },
1190 });
1191
1192 const starting = yield* orchestrator.getThreadProjection(threadId);
1193 const run = starting.runs[0];
1194 assert.isDefined(run);
1195 assert.equal(run.status, "starting");
1196
1197 const interrupt = yield* threadManagement.interruptThread({
1198 projectId,
1199 commandId: CommandId.make("runtime-layer-pending-interrupt-command"),
1200 threadId,
1201 runId: run.id,
1202 reason: "Cancelled before provider start",
1203 });
1204 assert.equal(interrupt.type, "interrupt_requested");
1205
1206 const interrupted = yield* orchestrator.getThreadProjection(threadId);
1207 assert.equal(interrupted.runs[0]?.status, "interrupted");
1208 assert.equal(interrupted.attempts[0]?.status, "interrupted");
1209 assert.equal(
1210 interrupted.nodes.find((node) => node.kind === "root_turn")?.status,
1211 "interrupted",
1212 );
1213 assert.deepEqual(
1214 interrupted.turnItems.filter((item) => item.runId === run.id).map((item) => item.type),
1215 ["user_message", "run_interrupt_request", "run_interrupt_result"],
1216 );
1217 assert.deepEqual(interrupted.providerTurns, []);
1218 assert.isFalse(yield* effectWorker.runOnce);
1219 }),
1220 );
1221});
1222
1223it.layer(SharedApplicationDataPlaneTestLayer)("snooze projection", (it) => {
1224 it.effect("carries snooze state through the V2 shell projection", () =>
1225 Effect.gen(function* () {
1226 const applicationEngine = yield* OrchestrationEngineService;
1227 const orchestrator = yield* OrchestratorV2;
1228 const projectId = ProjectId.make("runtime-layer-snoozed-project");
1229 const threadId = ThreadId.make("runtime-layer-snoozed-thread");
1230 const snoozedUntil = "2099-07-25T09:00:00.000Z";
1231
1232 yield* applicationEngine.dispatch({
1233 type: "project.create",
1234 commandId: CommandId.make("runtime-layer-snoozed-project-create"),
1235 projectId,
1236 title: "Snoozed shell projection",
1237 workspaceRoot: "/tmp/runtime-layer-snoozed-project",
1238 defaultModelSelection: modelSelection,
1239 scripts: [],
1240 createdAt: "2026-07-24T00:00:00.000Z",
1241 });
1242 yield* orchestrator.dispatch({
1243 type: "thread.create",
1244 createdBy: "user",
1245 creationSource: "web",
1246 commandId: CommandId.make("runtime-layer-snoozed-thread-create"),
1247 threadId,
1248 projectId,
1249 title: "Snoozed thread",
1250 modelSelection,
1251 runtimeMode: "full-access",
1252 interactionMode: "default",
1253 branch: null,
1254 worktreePath: null,
1255 });
1256 yield* orchestrator.dispatch({
1257 type: "thread.snooze",
1258 commandId: CommandId.make("runtime-layer-snoozed-thread-snooze"),
1259 threadId,
1260 snoozedUntil,
1261 });
1262
1263 const firstProjection = yield* orchestrator.getThreadProjection(threadId);
1264 const firstSnoozedAt = firstProjection.thread.snoozedAt;
1265 const firstUpdatedAt = firstProjection.thread.updatedAt;
1266 assert.isNotNull(firstSnoozedAt);
1267
1268 yield* orchestrator.dispatch({
1269 type: "thread.snooze",
1270 commandId: CommandId.make("runtime-layer-snoozed-thread-snooze-again"),
1271 threadId,
1272 snoozedUntil,
1273 });
1274
1275 const shell = yield* orchestrator.getShellSnapshot();
1276 const thread = shell.threads.find((candidate) => candidate.id === threadId);
1277 assert.isDefined(thread);
1278 assert.equal(DateTime.formatIso(thread.snoozedUntil!), snoozedUntil);
1279 assert.deepEqual(thread.snoozedAt, firstSnoozedAt);
1280 assert.deepEqual(thread.updatedAt, firstUpdatedAt);
1281
1282 yield* orchestrator.dispatch({
1283 type: "message.dispatch",
1284 createdBy: "user",
1285 creationSource: "web",
1286 commandId: CommandId.make("runtime-layer-snoozed-message"),
1287 threadId,
1288 messageId: MessageId.make("runtime-layer-snoozed-message"),
1289 text: "Wake this thread.",
1290 attachments: [],
1291 modelSelection,
1292 dispatchMode: { type: "start_immediately" },
1293 });
1294
1295 const awakened = yield* orchestrator.getThreadProjection(threadId);
1296 assert.isNull(awakened.thread.snoozedUntil);
1297 assert.isNull(awakened.thread.snoozedAt);
1298 }),
1299 );
1300});
1301
1302it.layer(SharedApplicationDataPlaneTestLayer)("visited projection", (it) => {
1303 it.effect("carries the visited watermark through the V2 shell projection", () =>
1304 Effect.gen(function* () {
1305 const applicationEngine = yield* OrchestrationEngineService;
1306 const orchestrator = yield* OrchestratorV2;
1307 const projectId = ProjectId.make("runtime-layer-visited-project");
1308 const threadId = ThreadId.make("runtime-layer-visited-thread");
1309 const visitedAt = "2026-07-24T01:00:00.000Z";
1310
1311 yield* applicationEngine.dispatch({
1312 type: "project.create",
1313 commandId: CommandId.make("runtime-layer-visited-project-create"),
1314 projectId,
1315 title: "Visited shell projection",
1316 workspaceRoot: "/tmp/runtime-layer-visited-project",
1317 defaultModelSelection: modelSelection,
1318 scripts: [],
1319 createdAt: "2026-07-24T00:00:00.000Z",
1320 });
1321 yield* orchestrator.dispatch({
1322 type: "thread.create",
1323 createdBy: "user",
1324 creationSource: "web",
1325 commandId: CommandId.make("runtime-layer-visited-thread-create"),
1326 threadId,
1327 projectId,
1328 title: "Visited thread",
1329 modelSelection,
1330 runtimeMode: "full-access",
1331 interactionMode: "default",
1332 branch: null,
1333 worktreePath: null,
1334 });
1335 const created = yield* orchestrator.getThreadProjection(threadId);
1336 assert.isNull(created.thread.lastVisitedAt);
1337 const createdUpdatedAt = created.thread.updatedAt;
1338
1339 yield* TestClock.adjust("1 second");
1340 yield* orchestrator.dispatch({
1341 type: "thread.visit",
1342 commandId: CommandId.make("runtime-layer-visited-thread-visit"),
1343 threadId,
1344 visitedAt,
1345 });
1346 const visited = yield* orchestrator.getThreadProjection(threadId);
1347 assert.isNotNull(visited.thread.lastVisitedAt);
1348 assert.equal(DateTime.formatIso(visited.thread.lastVisitedAt!), visitedAt);
1349 // Visiting records read state, not activity: updatedAt must not move.
1350 assert.deepEqual(visited.thread.updatedAt, createdUpdatedAt);
1351
1352 // Monotonic: an older watermark (a replay or a stale device) cannot
1353 // rewind the marker.
1354 yield* orchestrator.dispatch({
1355 type: "thread.visit",
1356 commandId: CommandId.make("runtime-layer-visited-thread-visit-stale"),
1357 threadId,
1358 visitedAt: "2026-07-24T00:30:00.000Z",
1359 });
1360 const afterStaleVisit = yield* orchestrator.getThreadProjection(threadId);
1361 assert.equal(DateTime.formatIso(afterStaleVisit.thread.lastVisitedAt!), visitedAt);
1362
1363 const shell = yield* orchestrator.getShellSnapshot();
1364 const thread = shell.threads.find((candidate) => candidate.id === threadId);
1365 assert.isDefined(thread);
1366 assert.equal(DateTime.formatIso(thread!.lastVisitedAt!), visitedAt);
1367 assert.deepEqual(thread!.updatedAt, createdUpdatedAt);
1368
1369 // No completed run yet → nothing to mark unread against.
1370 const markUnread = yield* orchestrator
1371 .dispatch({
1372 type: "thread.mark-unread",
1373 commandId: CommandId.make("runtime-layer-visited-thread-mark-unread"),
1374 threadId,
1375 })
1376 .pipe(Effect.flip);
1377 assert.instanceOf(markUnread, OrchestratorDispatchError);
1378 }),
1379 );
1380});
1381
1382it.layer(SharedApplicationDataPlaneTestLayer)("shared application data plane", (it) => {
1383 it.effect("orders retained project transactions and V2 thread transactions in one source", () =>
1384 Effect.gen(function* () {
1385 const applicationEngine = yield* OrchestrationEngineService;
1386 const applicationEvents = yield* OrchestrationEventStore;
1387 const orchestrator = yield* OrchestratorV2;
1388 const projectionSnapshot = yield* ProjectionSnapshotQuery;
1389 const sql = yield* SqlClient.SqlClient;
1390 const projectId = ProjectId.make("runtime-layer-shared-project");
1391 const threadId = ThreadId.make("runtime-layer-shared-thread");
1392 const projectCommand = {
1393 type: "project.create" as const,
1394 commandId: CommandId.make("runtime-layer-shared-project-create"),
1395 projectId,
1396 title: "Shared application source",
1397 workspaceRoot: "/tmp/runtime-layer-shared-project",
1398 defaultModelSelection: modelSelection,
1399 scripts: [],
1400 createdAt: "2026-06-20T00:00:00.000Z",
1401 };
1402
1403 const projectResult = yield* applicationEngine.dispatch(projectCommand);
1404 const projectRetry = yield* applicationEngine.dispatch(projectCommand);
1405 assert.equal(projectRetry.sequence, projectResult.sequence);
1406
1407 const delivered = yield* Queue.unbounded<ApplicationStoredEvent>();
1408 yield* applicationEvents.streamApplicationEvents().pipe(
1409 Stream.take(2),
1410 Stream.runForEach((event) => Queue.offer(delivered, event)),
1411 Effect.forkScoped,
1412 );
1413
1414 const projectEvent = yield* Queue.take(delivered);
1415 assert.equal(projectEvent.sequence, projectResult.sequence);
1416
1417 const threadResult = yield* orchestrator.dispatch({
1418 type: "thread.create",
1419 createdBy: "user",
1420 creationSource: "web",
1421 commandId: CommandId.make("runtime-layer-shared-thread-create"),
1422 threadId,
1423 projectId,
1424 title: "Shared thread",
1425 modelSelection,
1426 runtimeMode: "full-access",
1427 interactionMode: "default",
1428 branch: null,
1429 worktreePath: null,
1430 });
1431 const threadEvent = yield* Queue.take(delivered);
1432
1433 assert.equal(threadEvent.sequence, threadResult.sequence);
1434 assert.isAbove(threadEvent.sequence, projectEvent.sequence);
1435 assert.isTrue("aggregateKind" in projectEvent);
1436 assert.isTrue("event" in threadEvent);
1437 assert.equal((yield* projectionSnapshot.getProjectShellById(projectId))._tag, "Some");
1438
1439 const retainedReceipts = yield* sql<{
1440 readonly aggregate_kind: string;
1441 readonly aggregate_id: string;
1442 }>`
1443 SELECT aggregate_kind, aggregate_id
1444 FROM orchestration_command_receipts
1445 ORDER BY result_sequence ASC
1446 `;
1447 assert.deepEqual(retainedReceipts, [
1448 { aggregate_kind: "project", aggregate_id: projectId },
1449 { aggregate_kind: "thread", aggregate_id: threadId },
1450 ]);
1451
1452 const retiredWrites = yield* sql<{ readonly count: number }>`
1453 SELECT
1454 (SELECT COUNT(*) FROM orchestration_v2_events) +
1455 (SELECT COUNT(*) FROM orchestration_v2_command_receipts) AS count
1456 `;
1457 assert.equal(retiredWrites[0]?.count, 0);
1458 }),
1459 );
1460});