Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 type ModelSelection,
5 NodeId,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ExecutionNode,
9 type OrchestrationV2PlanArtifact,
10 type OrchestrationV2RuntimeRequest,
11 type OrchestrationV2ProviderThread,
12 type OrchestrationV2Run,
13 type OrchestrationV2TurnItem,
14 ProviderDriverKind,
15 ProviderInstanceId,
16 PlanId,
17 RunAttemptId,
18 RunId,
19 RuntimeRequestId,
20 TurnItemId,
21} from "@t3tools/contracts";
22import * as DateTime from "effect/DateTime";
23import * as Deferred from "effect/Deferred";
24import * as Fiber from "effect/Fiber";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Stream from "effect/Stream";
28import * as TestClock from "effect/testing/TestClock";
29
30import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
31import * as EventSink from "./EventSink.ts";
32import * as EventStore from "./EventStore.ts";
33import * as IdAllocator from "./IdAllocator.ts";
34import * as ProjectionStore from "./ProjectionStore.ts";
35import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
36import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
37import { makeProviderFailure } from "./ProviderFailure.ts";
38import {
39 makeProviderEventRoutingState,
40 type ProviderEventRouteIdentity,
41 routeProviderEvent,
42 selectInheritedBackgroundTurnItems,
43} from "./RunExecutionService.ts";
44
45const TestDatabaseLayer = SqlitePersistenceMemory;
46const TestStoresLayer = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(
47 Layer.provide(TestDatabaseLayer),
48);
49
50const TestEventSinkLayer = EventSink.layer.pipe(
51 Layer.provide(Layer.mergeAll(TestStoresLayer, TestDatabaseLayer)),
52);
53
54const TestLayer = Layer.mergeAll(
55 TestStoresLayer,
56 TestEventSinkLayer,
57 IdAllocator.layer,
58 ThreadCommandExecutor.layer,
59 ProviderEventIngestor.layer.pipe(
60 Layer.provide(
61 Layer.mergeAll(
62 TestStoresLayer,
63 TestEventSinkLayer,
64 IdAllocator.layer,
65 ThreadCommandExecutor.layer,
66 ),
67 ),
68 ),
69);
70const modelSelection = {
71 instanceId: ProviderInstanceId.make("codex"),
72 model: "gpt-5.4",
73} satisfies ModelSelection;
74const CODEX_DRIVER = ProviderDriverKind.make("codex");
75
76function threadCreatedEvent(
77 now: DateTime.Utc,
78): Effect.Effect<
79 OrchestrationV2DomainEvent,
80 IdAllocator.IdAllocatorV2Error,
81 IdAllocator.IdAllocatorV2
82> {
83 return Effect.gen(function* () {
84 const idAllocator = yield* IdAllocator.IdAllocatorV2;
85 const projectId = yield* idAllocator.allocate.project({
86 fixtureName: "provider-event-ingestor",
87 });
88 const threadId = yield* idAllocator.allocate.thread({
89 fixtureName: "provider-event-ingestor",
90 projectId,
91 });
92 const providerThreadId = idAllocator.derive.providerThread({
93 driver: CODEX_DRIVER,
94 nativeThreadId: "native-thread",
95 });
96 const thread: OrchestrationV2AppThread = {
97 createdBy: "user",
98 creationSource: "web",
99 id: threadId,
100 projectId,
101 title: "Provider event ingestor",
102 providerInstanceId: modelSelection.instanceId,
103 modelSelection: modelSelection,
104 runtimeMode: "full-access",
105 interactionMode: "default",
106 branch: null,
107 worktreePath: null,
108 branchPullRequest: null,
109 activeOrderKey: null,
110 activeProviderThreadId: providerThreadId,
111 lineage: {
112 parentThreadId: null,
113 relationshipToParent: null,
114 rootThreadId: threadId,
115 },
116 forkedFrom: null,
117 createdAt: now,
118 updatedAt: now,
119 archivedAt: null,
120 settledOverride: null,
121 settledAt: null,
122 lastVisitedAt: null,
123 deletedAt: null,
124 };
125
126 return {
127 id: yield* idAllocator.allocate.event({ threadId }),
128 type: "thread.created",
129 threadId,
130 occurredAt: now,
131 payload: thread,
132 };
133 });
134}
135
136const layer = it.layer(TestLayer);
137
138it.effect("records accepted billed turn usage once without billing the context window", () => {
139 const recorded: Array<Readonly<Record<string, unknown>>> = [];
140 const analytics = Layer.succeed(ProviderEventIngestor.ProviderTurnAnalytics, {
141 record: (properties: Readonly<Record<string, unknown>>) =>
142 Effect.sync(() => {
143 recorded.push(properties);
144 }),
145 });
146 return Effect.gen(function* () {
147 const now = yield* DateTime.now;
148 const eventSink = yield* EventSink.EventSinkV2;
149 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
150 const idAllocator = yield* IdAllocator.IdAllocatorV2;
151 const threadEvent = yield* threadCreatedEvent(now);
152 yield* eventSink.write({ events: [threadEvent] });
153 const providerSessionId = yield* idAllocator.allocate.providerSession({
154 providerInstanceId: modelSelection.instanceId,
155 threadId: threadEvent.threadId,
156 });
157 const providerThreadId = idAllocator.derive.providerThread({
158 driver: CODEX_DRIVER,
159 nativeThreadId: "billing-thread",
160 });
161 const providerTurn = {
162 id: idAllocator.derive.providerTurn({ driver: CODEX_DRIVER, nativeTurnId: "billing-turn" }),
163 providerThreadId,
164 nodeId: NodeId.make("node:billing-turn"),
165 runAttemptId: null,
166 nativeTurnRef: null,
167 ordinal: 1,
168 status: "completed" as const,
169 startedAt: now,
170 completedAt: DateTime.makeUnsafe(DateTime.toEpochMillis(now) + 120),
171 tokenUsage: {
172 inputTokens: 4000,
173 cachedInputTokens: 3000,
174 outputTokens: 100,
175 usedTokens: 4100,
176 updatedAt: DateTime.formatIso(now),
177 },
178 turnTokenUsage: {
179 usageStatus: "complete" as const,
180 usageScope: "main_agent" as const,
181 hasSubagents: false,
182 inputTokens: 40,
183 cachedInputTokens: 30,
184 outputTokens: 10,
185 },
186 };
187 const input = {
188 providerSessionId,
189 providerInstanceId: modelSelection.instanceId,
190 threadId: threadEvent.threadId,
191 analyticsContext: {
192 modelSelection,
193 runtimeMode: "full-access" as const,
194 interactionMode: "default" as const,
195 },
196 event: { type: "provider_turn.updated" as const, driver: CODEX_DRIVER, providerTurn },
197 };
198 yield* ingestor.ingestNormalized(input);
199 yield* ingestor.ingestNormalized(input);
200 const ignored = yield* ingestor.ingestNormalized({
201 ...input,
202 event: {
203 ...input.event,
204 providerTurn: {
205 ...providerTurn,
206 id: idAllocator.derive.providerTurn({
207 driver: CODEX_DRIVER,
208 nativeTurnId: "stale-billing-turn",
209 }),
210 },
211 },
212 writeIfRunCurrent: {
213 runId: RunId.make("missing-run"),
214 activeAttemptId: RunAttemptId.make("stale-attempt"),
215 expectedStatus: "running",
216 },
217 });
218 assert.isEmpty(ignored);
219 assert.lengthOf(recorded, 1);
220 assert.deepEqual(recorded[0], {
221 provider: CODEX_DRIVER,
222 terminalStatus: "completed",
223 usageStatus: "complete",
224 usageScope: "main_agent",
225 hasSubagents: false,
226 inputTokens: 40,
227 cachedInputTokens: 30,
228 outputTokens: 10,
229 model: modelSelection.model,
230 mixedModels: false,
231 runtimeMode: "full-access",
232 interactionMode: "default",
233 durationMs: 120,
234 });
235 }).pipe(Effect.provide(TestLayer.pipe(Layer.provide(analytics))));
236});
237
238layer("ProviderEventIngestorV2", (it) => {
239 it.effect("normalizes provider events through the real event log and projection store", () =>
240 Effect.gen(function* () {
241 const now = yield* DateTime.now;
242 const eventSink = yield* EventSink.EventSinkV2;
243 const eventStore = yield* EventStore.EventStoreV2;
244 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
245 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
246 const idAllocator = yield* IdAllocator.IdAllocatorV2;
247 const threadEvent = yield* threadCreatedEvent(now);
248 const providerSessionId = yield* idAllocator.allocate.providerSession({
249 providerInstanceId: modelSelection.instanceId,
250 threadId: threadEvent.threadId,
251 });
252 const providerThread: OrchestrationV2ProviderThread = {
253 id: idAllocator.derive.providerThread({
254 driver: CODEX_DRIVER,
255 nativeThreadId: "native-thread",
256 }),
257 driver: CODEX_DRIVER,
258 providerInstanceId: modelSelection.instanceId,
259 providerSessionId,
260 appThreadId: threadEvent.threadId,
261 ownerNodeId: null,
262 nativeThreadRef: {
263 driver: CODEX_DRIVER,
264 nativeId: "native-thread",
265 strength: "strong",
266 },
267 nativeConversationHeadRef: null,
268 status: "idle",
269 firstRunOrdinal: null,
270 lastRunOrdinal: null,
271 handoffIds: [],
272 forkedFrom: null,
273 createdAt: now,
274 updatedAt: now,
275 };
276
277 yield* eventSink.write({ events: [threadEvent] });
278 const storedEvents = yield* ingestor.ingestNormalized({
279 providerSessionId,
280 providerInstanceId: modelSelection.instanceId,
281 threadId: threadEvent.threadId,
282 event: {
283 type: "provider_thread.updated",
284 driver: CODEX_DRIVER,
285 providerThread,
286 },
287 });
288
289 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
290 const storedDomainEvents = yield* eventStore.read({}).pipe(Stream.runCollect);
291 const afterFirstEvent = yield* eventStore
292 .read({ afterSequence: 1, threadId: threadEvent.threadId })
293 .pipe(Stream.runCollect);
294 const latestThreadSequence = yield* eventStore.latestSequence({
295 threadId: threadEvent.threadId,
296 });
297
298 assert.equal(storedEvents.length, 1);
299 assert.equal(storedEvents[0]?.event.type, "provider-thread.updated");
300 assert.deepEqual(
301 projection.providerThreads.map((thread) => thread.id),
302 [providerThread.id],
303 );
304 assert.deepEqual(
305 Array.from(storedDomainEvents).map((stored) => stored.event.type),
306 ["thread.created", "provider-thread.updated"],
307 );
308 assert.deepEqual(
309 Array.from(storedDomainEvents).map((stored) => stored.sequence),
310 [1, 2],
311 );
312 assert.deepEqual(
313 Array.from(afterFirstEvent).map((stored) => stored.event.type),
314 ["provider-thread.updated"],
315 );
316 assert.equal(latestThreadSequence, 2);
317 }),
318 );
319
320 it.effect("carries plan-step durations through consecutive and restarted ingestion", () =>
321 Effect.gen(function* () {
322 yield* TestClock.setTime(Date.parse("2026-09-07T00:00:00.000Z"));
323 const now = yield* DateTime.now;
324 const eventSink = yield* EventSink.EventSinkV2;
325 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
326 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
327 const idAllocator = yield* IdAllocator.IdAllocatorV2;
328 const threadEvent = yield* threadCreatedEvent(now);
329 const providerSessionId = yield* idAllocator.allocate.providerSession({
330 providerInstanceId: modelSelection.instanceId,
331 threadId: threadEvent.threadId,
332 });
333 const planId = PlanId.make("plan:provider-event-duration");
334 const nodeId = NodeId.make("node:provider-event-duration");
335 type TodoListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;
336 const plan = (steps: TodoListPlan["steps"]): TodoListPlan => ({
337 id: planId,
338 threadId: threadEvent.threadId,
339 runId: null,
340 nodeId,
341 kind: "todo_list",
342 status: "active",
343 steps,
344 });
345 const ingest = (
346 service: ProviderEventIngestor.ProviderEventIngestorV2["Service"],
347 steps: TodoListPlan["steps"],
348 ) =>
349 service.ingestNormalized({
350 providerSessionId,
351 providerInstanceId: modelSelection.instanceId,
352 threadId: threadEvent.threadId,
353 event: { type: "plan.updated", driver: CODEX_DRIVER, plan: plan(steps) },
354 });
355
356 yield* eventSink.write({ events: [threadEvent] });
357 yield* ingest(ingestor, [
358 { id: "duplicate-a", text: "Verify", status: "running" },
359 { id: "duplicate-b", text: "Verify", status: "pending" },
360 { id: "fallback", text: "Report", status: "pending" },
361 ]);
362 yield* TestClock.adjust("3 seconds");
363 yield* ingest(ingestor, [
364 { id: "duplicate-a", text: "Verify", status: "completed" },
365 { id: "duplicate-b", text: "Verify", status: "pending" },
366 { id: "fallback", text: "Report", status: "pending" },
367 ]);
368
369 const restartedIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
370 Effect.provide(
371 Layer.fresh(ProviderEventIngestor.layer).pipe(
372 Layer.provide(
373 Layer.succeed(ProjectionStore.ProjectionStoreV2, {
374 ...projectionStore,
375 getThreadProjection: () => Effect.die("Plan timing must not load thread history"),
376 }),
377 ),
378 ),
379 ),
380 );
381 yield* TestClock.adjust("4 seconds");
382 yield* ingest(restartedIngestor, [
383 { id: "duplicate-a", text: "Verify", status: "completed" },
384 { id: "duplicate-b", text: "Verify", status: "completed" },
385 { id: "fallback", text: "Report", status: "pending" },
386 ]);
387 yield* TestClock.adjust("5 seconds");
388 yield* ingest(restartedIngestor, [
389 { id: "duplicate-a", text: "Verify", status: "completed" },
390 { id: "duplicate-b", text: "Verify", status: "completed" },
391 { id: "fallback", text: "Report", status: "completed" },
392 ]);
393
394 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
395 const persisted = projection.plans.find(
396 (candidate): candidate is TodoListPlan =>
397 candidate.kind === "todo_list" && candidate.id === planId,
398 );
399 assert.deepEqual(
400 persisted?.steps.map(({ id, text, status, durationMs }) => ({
401 id,
402 text,
403 status,
404 durationMs,
405 })),
406 [
407 { id: "duplicate-a", text: "Verify", status: "completed", durationMs: 3_000 },
408 { id: "duplicate-b", text: "Verify", status: "completed", durationMs: 4_000 },
409 { id: "fallback", text: "Report", status: "completed", durationMs: 5_000 },
410 ],
411 );
412
413 yield* ingest(restartedIngestor, [
414 { id: "duplicate-a", text: "Inserted task", status: "running" },
415 { id: "duplicate-b", text: "Verify", status: "completed" },
416 { id: "fallback", text: "Different completed task", status: "completed" },
417 ]);
418 yield* TestClock.adjust("2 seconds");
419 yield* ingest(restartedIngestor, [
420 { id: "duplicate-a", text: "Inserted task", status: "completed" },
421 { id: "duplicate-b", text: "Verify", status: "completed" },
422 { id: "fallback", text: "Different completed task", status: "completed" },
423 ]);
424 const updated = yield* projectionStore.getThreadProjection(threadEvent.threadId);
425 const changedPlan = updated.plans.find(
426 (candidate): candidate is TodoListPlan =>
427 candidate.kind === "todo_list" && candidate.id === planId,
428 );
429 assert.deepEqual(
430 changedPlan?.steps.map((step) => step.durationMs),
431 [2_000, 4_000, undefined],
432 );
433 }),
434 );
435
436 it.effect(
437 "treats successful provider terminal markers as non-persisted orchestration control signals",
438 () =>
439 Effect.gen(function* () {
440 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
441 const idAllocator = yield* IdAllocator.IdAllocatorV2;
442 const projectId = yield* idAllocator.allocate.project({
443 fixtureName: "provider-event-terminal",
444 });
445 const threadId = yield* idAllocator.allocate.thread({
446 fixtureName: "provider-event-terminal",
447 projectId,
448 });
449 const providerSessionId = yield* idAllocator.allocate.providerSession({
450 providerInstanceId: modelSelection.instanceId,
451 threadId,
452 });
453 const normalized = yield* ingestor.normalize({
454 providerSessionId,
455 providerInstanceId: modelSelection.instanceId,
456 threadId,
457 event: {
458 type: "turn.terminal",
459 driver: CODEX_DRIVER,
460 providerThreadId: idAllocator.derive.providerThread({
461 driver: CODEX_DRIVER,
462 nativeThreadId: "native-thread",
463 }),
464 providerTurnId: idAllocator.derive.providerTurn({
465 driver: CODEX_DRIVER,
466 nativeTurnId: "native-turn",
467 }),
468 runOrdinal: 1,
469 status: "completed",
470 failure: null,
471 threadDisposition: "reusable",
472 },
473 });
474
475 assert.deepEqual(normalized, []);
476 }),
477 );
478
479 it.effect("persists an interrupted run's inherited terminal through the live run router", () =>
480 Effect.gen(function* () {
481 const now = yield* DateTime.now;
482 const eventSink = yield* EventSink.EventSinkV2;
483 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
484 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
485 const idAllocator = yield* IdAllocator.IdAllocatorV2;
486 const threadEvent = yield* threadCreatedEvent(now);
487 const priorRunId = RunId.make("run:provider-event-inherited:prior");
488 const currentRunId = RunId.make("run:provider-event-inherited:current");
489 const itemId = TurnItemId.make("turn-item:provider-event-inherited");
490 const providerSessionId = yield* idAllocator.allocate.providerSession({
491 providerInstanceId: modelSelection.instanceId,
492 threadId: threadEvent.threadId,
493 });
494 const providerThreadId = idAllocator.derive.providerThread({
495 driver: CODEX_DRIVER,
496 nativeThreadId: "native-thread-inherited",
497 });
498 const providerTurnId = idAllocator.derive.providerTurn({
499 driver: CODEX_DRIVER,
500 nativeTurnId: "native-turn-inherited",
501 });
502 const runningItem = {
503 id: itemId,
504 threadId: threadEvent.threadId,
505 runId: priorRunId,
506 nodeId: NodeId.make("node:provider-event-inherited"),
507 providerThreadId,
508 providerTurnId,
509 nativeItemRef: null,
510 parentItemId: null,
511 ordinal: 101,
512 status: "running",
513 title: "Inherited background command",
514 startedAt: now,
515 completedAt: null,
516 updatedAt: now,
517 type: "command_execution",
518 input: "sleep 60",
519 } satisfies OrchestrationV2TurnItem;
520 const terminalItem = {
521 ...runningItem,
522 status: "completed" as const,
523 completedAt: now,
524 updatedAt: now,
525 };
526
527 yield* eventSink.write({ events: [threadEvent] });
528 yield* ingestor.ingestNormalized({
529 providerSessionId,
530 providerInstanceId: modelSelection.instanceId,
531 threadId: threadEvent.threadId,
532 runId: priorRunId,
533 event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
534 });
535
536 const identity: ProviderEventRouteIdentity = {
537 threadId: threadEvent.threadId,
538 runId: currentRunId,
539 attemptId: RunAttemptId.make("attempt:provider-event-inherited:current"),
540 providerThreadId,
541 };
542 const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
543 threadId: threadEvent.threadId,
544 currentProviderThreadId: providerThreadId,
545 currentRunOrdinal: 2,
546 runs: [
547 {
548 id: priorRunId,
549 threadId: threadEvent.threadId,
550 ordinal: 1,
551 status: "interrupted",
552 } as OrchestrationV2Run,
553 {
554 id: currentRunId,
555 threadId: threadEvent.threadId,
556 ordinal: 2,
557 status: "running",
558 } as OrchestrationV2Run,
559 ],
560 turnItems: [runningItem],
561 });
562 const routeState = makeProviderEventRoutingState({
563 identity,
564 inheritedBackgroundTurnItems,
565 providerTurnId: null,
566 });
567 const terminalEvent = {
568 type: "turn_item.updated",
569 driver: CODEX_DRIVER,
570 turnItem: terminalItem,
571 } as const;
572 const [accepted] = routeProviderEvent(terminalEvent, identity, routeState);
573 assert.isTrue(accepted);
574
575 const stored = yield* ingestor.ingestNormalized({
576 providerSessionId,
577 providerInstanceId: modelSelection.instanceId,
578 threadId: threadEvent.threadId,
579 runId: currentRunId,
580 event: terminalEvent,
581 });
582 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
583 const persisted = projection.turnItems.find((item) => item.id === itemId);
584
585 assert.equal(stored.length, 1);
586 assert.equal(stored[0]?.event.type, "turn-item.updated");
587 assert.equal(persisted?.runId, priorRunId);
588 assert.equal(persisted?.threadId, threadEvent.threadId);
589 assert.equal(persisted?.status, "completed");
590 }),
591 );
592
593 it.effect("persists a completed run's late background terminal exactly once", () =>
594 Effect.gen(function* () {
595 const now = yield* DateTime.now;
596 const eventSink = yield* EventSink.EventSinkV2;
597 const eventStore = yield* EventStore.EventStoreV2;
598 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
599 const idAllocator = yield* IdAllocator.IdAllocatorV2;
600 const threadEvent = yield* threadCreatedEvent(now);
601 const priorRunId = RunId.make("run:provider-event-completed:prior");
602 const currentRunId = RunId.make("run:provider-event-completed:current");
603 const itemId = TurnItemId.make("turn-item:provider-event-completed");
604 const providerSessionId = yield* idAllocator.allocate.providerSession({
605 providerInstanceId: modelSelection.instanceId,
606 threadId: threadEvent.threadId,
607 });
608 const providerThreadId = idAllocator.derive.providerThread({
609 driver: CODEX_DRIVER,
610 nativeThreadId: "native-thread-completed",
611 });
612 const providerTurnId = idAllocator.derive.providerTurn({
613 driver: CODEX_DRIVER,
614 nativeTurnId: "native-turn-completed",
615 });
616 const runningItem = {
617 id: itemId,
618 threadId: threadEvent.threadId,
619 runId: priorRunId,
620 nodeId: NodeId.make("node:provider-event-completed"),
621 providerThreadId,
622 providerTurnId,
623 nativeItemRef: null,
624 parentItemId: null,
625 ordinal: 101,
626 status: "running",
627 title: "Completed run background command",
628 startedAt: now,
629 completedAt: null,
630 updatedAt: now,
631 type: "command_execution",
632 input: "sleep 60",
633 } satisfies OrchestrationV2TurnItem;
634 const terminalEvent = {
635 type: "turn_item.updated",
636 driver: CODEX_DRIVER,
637 turnItem: {
638 ...runningItem,
639 status: "completed" as const,
640 completedAt: now,
641 updatedAt: now,
642 },
643 } as const;
644
645 yield* eventSink.write({ events: [threadEvent] });
646 yield* ingestor.ingestNormalized({
647 providerSessionId,
648 providerInstanceId: modelSelection.instanceId,
649 threadId: threadEvent.threadId,
650 runId: priorRunId,
651 event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
652 });
653
654 const priorIdentity: ProviderEventRouteIdentity = {
655 threadId: threadEvent.threadId,
656 runId: priorRunId,
657 attemptId: RunAttemptId.make("attempt:provider-event-completed:prior"),
658 providerThreadId,
659 };
660 const currentIdentity: ProviderEventRouteIdentity = {
661 threadId: threadEvent.threadId,
662 runId: currentRunId,
663 attemptId: RunAttemptId.make("attempt:provider-event-completed:current"),
664 providerThreadId,
665 };
666 const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
667 threadId: threadEvent.threadId,
668 currentProviderThreadId: providerThreadId,
669 currentRunOrdinal: 2,
670 runs: [
671 {
672 id: priorRunId,
673 threadId: threadEvent.threadId,
674 ordinal: 1,
675 status: "completed",
676 } as OrchestrationV2Run,
677 {
678 id: currentRunId,
679 threadId: threadEvent.threadId,
680 ordinal: 2,
681 status: "running",
682 } as OrchestrationV2Run,
683 ],
684 turnItems: [runningItem],
685 });
686 const routers = [
687 {
688 identity: priorIdentity,
689 state: makeProviderEventRoutingState({
690 identity: priorIdentity,
691 providerTurnId: providerTurnId,
692 }),
693 },
694 {
695 identity: currentIdentity,
696 state: makeProviderEventRoutingState({
697 identity: currentIdentity,
698 inheritedBackgroundTurnItems,
699 providerTurnId: null,
700 }),
701 },
702 ];
703 const acceptedRouters = routers.filter(
704 ({ identity, state }) => routeProviderEvent(terminalEvent, identity, state)[0],
705 );
706
707 yield* Effect.forEach(
708 acceptedRouters,
709 ({ identity }) =>
710 ingestor.ingestNormalized({
711 providerSessionId,
712 providerInstanceId: modelSelection.instanceId,
713 threadId: threadEvent.threadId,
714 runId: identity.runId,
715 event: terminalEvent,
716 }),
717 { concurrency: 1 },
718 );
719
720 const storedEvents = yield* eventStore
721 .read({ threadId: threadEvent.threadId })
722 .pipe(Stream.runCollect);
723 const storedTerminals = Array.from(storedEvents).filter(
724 (stored) =>
725 stored.event.type === "turn-item.updated" &&
726 stored.event.payload.id === itemId &&
727 stored.event.payload.status === "completed",
728 );
729
730 assert.equal(storedTerminals.length, 1);
731 assert.equal(acceptedRouters.length, 1);
732 assert.equal(acceptedRouters[0]?.identity.runId, priorRunId);
733 }),
734 );
735
736 it.effect.each(["completed", "interrupted", "failed", "cancelled", "control"] as const)(
737 "dismisses only native questions when a provider turn ends with %s",
738 (terminal) =>
739 Effect.gen(function* () {
740 const now = yield* DateTime.now;
741 const eventSink = yield* EventSink.EventSinkV2;
742 const eventStore = yield* EventStore.EventStoreV2;
743 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
744 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
745 const idAllocator = yield* IdAllocator.IdAllocatorV2;
746 const threadEvent = yield* threadCreatedEvent(now);
747 const threadId = threadEvent.threadId;
748 const providerSessionId = yield* idAllocator.allocate.providerSession({
749 providerInstanceId: modelSelection.instanceId,
750 threadId,
751 });
752 const providerThreadId = idAllocator.derive.providerThread({
753 driver: CODEX_DRIVER,
754 nativeThreadId: `${threadId}:questions`,
755 });
756 const providerTurnId = idAllocator.derive.providerTurn({
757 driver: CODEX_DRIVER,
758 nativeTurnId: `${threadId}:questions`,
759 });
760 const otherTurnId = idAllocator.derive.providerTurn({
761 driver: CODEX_DRIVER,
762 nativeTurnId: `${threadId}:other-turn`,
763 });
764 const specs = [
765 { key: "native", responseCapability: { type: "live", providerSessionId } },
766 {
767 key: "unavailable",
768 responseCapability: { type: "not_resumable", reason: "Turn ended" },
769 },
770 { key: "message", responseCapability: { type: "message" } },
771 { key: "answered", responseCapability: { type: "live", providerSessionId } },
772 { key: "other-turn", responseCapability: { type: "live", providerSessionId } },
773 { key: "approval", responseCapability: { type: "live", providerSessionId } },
774 ] as const;
775 const fixtures = specs.map((spec, ordinal) => {
776 const nodeId = NodeId.make(`${threadId}:${spec.key}`);
777 const resolved = spec.key === "answered";
778 const request: OrchestrationV2RuntimeRequest = {
779 id: RuntimeRequestId.make(`${threadId}:${spec.key}`),
780 nodeId,
781 providerTurnId: spec.key === "other-turn" ? otherTurnId : providerTurnId,
782 nativeRequestRef: null,
783 kind: spec.key === "approval" ? "command" : "user_input",
784 status: resolved ? "resolved" : "pending",
785 responseCapability: spec.responseCapability,
786 createdAt: now,
787 resolvedAt: resolved ? now : null,
788 };
789 const node: OrchestrationV2ExecutionNode = {
790 id: nodeId,
791 threadId,
792 runId: null,
793 parentNodeId: null,
794 rootNodeId: nodeId,
795 kind: spec.key === "approval" ? "approval_request" : "user_input_request",
796 status: resolved ? "completed" : "waiting",
797 countsForRun: false,
798 providerThreadId,
799 providerTurnId: request.providerTurnId,
800 nativeItemRef: null,
801 runtimeRequestId: request.id,
802 checkpointScopeId: null,
803 startedAt: now,
804 completedAt: resolved ? now : null,
805 };
806 const item: OrchestrationV2TurnItem = {
807 id: TurnItemId.make(`${threadId}:${spec.key}`),
808 threadId,
809 runId: null,
810 nodeId,
811 providerThreadId,
812 providerTurnId: request.providerTurnId,
813 nativeItemRef: null,
814 parentItemId: null,
815 ordinal,
816 status: resolved ? "completed" : "waiting",
817 title: "Which option?",
818 startedAt: now,
819 completedAt: resolved ? now : null,
820 updatedAt: now,
821 ...(spec.key === "approval"
822 ? { type: "approval_request", requestId: request.id, requestKind: "command" }
823 : {
824 type: "user_input_request",
825 requestId: request.id,
826 questions: [],
827 ...(spec.key === "message" ? { responseMode: "message" as const } : {}),
828 }),
829 };
830 return { key: spec.key, request, node, item };
831 });
832 const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
833 for (const fixture of fixtures) {
834 for (const payload of [
835 { type: "runtime-request.updated" as const, payload: fixture.request },
836 { type: "node.updated" as const, payload: fixture.node },
837 { type: "turn-item.updated" as const, payload: fixture.item },
838 ]) {
839 seedEvents.push({
840 id: yield* idAllocator.allocate.event({ threadId }),
841 threadId,
842 occurredAt: now,
843 ...payload,
844 });
845 }
846 }
847 yield* eventSink.write({ events: seedEvents });
848 const input = {
849 providerSessionId,
850 providerInstanceId: modelSelection.instanceId,
851 threadId,
852 event:
853 terminal === "control"
854 ? {
855 type: "turn.terminal" as const,
856 driver: CODEX_DRIVER,
857 providerThreadId,
858 providerTurnId,
859 runOrdinal: 1,
860 status: "completed" as const,
861 failure: null,
862 threadDisposition: "reusable" as const,
863 }
864 : {
865 type: "provider_turn.updated" as const,
866 driver: CODEX_DRIVER,
867 providerTurn: {
868 id: providerTurnId,
869 providerThreadId,
870 nodeId: NodeId.make(`${threadId}:root`),
871 runAttemptId: null,
872 nativeTurnRef: null,
873 ordinal: 1,
874 status: terminal,
875 startedAt: now,
876 completedAt: now,
877 },
878 },
879 };
880 const stored = yield* ingestor.ingestNormalized(input);
881 const projection = yield* projectionStore.getThreadProjection(threadId);
882 for (const fixture of fixtures) {
883 const closed = fixture.key === "native" || fixture.key === "unavailable";
884 const request = projection.runtimeRequests.find(
885 (item) => item.id === fixture.request.id,
886 )!;
887 const node = projection.nodes.find((item) => item.id === fixture.node.id)!;
888 const item = projection.turnItems.find((item) => item.id === fixture.item.id)!;
889 if (closed) {
890 assert.equal(request.status, "cancelled");
891 assert.isNotNull(request.resolvedAt);
892 assert.equal(node.status, "cancelled");
893 assert.isNotNull(node.completedAt);
894 assert.equal(item.status, "cancelled");
895 assert.isNotNull(item.completedAt);
896 } else {
897 assert.equal(request.status, fixture.request.status);
898 assert.equal(node.status, fixture.node.status);
899 assert.equal(item.status, fixture.item.status);
900 }
901 }
902 assert.equal(
903 stored.filter((entry) => entry.event.type === "runtime-request.updated").length,
904 2,
905 );
906 assert.isEmpty(
907 (yield* projectionStore.getPendingNativeUserInputs(threadId, providerTurnId))
908 .runtimeRequests,
909 );
910 const replayed = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
911 assert.equal(
912 replayed.filter(
913 (entry) =>
914 entry.event.type === "runtime-request.updated" &&
915 entry.event.payload.status === "cancelled",
916 ).length,
917 2,
918 );
919 const repeated = yield* ingestor.ingestNormalized(input);
920 assert.isFalse(repeated.some((entry) => entry.event.type === "runtime-request.updated"));
921 }),
922 );
923
924 it.effect(
925 "preserves an answer committed after terminal normalization reads a pending question",
926 () =>
927 Effect.scoped(
928 Effect.gen(function* () {
929 const eventSink = yield* EventSink.EventSinkV2;
930 const eventStore = yield* EventStore.EventStoreV2;
931 const projections = yield* ProjectionStore.ProjectionStoreV2;
932 const idAllocator = yield* IdAllocator.IdAllocatorV2;
933 const now = yield* DateTime.now;
934 const threadEvent = yield* threadCreatedEvent(now);
935 const threadId = threadEvent.threadId;
936 const providerSessionId = yield* idAllocator.allocate.providerSession({
937 providerInstanceId: modelSelection.instanceId,
938 threadId,
939 });
940 const providerThreadId = idAllocator.derive.providerThread({
941 driver: CODEX_DRIVER,
942 nativeThreadId: `${threadId}:race`,
943 });
944 const providerTurnId = idAllocator.derive.providerTurn({
945 driver: CODEX_DRIVER,
946 nativeTurnId: `${threadId}:race`,
947 });
948 const nodeId = NodeId.make(`${threadId}:question`);
949 const request: OrchestrationV2RuntimeRequest = {
950 id: RuntimeRequestId.make(`${threadId}:question`),
951 nodeId,
952 providerTurnId,
953 nativeRequestRef: null,
954 kind: "user_input",
955 status: "pending",
956 responseCapability: { type: "live", providerSessionId },
957 createdAt: now,
958 resolvedAt: null,
959 };
960 const node: OrchestrationV2ExecutionNode = {
961 id: nodeId,
962 threadId,
963 runId: null,
964 parentNodeId: null,
965 rootNodeId: nodeId,
966 kind: "user_input_request",
967 status: "waiting",
968 countsForRun: false,
969 providerThreadId,
970 providerTurnId,
971 nativeItemRef: null,
972 runtimeRequestId: request.id,
973 checkpointScopeId: null,
974 startedAt: now,
975 completedAt: null,
976 };
977 const item: OrchestrationV2TurnItem = {
978 id: TurnItemId.make(`${threadId}:question`),
979 threadId,
980 runId: null,
981 nodeId,
982 providerThreadId,
983 providerTurnId,
984 nativeItemRef: null,
985 parentItemId: null,
986 ordinal: 1,
987 status: "waiting",
988 title: "Which option?",
989 startedAt: now,
990 completedAt: null,
991 updatedAt: now,
992 type: "user_input_request",
993 requestId: request.id,
994 questions: [],
995 };
996 const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
997 for (const payload of [
998 { type: "runtime-request.updated" as const, payload: request },
999 { type: "node.updated" as const, payload: node },
1000 { type: "turn-item.updated" as const, payload: item },
1001 ])
1002 seedEvents.push({
1003 id: yield* idAllocator.allocate.event({ threadId }),
1004 threadId,
1005 occurredAt: now,
1006 ...payload,
1007 });
1008 yield* eventSink.write({ events: seedEvents });
1009 const normalized = yield* Deferred.make<void>();
1010 const releaseTerminalWrite = yield* Deferred.make<void>();
1011 const gatedSink = EventSink.EventSinkV2.of({
1012 ...eventSink,
1013 write: (input) =>
1014 Deferred.succeed(normalized, undefined).pipe(
1015 Effect.andThen(Deferred.await(releaseTerminalWrite)),
1016 Effect.andThen(eventSink.write(input)),
1017 ),
1018 });
1019 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
1020 Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),
1021 Effect.provideService(EventSink.EventSinkV2, gatedSink),
1022 );
1023 const terminal = yield* ingestor
1024 .ingestNormalized({
1025 providerSessionId,
1026 providerInstanceId: modelSelection.instanceId,
1027 threadId,
1028 event: {
1029 type: "provider_turn.updated",
1030 driver: CODEX_DRIVER,
1031 providerTurn: {
1032 id: providerTurnId,
1033 providerThreadId,
1034 nodeId,
1035 runAttemptId: null,
1036 nativeTurnRef: null,
1037 ordinal: 1,
1038 status: "completed",
1039 startedAt: now,
1040 completedAt: now,
1041 },
1042 },
1043 })
1044 .pipe(Effect.forkScoped);
1045 yield* Deferred.await(normalized);
1046 const answers = { decision: "Use the existing workspace" };
1047 const responseEvents: Array<OrchestrationV2DomainEvent> = [];
1048 for (const payload of [
1049 {
1050 type: "runtime-request.updated" as const,
1051 payload: { ...request, status: "resolved" as const, answers, resolvedAt: now },
1052 },
1053 {
1054 type: "node.updated" as const,
1055 payload: { ...node, status: "completed" as const, completedAt: now },
1056 },
1057 {
1058 type: "turn-item.updated" as const,
1059 payload: { ...item, status: "completed" as const, completedAt: now },
1060 },
1061 ])
1062 responseEvents.push({
1063 id: yield* idAllocator.allocate.event({ threadId }),
1064 threadId,
1065 occurredAt: now,
1066 ...payload,
1067 });
1068 yield* eventSink.write({ events: responseEvents });
1069 yield* Deferred.succeed(releaseTerminalWrite, undefined);
1070 const committedTerminal = yield* Fiber.join(terminal);
1071 assert.deepEqual(
1072 committedTerminal.map((stored) => stored.event.type),
1073 ["provider-turn.updated"],
1074 );
1075 const projection = yield* projections.getThreadProjection(threadId);
1076 const answered = projection.runtimeRequests.find((entry) => entry.id === request.id)!;
1077 assert.equal(answered.status, "resolved");
1078 assert.deepEqual(answered.answers, answers);
1079 assert.equal(projection.nodes.find((entry) => entry.id === nodeId)!.status, "completed");
1080 assert.equal(
1081 projection.turnItems.find((entry) => entry.id === item.id)!.status,
1082 "completed",
1083 );
1084 const history = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
1085 assert.isFalse(
1086 history.some(
1087 (stored) =>
1088 stored.event.type === "runtime-request.updated" &&
1089 stored.event.payload.status === "cancelled",
1090 ),
1091 );
1092 }),
1093 ),
1094 );
1095
1096 it.effect("persists a failed provider terminal as one expected error item", () =>
1097 Effect.gen(function* () {
1098 const now = yield* DateTime.now;
1099 const retryStartedAt = DateTime.makeUnsafe(DateTime.toEpochMillis(now) - 5_000);
1100 const eventSink = yield* EventSink.EventSinkV2;
1101 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1102 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1103 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1104 const threadEvent = yield* threadCreatedEvent(now);
1105 const providerSessionId = yield* idAllocator.allocate.providerSession({
1106 providerInstanceId: modelSelection.instanceId,
1107 threadId: threadEvent.threadId,
1108 });
1109 const providerThreadId = idAllocator.derive.providerThread({
1110 driver: CODEX_DRIVER,
1111 nativeThreadId: "native-thread-failed",
1112 });
1113 const providerTurnId = idAllocator.derive.providerTurn({
1114 driver: CODEX_DRIVER,
1115 nativeTurnId: "native-turn-failed",
1116 });
1117
1118 yield* eventSink.write({ events: [threadEvent] });
1119 const stored = yield* ingestor.ingestNormalized({
1120 providerSessionId,
1121 providerInstanceId: modelSelection.instanceId,
1122 threadId: threadEvent.threadId,
1123 event: {
1124 type: "turn.terminal",
1125 driver: CODEX_DRIVER,
1126 providerThreadId,
1127 providerTurnId,
1128 runOrdinal: 1,
1129 failureItemOrdinal: 102,
1130 status: "failed",
1131 failure: makeProviderFailure({
1132 message: "Invalid reasoning effort.",
1133 code: "invalid_request",
1134 class: "validation_error",
1135 }),
1136 retry: {
1137 attempt: 3,
1138 maxAttempts: 3,
1139 retryDelayMs: 2_000,
1140 },
1141 retryStartedAt,
1142 threadDisposition: "reusable",
1143 },
1144 });
1145
1146 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
1147 const errorItems = projection.visibleTurnItems.filter(
1148 (candidate) => candidate.item.type === "error",
1149 );
1150
1151 assert.equal(stored.length, 1);
1152 assert.equal(stored[0]?.event.type, "turn-item.updated");
1153 assert.equal(errorItems.length, 1);
1154 const errorItem = errorItems[0]?.item;
1155 assert.equal(errorItem?.type, "error");
1156 if (errorItem?.type !== "error") return;
1157 assert.equal(errorItem.failure.message, "Invalid reasoning effort.");
1158 assert.equal(errorItem.failure.code, "invalid_request");
1159 assert.deepEqual(errorItem.retry, {
1160 attempt: 3,
1161 maxAttempts: 3,
1162 retryDelayMs: 2_000,
1163 });
1164 const errorStartedAt = errorItem.startedAt;
1165 assert.ok(errorStartedAt);
1166 assert.equal(DateTime.toEpochMillis(errorStartedAt), DateTime.toEpochMillis(retryStartedAt));
1167 assert.equal(errorItem.providerThreadId, providerThreadId);
1168 assert.equal(errorItem.providerTurnId, providerTurnId);
1169 }),
1170 );
1171
1172 it.effect("routes provider-owned child artifacts to their child app thread", () =>
1173 Effect.gen(function* () {
1174 const now = yield* DateTime.now;
1175 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1176 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1177 const rootEvent = yield* threadCreatedEvent(now);
1178 if (rootEvent.type !== "thread.created") {
1179 throw new Error("Expected a thread.created fixture event");
1180 }
1181 const childThreadId = idAllocator.derive.threadFromProviderThread({
1182 driver: CODEX_DRIVER,
1183 nativeThreadId: "native-subagent-thread",
1184 });
1185 const childRootNodeId = NodeId.make("node:subagent-root");
1186 const childThread: OrchestrationV2AppThread = {
1187 ...rootEvent.payload,
1188 id: childThreadId,
1189 title: "inspect package",
1190 activeProviderThreadId: null,
1191 lineage: {
1192 parentThreadId: rootEvent.threadId,
1193 relationshipToParent: "subagent",
1194 rootThreadId: rootEvent.threadId,
1195 },
1196 forkedFrom: {
1197 type: "node",
1198 nodeId: NodeId.make("node:parent-subagent"),
1199 },
1200 };
1201 const providerSessionId = yield* idAllocator.allocate.providerSession({
1202 providerInstanceId: modelSelection.instanceId,
1203 threadId: rootEvent.threadId,
1204 });
1205
1206 const threadEvents = yield* ingestor.normalize({
1207 providerSessionId,
1208 providerInstanceId: modelSelection.instanceId,
1209 threadId: rootEvent.threadId,
1210 event: {
1211 type: "app_thread.created",
1212 driver: CODEX_DRIVER,
1213 appThread: childThread,
1214 },
1215 });
1216 const messageEvents = yield* ingestor.normalize({
1217 providerSessionId,
1218 providerInstanceId: modelSelection.instanceId,
1219 threadId: rootEvent.threadId,
1220 event: {
1221 type: "message.updated",
1222 driver: CODEX_DRIVER,
1223 message: {
1224 createdBy: "agent",
1225 creationSource: "provider",
1226 id: MessageId.make("message:subagent-response"),
1227 threadId: childThreadId,
1228 runId: null,
1229 nodeId: childRootNodeId,
1230 role: "assistant",
1231 text: "Subagent result",
1232 attachments: [],
1233 streaming: false,
1234 createdAt: now,
1235 updatedAt: now,
1236 },
1237 },
1238 });
1239
1240 assert.equal(threadEvents[0]?.type, "thread.created");
1241 assert.equal(threadEvents[0]?.threadId, childThreadId);
1242 assert.equal(messageEvents[0]?.type, "message.updated");
1243 assert.equal(messageEvents[0]?.threadId, childThreadId);
1244 }),
1245 );
1246
1247 it.effect("moves a native subagent's thread to the model its provider reports later", () =>
1248 Effect.gen(function* () {
1249 const now = yield* DateTime.now;
1250 const eventSink = yield* EventSink.EventSinkV2;
1251 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1252 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1253 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1254 const rootEvent = yield* threadCreatedEvent(now);
1255 if (rootEvent.type !== "thread.created") {
1256 throw new Error("Expected a thread.created fixture event");
1257 }
1258 const childThreadId = idAllocator.derive.threadFromProviderThread({
1259 driver: CODEX_DRIVER,
1260 nativeThreadId: "native-late-model-subagent",
1261 });
1262 const providerSessionId = yield* idAllocator.allocate.providerSession({
1263 providerInstanceId: modelSelection.instanceId,
1264 threadId: rootEvent.threadId,
1265 });
1266 const ingest = (event: ProviderEventIngestor.ProviderEventIngestInput["event"]) =>
1267 ingestor.ingestNormalized({
1268 providerSessionId,
1269 providerInstanceId: modelSelection.instanceId,
1270 threadId: rootEvent.threadId,
1271 event,
1272 });
1273 yield* eventSink.write({ events: [rootEvent] });
1274 // The subagent's thread starts on the parent's model and options.
1275 yield* ingest({
1276 type: "app_thread.created",
1277 driver: CODEX_DRIVER,
1278 appThread: {
1279 ...rootEvent.payload,
1280 id: childThreadId,
1281 title: "review design",
1282 modelSelection: {
1283 ...modelSelection,
1284 options: [{ id: "reasoningEffort", value: "xhigh" }],
1285 },
1286 activeProviderThreadId: null,
1287 lineage: {
1288 parentThreadId: rootEvent.threadId,
1289 relationshipToParent: "subagent",
1290 rootThreadId: rootEvent.threadId,
1291 },
1292 },
1293 });
1294 const subagentUpdated = {
1295 type: "subagent.updated",
1296 driver: CODEX_DRIVER,
1297 subagent: {
1298 id: NodeId.make("node:late-model-subagent"),
1299 threadId: rootEvent.threadId,
1300 runId: null,
1301 parentNodeId: NodeId.make("node:root"),
1302 origin: "provider_native",
1303 createdBy: "agent",
1304 driver: CODEX_DRIVER,
1305 providerInstanceId: modelSelection.instanceId,
1306 providerThreadId: null,
1307 childThreadId,
1308 nativeTaskRef: null,
1309 prompt: "Review the design",
1310 title: "review design",
1311 model: "gpt-6.1-sol",
1312 status: "running",
1313 result: null,
1314 startedAt: now,
1315 completedAt: null,
1316 updatedAt: now,
1317 },
1318 } satisfies ProviderEventIngestor.ProviderEventIngestInput["event"];
1319
1320 const first = yield* ingest(subagentUpdated);
1321 const repeated = yield* ingest(subagentUpdated);
1322 const childThread = yield* projectionStore.getThread(childThreadId);
1323
1324 assert.deepEqual(
1325 first.map((stored) => [stored.event.type, stored.event.threadId]),
1326 [
1327 ["subagent.updated", rootEvent.threadId],
1328 ["thread.model-selection-updated", childThreadId],
1329 ],
1330 );
1331 assert.deepEqual(
1332 repeated.map((stored) => stored.event.type),
1333 ["subagent.updated"],
1334 );
1335 assert.deepEqual(childThread.modelSelection, {
1336 instanceId: modelSelection.instanceId,
1337 model: "gpt-6.1-sol",
1338 });
1339 }),
1340 );
1341});