Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 ContextTransferId,
5 EventId,
6 MessageId,
7 NodeId,
8 type OrchestrationV2AppThread,
9 type OrchestrationV2Run,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ProviderSessionId,
14 ProviderThreadId,
15 RunId,
16 RuntimeRequestId,
17 ThreadId,
18 TurnItemId,
19} from "@t3tools/contracts";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as SqlClient from "effect/sql/SqlClient";
24
25import * as SqlitePersistence from "../persistence/Sqlite.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
28import * as EffectOutbox from "./EffectOutbox.ts";
29import * as ProjectionStore from "./ProjectionStore.ts";
30import * as EventSink from "./EventSink.ts";
31import * as EventStore from "./EventStore.ts";
32import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
33import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
34import { restartContinuationRun } from "./RestartContinuation.ts";
35
36const layerTest = Layer.mergeAll(ProjectionStore.layer, EffectOutbox.layer).pipe(
37 Layer.provideMerge(SqlitePersistence.layerMemory),
38);
39const layerRecoveryTest = ProviderRuntimeRecovery.layer.pipe(
40 Layer.provideMerge(
41 EventSink.layer.pipe(
42 Layer.provideMerge(
43 Layer.mergeAll(
44 EventStore.layer,
45 ProjectionStore.layer,
46 EffectOutbox.layer,
47 IdAllocator.layer,
48 ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
49 ),
50 ),
51 ),
52 Layer.provide(ServerSettings.layerTest()),
53);
54const providerInstanceId = ProviderInstanceId.make("codex");
55const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" };
56const driver = ProviderDriverKind.make("codex");
57
58const createThread = Effect.fn(function* (
59 name: string,
60 overrides: Partial<OrchestrationV2AppThread> = {},
61) {
62 const projections = yield* ProjectionStore.ProjectionStoreV2;
63 const now = yield* DateTime.now;
64 const threadId = ThreadId.make(`thread:recovery:${name}`);
65 const thread: OrchestrationV2AppThread = {
66 createdBy: "user",
67 creationSource: "web",
68 id: threadId,
69 projectId: ProjectId.make("project:recovery"),
70 title: name,
71 providerInstanceId,
72 modelSelection,
73 runtimeMode: "full-access",
74 interactionMode: "default",
75 branch: null,
76 worktreePath: null,
77 activeProviderThreadId: null,
78 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
79 forkedFrom: null,
80 createdAt: now,
81 updatedAt: now,
82 archivedAt: null,
83 settledOverride: null,
84 settledAt: null,
85 lastVisitedAt: null,
86 deletedAt: null,
87 ...overrides,
88 };
89 yield* projections.apply({
90 id: EventId.make(`event:${threadId}:created`),
91 type: "thread.created",
92 threadId,
93 occurredAt: now,
94 payload: thread,
95 });
96 return threadId;
97});
98
99const createRun = Effect.fn(function* (
100 threadId: ThreadId,
101 status: OrchestrationV2Run["status"],
102 overrides: Partial<OrchestrationV2Run> = {},
103) {
104 const projections = yield* ProjectionStore.ProjectionStoreV2;
105 const now = yield* DateTime.now;
106 const ordinal = overrides.ordinal ?? 1;
107 const runId = RunId.make(`run:${threadId}:${ordinal}`);
108 yield* projections.apply({
109 id: EventId.make(`event:${runId}:created`),
110 type: "run.created",
111 threadId,
112 runId,
113 occurredAt: now,
114 payload: {
115 id: runId,
116 threadId,
117 ordinal,
118 providerInstanceId,
119 modelSelection,
120 providerThreadId: null,
121 userMessageId: MessageId.make(`message:${runId}`),
122 rootNodeId: null,
123 activeAttemptId: null,
124 status,
125 requestedAt: now,
126 startedAt: now,
127 completedAt: status === "completed" ? now : null,
128 checkpointId: null,
129 contextHandoffId: null,
130 ...overrides,
131 },
132 });
133 return runId;
134});
135
136it.effect.each(["startup", "shutdown"] as const)(
137 "%s cancels queued buffered wakes and holds durable messages",
138 (trigger) =>
139 Effect.gen(function* () {
140 const projections = yield* ProjectionStore.ProjectionStoreV2;
141 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
142 const now = yield* DateTime.now;
143 const bufferedThreads = [] as ThreadId[];
144 const durableThreads = [] as ThreadId[];
145 for (const kind of ["buffered", "user", "notification", "delegated"] as const) {
146 const threadId = yield* createThread(`wake:${trigger}:${kind}`);
147 const buffered = kind === "buffered";
148 (buffered ? bufferedThreads : durableThreads).push(threadId);
149 const messageId = MessageId.make(`message:${threadId}`);
150 const runId = yield* createRun(threadId, "queued", {
151 userMessageId: messageId,
152 startedAt: null,
153 queuePosition: 1,
154 });
155 yield* createRun(threadId, "completed", { ordinal: 2 });
156 yield* projections.apply({
157 id: EventId.make(`message:${threadId}`),
158 type: "message.updated",
159 threadId,
160 runId,
161 occurredAt: now,
162 payload: {
163 id: messageId,
164 threadId,
165 runId,
166 nodeId: null,
167 role: "user",
168 text: "Queued work",
169 attachments: [],
170 streaming: false,
171 createdAt: now,
172 updatedAt: now,
173 createdBy: kind === "user" ? "user" : "agent",
174 creationSource: buffered ? "provider" : "server",
175 ...(kind === "user" || kind === "delegated"
176 ? {}
177 : {
178 notification: {
179 source: { kind: "background_task" as const },
180 outcome: "updated" as const,
181 summary: "Background activity updated",
182 },
183 }),
184 ...(kind === "delegated"
185 ? { delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [] } }
186 : {}),
187 },
188 });
189 }
190 assert.deepEqual(
191 new Set(yield* projections.getRecoveryThreadIds("runtime")),
192 new Set([...bufferedThreads, ...durableThreads]),
193 );
194 const summary = yield* recovery.reconcile(trigger);
195 assert.equal(summary.terminalizedRuns, 1);
196 for (const threadId of bufferedThreads) {
197 const projection = yield* projections.getThreadProjection(threadId);
198 assert.equal(projection.runs[0]?.status, "cancelled");
199 assert.isNotNull(projection.runs[0]?.completedAt);
200 assert.isNull(projection.runs[0]?.queuePosition);
201 assert.equal(projection.runs[1]?.status, "completed");
202 }
203 for (const threadId of durableThreads) {
204 const projection = yield* projections.getThreadProjection(threadId);
205 assert.equal(projection.runs[0]?.status, "queued");
206 assert.isTrue(projection.runs[0]?.queueHeld);
207 }
208 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), []);
209 }).pipe(Effect.provide(layerRecoveryTest)),
210);
211
212it.effect("stops a session its thread detached, which kept its live status", () =>
213 Effect.gen(function* () {
214 const projections = yield* ProjectionStore.ProjectionStoreV2;
215 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
216 const now = yield* DateTime.now;
217 const threadId = yield* createThread("detached-session");
218 const providerSessionId = ProviderSessionId.make("session:recovery:detached");
219 yield* projections.apply({
220 id: EventId.make("event:recovery:detached-session:attached"),
221 type: "provider-session.attached",
222 threadId,
223 driver,
224 providerInstanceId,
225 occurredAt: now,
226 payload: {
227 id: providerSessionId,
228 driver,
229 providerInstanceId,
230 status: "ready",
231 cwd: "/workspace",
232 model: modelSelection.model,
233 capabilities: CodexProviderCapabilitiesV2,
234 createdAt: now,
235 updatedAt: now,
236 lastError: null,
237 },
238 });
239 yield* projections.apply({
240 id: EventId.make("event:recovery:detached-session:detached"),
241 type: "provider-session.detached",
242 threadId,
243 driver,
244 providerInstanceId,
245 occurredAt: now,
246 payload: { providerSessionId, detachedAt: now, reason: "Thread settled." },
247 });
248 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), [threadId]);
249
250 const summary = yield* recovery.reconcile("startup");
251
252 assert.equal(summary.stoppedSessions, 1);
253 const sql = yield* SqlClient.SqlClient;
254 const rows = yield* sql<{ readonly status: string }>`
255 SELECT status FROM orchestration_v2_projection_provider_sessions
256 WHERE provider_session_id = ${providerSessionId}
257 `;
258 assert.deepEqual(rows, [{ status: "stopped" }]);
259 assert.deepEqual(yield* projections.getRecoveryThreadIds("runtime"), []);
260 }).pipe(Effect.provide(layerRecoveryTest)),
261);
262
263it.effect("selects unfinished recovery work without reading settled thread histories", () =>
264 Effect.gen(function* () {
265 const projections = yield* ProjectionStore.ProjectionStoreV2;
266 const outbox = yield* EffectOutbox.EffectOutboxV2;
267 const sql = yield* SqlClient.SqlClient;
268 const now = yield* DateTime.now;
269 for (let index = 0; index < 600; index += 1) {
270 yield* createRun(yield* createThread(`settled-${index}`), "completed");
271 }
272 const queued = yield* createThread("queued");
273 const archived = yield* createThread("archived", { archivedAt: now });
274 const deleted = yield* createThread("deleted", { deletedAt: now });
275 const blocked = yield* createThread("blocked");
276 yield* createRun(queued, "completed");
277 for (const threadId of [queued, archived, deleted, blocked]) {
278 yield* createRun(threadId, "queued", threadId === queued ? { ordinal: 2 } : {});
279 }
280 yield* createRun(blocked, "waiting", { ordinal: 2 });
281 const background = yield* createThread("background");
282 yield* createRun(background, "completed");
283 yield* projections.apply({
284 id: EventId.make("event:recovery:background"),
285 type: "turn-item.updated",
286 threadId: background,
287 occurredAt: now,
288 payload: {
289 id: TurnItemId.make("item:recovery:background"),
290 threadId: background,
291 runId: null,
292 nodeId: null,
293 providerThreadId: null,
294 providerTurnId: null,
295 nativeItemRef: null,
296 parentItemId: null,
297 ordinal: 1,
298 type: "dynamic_tool",
299 status: "waiting",
300 title: null,
301 startedAt: now,
302 completedAt: null,
303 updatedAt: now,
304 toolName: "background",
305 input: null,
306 output: null,
307 },
308 });
309 const outboxOnly = yield* createThread("outbox-only");
310 yield* outbox.enqueue([
311 {
312 id: "effect:recovery:outbox-only",
313 commandId: CommandId.make("command:recovery:outbox-only"),
314 threadId: outboxOnly,
315 request: { type: "provider-turn.start", runId: RunId.make("run:outbox-only") },
316 },
317 ]);
318 const requestOnly = yield* createThread("request-only");
319 yield* projections.apply({
320 id: EventId.make("event:recovery:request-only"),
321 type: "runtime-request.updated",
322 threadId: requestOnly,
323 occurredAt: now,
324 payload: {
325 id: RuntimeRequestId.make("request:recovery:pending"),
326 nodeId: NodeId.make("node:recovery:request"),
327 providerTurnId: null,
328 nativeRequestRef: null,
329 kind: "user_input",
330 status: "pending",
331 responseCapability: { type: "not_resumable", reason: "Process stopped" },
332 createdAt: now,
333 resolvedAt: null,
334 },
335 });
336 const delivery = yield* createThread("delivery", { archivedAt: now });
337 yield* createRun(delivery, "completed", {
338 delegatedCompletion: {
339 disposition: "open",
340 nextGeneration: 2,
341 delivery: { generation: 1, messageId: MessageId.make("message:delivery"), taskIds: [] },
342 },
343 });
344
345 yield* sql`
346 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
347 WHERE thread_id = ${ThreadId.make("thread:recovery:settled-599")}
348 `;
349 yield* sql`
350 UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
351 WHERE thread_id = ${queued} AND ordinal = 1
352 `;
353 assert.deepEqual(yield* projections.getRecoveryThreadIds("queued-runs"), [queued]);
354 assert.deepEqual(
355 new Set(yield* projections.getRecoveryThreadIds("runtime")),
356 new Set([queued, archived, blocked, background, outboxOnly, requestOnly]),
357 );
358 assert.deepEqual(yield* projections.getRecoveryThreadIds("delegated-completions"), [delivery]);
359 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
360 const recoveryState = yield* projections.getRuntimeRecoveryProjection(queued);
361 assert.deepEqual(
362 recoveryState.runs.map((run) => run.id),
363 [RunId.make(`run:${queued}:2`)],
364 );
365 assert.deepEqual(yield* projections.getUnreadableThreadIds(), [
366 queued,
367 ThreadId.make("thread:recovery:settled-599"),
368 ]);
369 }).pipe(Effect.provide(layerTest)),
370);
371
372it.effect("recovers terminal subagent results until their cross-thread transfer exists", () =>
373 Effect.gen(function* () {
374 const projections = yield* ProjectionStore.ProjectionStoreV2;
375 const sql = yield* SqlClient.SqlClient;
376 const now = yield* DateTime.now;
377 const parent = yield* createThread("subagent-parent");
378 const children: Array<ThreadId> = [];
379 for (const name of ["terminal", "archived", "deleted", "running", "held", "queued"]) {
380 const child = yield* createThread(`subagent-${name}`, {
381 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
382 forkedFrom: { type: "node", nodeId: NodeId.make(`node:${name}`) },
383 archivedAt: name === "archived" ? now : null,
384 deletedAt: name === "deleted" ? now : null,
385 });
386 yield* createRun(child, name === "running" ? "running" : "completed");
387 if (name === "held" || name === "queued") {
388 yield* createRun(child, "queued", {
389 ordinal: 2,
390 startedAt: null,
391 ...(name === "held" ? { queueHeld: true } : {}),
392 });
393 }
394 children.push(child);
395 }
396 const terminalChildren = new Set([children[0]!, children[1]!, children[4]!]);
397 assert.deepEqual(
398 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
399 terminalChildren,
400 );
401
402 const completed = children[0]!;
403 const transferId = ContextTransferId.make("transfer:recovery:subagent-result");
404 yield* projections.apply({
405 id: EventId.make("event:recovery:subagent-result"),
406 type: "context-transfer.created",
407 threadId: parent,
408 occurredAt: now,
409 payload: {
410 id: transferId,
411 type: "subagent_result",
412 sourceThreadId: completed,
413 targetThreadId: parent,
414 sourcePoint: { threadId: completed },
415 basePoint: null,
416 sourceProviderInstanceId: providerInstanceId,
417 targetProviderInstanceId: providerInstanceId,
418 targetRunId: null,
419 status: "pending",
420 resolution: null,
421 createdBy: "system",
422 error: null,
423 createdAt: now,
424 updatedAt: now,
425 consumedAt: null,
426 },
427 });
428 const archivedChild = children[1];
429 assert.isDefined(archivedChild);
430 assert.deepEqual(
431 new Set(yield* projections.getRecoveryThreadIds("subagent-results")),
432 new Set([archivedChild, children[4]!]),
433 );
434 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
435 yield* sql`
436 UPDATE orchestration_v2_projection_context_transfers SET payload_json = '{}'
437 WHERE context_transfer_id = ${transferId}
438 `;
439 assert.deepEqual(
440 new Set(yield* projections.getUnreadableThreadIds()),
441 new Set([parent, completed]),
442 );
443 }).pipe(Effect.provide(layerTest)),
444);
445
446it.effect.each([
447 { name: "SQLite", layer: layerTest },
448 { name: "memory", layer: ProjectionStore.layerMemory },
449])("recovers only recorded follow-up results with $name projections", ({ layer }) =>
450 Effect.gen(function* () {
451 const projections = yield* ProjectionStore.ProjectionStoreV2;
452 const now = yield* DateTime.now;
453 const parent = yield* createThread("followup-parent");
454 const child = yield* createThread("followup-child", {
455 lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
456 forkedFrom: { type: "node", nodeId: NodeId.make("node:original") },
457 });
458 const originalRunId = yield* createRun(child, "completed");
459 yield* projections.apply({
460 id: EventId.make("event:original-result"),
461 type: "context-transfer.created",
462 threadId: parent,
463 occurredAt: now,
464 payload: {
465 id: ContextTransferId.make("transfer:original-result"),
466 type: "subagent_result",
467 sourceThreadId: child,
468 targetThreadId: parent,
469 sourcePoint: { threadId: child, runId: originalRunId },
470 basePoint: null,
471 sourceProviderInstanceId: providerInstanceId,
472 targetProviderInstanceId: providerInstanceId,
473 targetRunId: null,
474 status: "pending",
475 resolution: null,
476 createdBy: "system",
477 error: null,
478 createdAt: now,
479 updatedAt: now,
480 consumedAt: null,
481 },
482 });
483 yield* createRun(child, "completed", { ordinal: 2 });
484 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
485 const taskId = NodeId.make("node:followup");
486 yield* createRun(child, "completed", { ordinal: 3, delegatedTaskId: taskId });
487 yield* createRun(child, "running", { ordinal: 4 });
488 const task = {
489 id: taskId,
490 threadId: parent,
491 runId: null,
492 parentNodeId: NodeId.make("node:parent"),
493 origin: "app_owned" as const,
494 createdBy: "agent" as const,
495 driver,
496 providerInstanceId,
497 providerThreadId: null,
498 childThreadId: child,
499 nativeTaskRef: null,
500 prompt: "Check the follow-up.",
501 title: null,
502 model: null,
503 status: "running" as const,
504 result: null,
505 startedAt: now,
506 completedAt: null,
507 updatedAt: now,
508 };
509 yield* projections.apply({
510 id: EventId.make("event:followup-task"),
511 type: "subagent.updated",
512 threadId: parent,
513 occurredAt: now,
514 payload: task,
515 });
516 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), [child]);
517 yield* projections.apply({
518 id: EventId.make("event:followup-settled"),
519 type: "subagent.updated",
520 threadId: parent,
521 occurredAt: now,
522 payload: { ...task, status: "completed", result: "Follow-up result.", completedAt: now },
523 });
524 assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
525 }).pipe(Effect.provide(layer)),
526);
527
528it.effect("includes shared sessions and provider-owned background rosters in recovery", () =>
529 Effect.gen(function* () {
530 const projections = yield* ProjectionStore.ProjectionStoreV2;
531 const now = yield* DateTime.now;
532 const first = yield* createThread("shared-first");
533 const second = yield* createThread("shared-second", { archivedAt: now });
534 const providerSessionId = ProviderSessionId.make("session:recovery:shared");
535 for (const threadId of [first, second]) {
536 yield* projections.apply({
537 id: EventId.make(`event:${threadId}:session`),
538 type: "provider-session.attached",
539 threadId,
540 driver,
541 providerInstanceId,
542 occurredAt: now,
543 payload: {
544 id: providerSessionId,
545 driver,
546 providerInstanceId,
547 status: "ready",
548 cwd: "/workspace",
549 model: modelSelection.model,
550 capabilities: CodexProviderCapabilitiesV2,
551 createdAt: now,
552 updatedAt: now,
553 lastError: null,
554 },
555 });
556 }
557 const roster = yield* createThread("roster");
558 yield* projections.apply({
559 id: EventId.make("event:recovery:roster"),
560 type: "provider-thread.updated",
561 threadId: roster,
562 driver,
563 providerInstanceId,
564 occurredAt: now,
565 payload: {
566 id: ProviderThreadId.make("provider-thread:recovery:roster"),
567 appThreadId: roster,
568 ownerNodeId: null,
569 driver,
570 providerInstanceId,
571 providerSessionId: null,
572 nativeThreadRef: null,
573 nativeConversationHeadRef: null,
574 status: "idle",
575 firstRunOrdinal: null,
576 lastRunOrdinal: null,
577 handoffIds: [],
578 forkedFrom: null,
579 createdAt: now,
580 updatedAt: now,
581 pendingBackgroundTasks: [
582 { taskId: "background", description: "Still running", kind: "command" },
583 ],
584 },
585 });
586 const prepared = yield* createThread("prepared-continuation");
587 const preparedSessionId = ProviderSessionId.make("session:recovery:prepared");
588 const preparedProviderThreadId = ProviderThreadId.make("provider-thread:recovery:prepared");
589 yield* projections.apply({
590 id: EventId.make("event:recovery:prepared-session"),
591 type: "provider-session.attached",
592 threadId: prepared,
593 driver,
594 providerInstanceId,
595 occurredAt: now,
596 payload: {
597 id: preparedSessionId,
598 driver,
599 providerInstanceId,
600 status: "stopped",
601 cwd: "/workspace",
602 model: modelSelection.model,
603 capabilities: CodexProviderCapabilitiesV2,
604 createdAt: now,
605 updatedAt: now,
606 lastError: null,
607 },
608 });
609 yield* projections.apply({
610 id: EventId.make("event:recovery:prepared-thread"),
611 type: "provider-thread.updated",
612 threadId: prepared,
613 driver,
614 providerInstanceId,
615 occurredAt: now,
616 payload: {
617 id: preparedProviderThreadId,
618 appThreadId: prepared,
619 ownerNodeId: null,
620 driver,
621 providerInstanceId,
622 providerSessionId: preparedSessionId,
623 nativeThreadRef: { driver, nativeId: "native:prepared", strength: "strong" },
624 nativeConversationHeadRef: null,
625 status: "idle",
626 firstRunOrdinal: 1,
627 lastRunOrdinal: 1,
628 handoffIds: [],
629 forkedFrom: null,
630 createdAt: now,
631 updatedAt: now,
632 pendingBackgroundTasks: [],
633 },
634 });
635 const preparedRunId = yield* createRun(prepared, "starting", {
636 providerThreadId: preparedProviderThreadId,
637 restartContinuationOfRunId: RunId.make("run:recovery:source"),
638 });
639 assert.deepEqual(
640 new Set(yield* projections.getRecoveryThreadIds("runtime")),
641 new Set([first, second, roster, prepared]),
642 );
643 const preparedState = yield* projections.getRuntimeRecoveryProjection(prepared);
644 assert.deepEqual(
645 preparedState.providerSessions.map((session) => session.id),
646 [preparedSessionId],
647 );
648 assert.equal(restartContinuationRun(preparedState, yield* DateTime.now)?.id, preparedRunId);
649 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
650 const sql = yield* SqlClient.SqlClient;
651 yield* sql`
652 UPDATE orchestration_v2_projection_provider_sessions SET payload_json = '{}'
653 WHERE provider_session_id = ${providerSessionId}
654 `;
655 assert.deepEqual(
656 new Set(yield* projections.getUnreadableThreadIds()),
657 new Set([first, second]),
658 );
659 }).pipe(Effect.provide(layerTest)),
660);
661
662it.effect("reads the run that owns a background roster, not a queued or resumed one", () =>
663 Effect.gen(function* () {
664 const projections = yield* ProjectionStore.ProjectionStoreV2;
665 const now = yield* DateTime.now;
666 const withRoster = Effect.fn(function* (threadId: ThreadId) {
667 yield* projections.apply({
668 id: EventId.make(`event:${threadId}:roster`),
669 type: "provider-thread.updated",
670 threadId,
671 driver,
672 providerInstanceId,
673 occurredAt: now,
674 payload: {
675 id: ProviderThreadId.make(`provider-thread:${threadId}`),
676 appThreadId: threadId,
677 ownerNodeId: null,
678 driver,
679 providerInstanceId,
680 providerSessionId: null,
681 nativeThreadRef: null,
682 nativeConversationHeadRef: null,
683 status: "idle",
684 firstRunOrdinal: null,
685 lastRunOrdinal: null,
686 handoffIds: [],
687 forkedFrom: null,
688 createdAt: now,
689 updatedAt: now,
690 pendingBackgroundTasks: [
691 { taskId: "background", description: "Still running", kind: "command" },
692 ],
693 },
694 });
695 });
696 const runIds = (threadId: ThreadId) =>
697 projections
698 .getRuntimeRecoveryProjection(threadId)
699 .pipe(Effect.map((state) => state.runs.map((run) => run.id)));
700 const settled = yield* createThread("roster-before-queue");
701 const settledRun = yield* createRun(settled, "completed", {
702 providerThreadId: ProviderThreadId.make(`provider-thread:${settled}`),
703 });
704 const queuedRun = yield* createRun(settled, "queued", { ordinal: 2, completedAt: null });
705 yield* withRoster(settled);
706 assert.deepEqual(yield* runIds(settled), [settledRun, queuedRun]);
707 const resumed = yield* createThread("roster-after-resume");
708 const resumedRun = yield* createRun(resumed, "completed", {
709 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
710 completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"),
711 });
712 const continuationRun = yield* createRun(resumed, "completed", {
713 providerThreadId: ProviderThreadId.make(`provider-thread:${resumed}`),
714 ordinal: 2,
715 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
716 });
717 yield* withRoster(resumed);
718 assert.deepEqual(yield* runIds(resumed), [resumedRun, continuationRun]);
719 const quiet = yield* createThread("no-roster-before-queue");
720 yield* createRun(quiet, "completed");
721 const quietQueued = yield* createRun(quiet, "queued", { ordinal: 2, completedAt: null });
722 assert.deepEqual(yield* runIds(quiet), [quietQueued]);
723 }).pipe(Effect.provide(layerTest)),
724);
725
726it.effect("wakes the run whose subagent lost its shell, past a wake cut before it started", () =>
727 Effect.gen(function* () {
728 const projections = yield* ProjectionStore.ProjectionStoreV2;
729 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
730 const sql = yield* SqlClient.SqlClient;
731 const now = yield* DateTime.now;
732 const threadId = yield* createThread("subagent-shell");
733 const providerThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
734 const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
735 yield* projections.apply({
736 id: EventId.make(`event:${threadId}:session`),
737 type: "provider-session.attached",
738 threadId,
739 driver,
740 providerInstanceId,
741 occurredAt: now,
742 payload: {
743 id: providerSessionId,
744 driver,
745 providerInstanceId,
746 status: "ready",
747 cwd: "/workspace",
748 model: modelSelection.model,
749 capabilities: CodexProviderCapabilitiesV2,
750 createdAt: now,
751 updatedAt: now,
752 lastError: null,
753 },
754 });
755 const settledRun = yield* createRun(threadId, "completed", { providerThreadId });
756 yield* createRun(threadId, "starting", {
757 ordinal: 2,
758 providerThreadId,
759 startedAt: null,
760 completedAt: null,
761 });
762 yield* projections.apply({
763 id: EventId.make(`event:${threadId}:roster`),
764 type: "provider-thread.updated",
765 threadId,
766 driver,
767 providerInstanceId,
768 occurredAt: now,
769 payload: {
770 id: providerThreadId,
771 appThreadId: threadId,
772 ownerNodeId: null,
773 driver,
774 providerInstanceId,
775 providerSessionId,
776 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
777 nativeConversationHeadRef: null,
778 status: "idle",
779 firstRunOrdinal: 1,
780 lastRunOrdinal: 2,
781 handoffIds: [],
782 forkedFrom: null,
783 createdAt: now,
784 updatedAt: now,
785 pendingBackgroundTasks: [
786 { taskId: "shell", description: "sleep 150", kind: "command", parentTaskId: "agent" },
787 ],
788 },
789 });
790
791 yield* recovery.reconcile("startup");
792
793 const effects = yield* sql<{ readonly effect_id: string }>`
794 SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
795 `;
796 assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
797 const projection = yield* projections.getThreadProjection(threadId);
798 assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
799 { kind: "subagent", label: "sleep 150 (subagent agent)", id: "agent" },
800 ]);
801 }).pipe(Effect.provide(layerRecoveryTest)),
802);
803
804it.effect("wakes a settled run whose native subagent ran on its own provider thread", () =>
805 Effect.gen(function* () {
806 const projections = yield* ProjectionStore.ProjectionStoreV2;
807 const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
808 const sql = yield* SqlClient.SqlClient;
809 const now = yield* DateTime.now;
810 const threadId = yield* createThread("native-subagent");
811 const parentProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
812 const childProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}:child`);
813 const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
814 const subagentId = NodeId.make(`node:${threadId}:subagent`);
815 // An older thread on the same Codex session is recovered first and stops it.
816 const sibling = yield* createThread("a-shared-session");
817 yield* createRun(sibling, "completed");
818 for (const boundThreadId of [sibling, threadId]) {
819 yield* projections.apply({
820 id: EventId.make(`event:${boundThreadId}:session`),
821 type: "provider-session.attached",
822 threadId: boundThreadId,
823 driver,
824 providerInstanceId,
825 occurredAt: now,
826 payload: {
827 id: providerSessionId,
828 driver,
829 providerInstanceId,
830 status: "ready",
831 cwd: "/workspace",
832 model: modelSelection.model,
833 capabilities: CodexProviderCapabilitiesV2,
834 createdAt: now,
835 updatedAt: now,
836 lastError: null,
837 },
838 });
839 }
840 const settledRun = yield* createRun(threadId, "completed", {
841 providerThreadId: parentProviderThreadId,
842 });
843 for (const [id, nativeId] of [
844 [parentProviderThreadId, "native-thread"],
845 [childProviderThreadId, "agent-thread"],
846 ] as const) {
847 yield* projections.apply({
848 id: EventId.make(`event:${id}`),
849 type: "provider-thread.updated",
850 threadId,
851 driver,
852 providerInstanceId,
853 occurredAt: now,
854 payload: {
855 id,
856 appThreadId:
857 id === parentProviderThreadId ? threadId : ThreadId.make(`${threadId}:child`),
858 ownerNodeId: null,
859 driver,
860 providerInstanceId,
861 providerSessionId,
862 nativeThreadRef: { driver, nativeId, strength: "strong" },
863 nativeConversationHeadRef: null,
864 status: "idle",
865 firstRunOrdinal: id === parentProviderThreadId ? 1 : null,
866 lastRunOrdinal: id === parentProviderThreadId ? 1 : null,
867 handoffIds: [],
868 forkedFrom: null,
869 createdAt: now,
870 updatedAt: now,
871 },
872 });
873 }
874 const subagent = {
875 threadId,
876 runId: settledRun,
877 origin: "provider_native",
878 driver,
879 providerInstanceId,
880 childThreadId: null,
881 prompt: "audit src",
882 status: "running",
883 result: null,
884 startedAt: now,
885 completedAt: null,
886 updatedAt: now,
887 } as const;
888 yield* projections.apply({
889 id: EventId.make(`event:${threadId}:subagent`),
890 type: "subagent.updated",
891 threadId,
892 occurredAt: now,
893 payload: {
894 ...subagent,
895 id: subagentId,
896 parentNodeId: NodeId.make(`node:${threadId}:root`),
897 createdBy: "agent",
898 providerThreadId: childProviderThreadId,
899 nativeTaskRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
900 title: null,
901 model: null,
902 },
903 });
904 yield* projections.apply({
905 id: EventId.make(`event:${threadId}:subagent-item`),
906 type: "turn-item.updated",
907 threadId,
908 occurredAt: now,
909 payload: {
910 ...subagent,
911 id: TurnItemId.make(`item:${threadId}:subagent`),
912 nodeId: subagentId,
913 providerThreadId: childProviderThreadId,
914 providerTurnId: null,
915 nativeItemRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
916 parentItemId: null,
917 ordinal: 1,
918 type: "subagent",
919 title: "audit",
920 subagentId,
921 },
922 });
923
924 yield* recovery.reconcile("startup");
925
926 const effects = yield* sql<{ readonly effect_id: string }>`
927 SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
928 `;
929 assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
930 const projection = yield* projections.getThreadProjection(threadId);
931 assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
932 {
933 kind: "subagent",
934 label: "audit (id agent-thread)",
935 id: TurnItemId.make(`item:${threadId}:subagent`),
936 },
937 ]);
938 }).pipe(Effect.provide(layerRecoveryTest)),
939);
940
941it.effect("marks fork descendants unreadable when their source is missing or corrupt", () =>
942 Effect.gen(function* () {
943 const projections = yield* ProjectionStore.ProjectionStoreV2;
944 const sql = yield* SqlClient.SqlClient;
945 const source = yield* createThread("source");
946 const sourceRun = yield* createRun(source, "completed");
947 const fork = yield* createThread("fork", {
948 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
949 });
950 const descendant = yield* createThread("descendant", {
951 forkedFrom: { type: "run", threadId: fork, runId: RunId.make("run:fork") },
952 });
953 assert.deepEqual(yield* projections.getUnreadableThreadIds(), []);
954 yield* sql`
955 UPDATE orchestration_v2_projection_runs SET payload_json = '{}'
956 WHERE run_id = ${sourceRun}
957 `;
958 assert.deepEqual(
959 new Set(yield* projections.getUnreadableThreadIds()),
960 new Set([source, fork, descendant]),
961 );
962 yield* sql`DELETE FROM orchestration_v2_projection_threads WHERE thread_id = ${source}`;
963 assert.deepEqual(
964 new Set(yield* projections.getUnreadableThreadIds()),
965 new Set([fork, descendant]),
966 );
967 }).pipe(Effect.provide(layerTest)),
968);