Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { assert, it } from "@effect/vitest";
3import {
4 CheckpointId,
5 CheckpointRef,
6 CheckpointScopeId,
7 EventId,
8 MessageId,
9 NodeId,
10 type OrchestrationV2DomainEvent,
11 type OrchestrationV2Run,
12 ProjectId,
13 ProviderDriverKind,
14 ProviderInstanceId,
15 ProviderThreadId,
16 RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Ref from "effect/Ref";
23import * as SqlClient from "effect/sql/SqlClient";
24
25import * as SqlitePersistence from "../persistence/Sqlite.ts";
26import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
27import { VcsProcessTimeoutError } from "@t3tools/contracts";
28import * as CheckpointService from "./CheckpointService.ts";
29import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
30import * as EventSink from "./EventSink.ts";
31import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
32import * as ProjectionStore from "./ProjectionStore.ts";
33
34const layerProjectionStoreTest = Layer.mergeAll(
35 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
36 SqlitePersistence.layerMemory,
37);
38
39const threadId = ThreadId.make("thread:checkpoint-capture-delegated");
40const projectId = ProjectId.make("project:checkpoint-capture-delegated");
41const runId = RunId.make("run:checkpoint-capture-delegated");
42const scopeId = CheckpointScopeId.make("scope:checkpoint-capture-delegated");
43const rootNodeId = NodeId.make("node:checkpoint-capture-delegated-root");
44const taskId = NodeId.make("node:checkpoint-capture-task");
45const deliveryMessageId = MessageId.make("message:checkpoint-capture-delivery");
46const providerThreadId = ProviderThreadId.make("provider-thread:checkpoint-capture-delegated");
47const providerInstanceId = ProviderInstanceId.make("codex");
48const driver = ProviderDriverKind.make("codex");
49const modelSelection = {
50 instanceId: providerInstanceId,
51 model: "gpt-5.4",
52} as const;
53
54it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
55 it.effect.each([false, true])(
56 "captures without decoding history or losing newer delegated completion, ref lookup fails=%s",
57 (refLookupFails) =>
58 Effect.gen(function* () {
59 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
60 const now = yield* DateTime.now;
61 const later = DateTime.add(now, { seconds: 1 });
62
63 const staleDelegatedCompletion = {
64 disposition: "open" as const,
65 nextGeneration: 1,
66 delivery: null,
67 };
68 const newerCohort = {
69 disposition: "open" as const,
70 nextGeneration: 2,
71 delivery: {
72 generation: 1,
73 messageId: deliveryMessageId,
74 taskIds: [taskId],
75 },
76 };
77 const staleRun: OrchestrationV2Run = {
78 id: runId,
79 threadId,
80 ordinal: 1,
81 providerInstanceId,
82 modelSelection,
83 providerThreadId,
84 userMessageId: MessageId.make("message:checkpoint-capture-user"),
85 rootNodeId,
86 activeAttemptId: null,
87 status: "waiting",
88 requestedAt: now,
89 startedAt: now,
90 completedAt: null,
91 checkpointId: null,
92 contextHandoffId: null,
93 delegatedCompletion: staleDelegatedCompletion,
94 };
95 const rootNode = {
96 id: rootNodeId,
97 threadId,
98 runId,
99 parentNodeId: null,
100 rootNodeId,
101 kind: "root_turn" as const,
102 status: "waiting" as const,
103 countsForRun: true,
104 providerThreadId,
105 providerTurnId: null,
106 nativeItemRef: null,
107 runtimeRequestId: null,
108 checkpointScopeId: scopeId,
109 startedAt: now,
110 completedAt: null,
111 };
112 const scope = {
113 id: scopeId,
114 threadId,
115 runId,
116 nodeId: rootNodeId,
117 parentScopeId: null,
118 providerThreadId,
119 kind: "root_run" as const,
120 ordinalWithinParent: 0,
121 advancesAppRunCount: true,
122 cwd: "/repo",
123 createdAt: now,
124 };
125 const providerThread = {
126 id: providerThreadId,
127 driver,
128 providerInstanceId,
129 providerSessionId: null,
130 appThreadId: threadId,
131 ownerNodeId: rootNodeId,
132 nativeThreadRef: null,
133 nativeConversationHeadRef: null,
134 status: "idle" as const,
135 firstRunOrdinal: 1,
136 lastRunOrdinal: 1,
137 handoffIds: [],
138 forkedFrom: null,
139 createdAt: now,
140 updatedAt: now,
141 };
142 const readyBaseline = {
143 id: CheckpointId.make("checkpoint:baseline-0"),
144 threadId,
145 scopeId,
146 runId: null,
147 nodeId: rootNodeId,
148 parentCheckpointId: null,
149 ordinalWithinScope: 0,
150 appRunOrdinal: null,
151 ref: CheckpointRef.make("checkpoint-ref:baseline-0"),
152 status: "ready" as const,
153 files: [],
154 capturedAt: now,
155 };
156 const captured = {
157 id: CheckpointId.make("checkpoint:captured-1"),
158 threadId,
159 scopeId,
160 runId,
161 nodeId: rootNodeId,
162 parentCheckpointId: readyBaseline.id,
163 ordinalWithinScope: 1,
164 appRunOrdinal: 1,
165 ref: CheckpointRef.make("checkpoint-ref:captured-1"),
166 status: "ready" as const,
167 files: [],
168 capturedAt: now,
169 };
170
171 yield* projectionStore.apply({
172 id: EventId.make("event:checkpoint-capture:thread"),
173 type: "thread.created",
174 threadId,
175 occurredAt: now,
176 payload: {
177 createdBy: "user",
178 creationSource: "web",
179 id: threadId,
180 projectId,
181 title: "Checkpoint capture delegated completion",
182 providerInstanceId,
183 modelSelection,
184 runtimeMode: "full-access",
185 interactionMode: "default",
186 branch: null,
187 worktreePath: null,
188 activeProviderThreadId: null,
189 lineage: {
190 parentThreadId: null,
191 relationshipToParent: null,
192 rootThreadId: threadId,
193 },
194 forkedFrom: null,
195 createdAt: now,
196 updatedAt: now,
197 archivedAt: null,
198 settledOverride: null,
199 settledAt: null,
200 lastVisitedAt: null,
201 deletedAt: null,
202 },
203 });
204 yield* projectionStore.apply({
205 id: EventId.make("event:checkpoint-capture:run-stale"),
206 type: "run.updated",
207 threadId,
208 runId,
209 nodeId: rootNodeId,
210 providerInstanceId,
211 occurredAt: now,
212 payload: staleRun,
213 });
214 yield* projectionStore.apply({
215 id: EventId.make("event:checkpoint-capture:node"),
216 type: "node.updated",
217 threadId,
218 runId,
219 nodeId: rootNodeId,
220 providerInstanceId,
221 occurredAt: now,
222 payload: rootNode,
223 });
224 yield* projectionStore.apply({
225 id: EventId.make("event:checkpoint-capture:provider-thread"),
226 type: "provider-thread.updated",
227 threadId,
228 nodeId: rootNodeId,
229 driver,
230 providerInstanceId,
231 occurredAt: now,
232 payload: providerThread,
233 });
234 yield* projectionStore.apply({
235 id: EventId.make("event:checkpoint-capture:scope"),
236 type: "checkpoint-scope.created",
237 threadId,
238 runId,
239 nodeId: rootNodeId,
240 occurredAt: now,
241 payload: scope,
242 });
243 yield* projectionStore.apply({
244 id: EventId.make("event:checkpoint-capture:baseline"),
245 type: "checkpoint.captured",
246 threadId,
247 nodeId: rootNodeId,
248 driver,
249 providerInstanceId,
250 occurredAt: now,
251 payload: readyBaseline,
252 });
253 const sql = yield* SqlClient.SqlClient;
254 yield* sql`INSERT OR REPLACE INTO orchestration_v2_projection_turn_items
255 (turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
256 parent_item_id, ordinal, type, status, updated_at, payload_json)
257 VALUES ('obsolete-history', ${threadId}, ${runId}, ${rootNodeId}, NULL, NULL,
258 NULL, 1, 'assistant_message', 'completed', ${DateTime.formatIso(now)}, '{"obsolete":true}')`;
259 yield* sql`UPDATE orchestration_v2_projection_checkpoints
260 SET payload_json = json_set(payload_json, '$.files', 'obsolete file summary')
261 WHERE checkpoint_id = ${readyBaseline.id}`;
262 assert.equal(
263 (yield* Effect.exit(projectionStore.getThreadProjection(threadId)))._tag,
264 "Failure",
265 );
266
267 const committed = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
268 const layerCapture = CheckpointCaptureService.layer.pipe(
269 Layer.provide(
270 Layer.mergeAll(
271 IdAllocator.layer,
272 refLookupFails
273 ? CheckpointService.layer.pipe(
274 Layer.provide(
275 Layer.mergeAll(
276 IdAllocator.layer,
277 NodeCrypto.layer,
278 Layer.mock(CheckpointStore.CheckpointStore)({
279 listAuthoredPaths: () => Effect.succeed(null),
280 isGitRepository: () => Effect.succeed(true),
281 captureCheckpoint: () => Effect.void,
282 hasCheckpointRef: () =>
283 Effect.fail(
284 new VcsProcessTimeoutError({
285 operation: "test.hasCheckpointRef",
286 command: "git",
287 cwd: "/repo",
288 timeoutMs: 30000,
289 }),
290 ),
291 }),
292 ),
293 ),
294 )
295 : Layer.mock(CheckpointService.CheckpointServiceV2)({
296 materializeBaselineCheckpoint: () =>
297 Effect.die(
298 "baseline materialization must be skipped when ordinal 0 is ready",
299 ),
300 capture: () => Effect.succeed(captured),
301 }),
302 Layer.mock(EventSink.EventSinkV2)({
303 commitCommand: (input) =>
304 Ref.set(committed, input.events).pipe(
305 Effect.as({
306 commandId: input.commandId,
307 committed: true,
308 sequence: 1,
309 events: input.events,
310 effects: [],
311 } as never),
312 ),
313 }),
314 ),
315 ),
316 );
317
318 yield* Effect.gen(function* () {
319 const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2;
320 const incomplete = yield* service
321 .execute({ threadId, runId, scopeId: CheckpointScopeId.make("missing-scope") })
322 .pipe(Effect.flip);
323 assert.instanceOf(incomplete, CheckpointCaptureService.CheckpointCaptureExecutionError);
324 yield* service.execute({ threadId, runId, scopeId });
325
326 const events = yield* Ref.get(committed);
327 const runUpdated = events.find((event) => event.type === "run.updated");
328 assert.isDefined(runUpdated);
329 if (runUpdated?.type !== "run.updated") {
330 return;
331 }
332 assert.equal(runUpdated.payload.status, "completed");
333 const capturedEvent = events.find((event) => event.type === "checkpoint.captured");
334 assert.equal(
335 runUpdated.payload.checkpointId,
336 refLookupFails ? capturedEvent?.payload.id : captured.id,
337 );
338 if (refLookupFails && capturedEvent?.type === "checkpoint.captured") {
339 assert.equal(capturedEvent.payload.status, "ready");
340 assert.deepEqual(capturedEvent.payload.files, []);
341 }
342 assert.isUndefined(
343 runUpdated.payload.delegatedCompletion,
344 "checkpoint capture must omit delegatedCompletion so ProjectionStore can keep a newer cohort",
345 );
346
347 yield* projectionStore.apply({
348 id: EventId.make("event:checkpoint-capture:newer-cohort"),
349 type: "run.updated",
350 threadId,
351 runId,
352 nodeId: rootNodeId,
353 providerInstanceId,
354 occurredAt: later,
355 payload: {
356 ...staleRun,
357 delegatedCompletion: newerCohort,
358 },
359 });
360
361 yield* projectionStore.apply(runUpdated);
362
363 const projectedRun = (yield* projectionStore.getCheckpointCaptureContext(threadId, {
364 runId,
365 scopeId,
366 })).run;
367 assert.isDefined(projectedRun);
368 assert.equal(projectedRun?.status, "completed");
369 assert.equal(projectedRun?.checkpointId, runUpdated.payload.checkpointId);
370 assert.deepEqual(projectedRun?.delegatedCompletion, newerCohort);
371 assert.equal(projectedRun?.delegatedCompletion?.delivery?.messageId, deliveryMessageId);
372 assert.deepEqual(projectedRun?.delegatedCompletion?.delivery?.taskIds, [taskId]);
373 yield* Ref.set(committed, []);
374 yield* service.execute({ threadId, runId, scopeId });
375 assert.deepEqual(yield* Ref.get(committed), []);
376 }).pipe(Effect.provide(layerCapture));
377 }),
378 );
379
380 it.effect("does not capture a stopped run that a rollback already discarded", () =>
381 Effect.gen(function* () {
382 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
383 const now = yield* DateTime.now;
384 const stoppedThreadId = ThreadId.make("thread:checkpoint-capture-rolled-back");
385 const stoppedRunId = RunId.make("run:checkpoint-capture-rolled-back");
386 yield* projectionStore.apply({
387 id: EventId.make("event:checkpoint-capture-rolled-back:thread"),
388 type: "thread.created",
389 threadId: stoppedThreadId,
390 occurredAt: now,
391 payload: {
392 createdBy: "user",
393 creationSource: "web",
394 id: stoppedThreadId,
395 projectId,
396 title: "Checkpoint capture after rollback",
397 providerInstanceId,
398 modelSelection,
399 runtimeMode: "full-access",
400 interactionMode: "default",
401 branch: null,
402 worktreePath: null,
403 activeProviderThreadId: null,
404 lineage: {
405 parentThreadId: null,
406 relationshipToParent: null,
407 rootThreadId: stoppedThreadId,
408 },
409 forkedFrom: null,
410 createdAt: now,
411 updatedAt: now,
412 archivedAt: null,
413 settledOverride: null,
414 settledAt: null,
415 lastVisitedAt: null,
416 deletedAt: null,
417 },
418 });
419 const stoppedRun: OrchestrationV2Run = {
420 id: stoppedRunId,
421 threadId: stoppedThreadId,
422 ordinal: 2,
423 providerInstanceId,
424 modelSelection,
425 providerThreadId,
426 userMessageId: MessageId.make("message:checkpoint-capture-rolled-back"),
427 rootNodeId,
428 activeAttemptId: null,
429 status: "interrupted",
430 requestedAt: now,
431 startedAt: now,
432 completedAt: now,
433 checkpointId: null,
434 contextHandoffId: null,
435 };
436 yield* projectionStore.apply({
437 id: EventId.make("event:checkpoint-capture-rolled-back:run"),
438 type: "run.updated",
439 threadId: stoppedThreadId,
440 runId: stoppedRunId,
441 providerInstanceId,
442 occurredAt: now,
443 payload: { ...stoppedRun, status: "rolled_back" },
444 });
445
446 const committed = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
447 const layerCapture = CheckpointCaptureService.layer.pipe(
448 Layer.provide(
449 Layer.mergeAll(
450 IdAllocator.layer,
451 Layer.mock(CheckpointService.CheckpointServiceV2)({
452 materializeBaselineCheckpoint: () => Effect.die("a discarded run has no baseline"),
453 capture: () => Effect.die("a discarded run must not be captured"),
454 }),
455 Layer.mock(EventSink.EventSinkV2)({
456 commitCommand: (input) =>
457 Ref.set(committed, input.events).pipe(Effect.as({ committed: true } as never)),
458 }),
459 ),
460 ),
461 );
462
463 yield* CheckpointCaptureService.CheckpointCaptureServiceV2.pipe(
464 Effect.flatMap((service) =>
465 service.execute({ threadId: stoppedThreadId, runId: stoppedRunId, scopeId }),
466 ),
467 Effect.provide(layerCapture),
468 );
469
470 assert.deepEqual(yield* Ref.get(committed), []);
471 const projected = yield* projectionStore.getCheckpointCaptureContext(stoppedThreadId, {
472 runId: stoppedRunId,
473 scopeId,
474 });
475 assert.equal(projected.run?.status, "rolled_back");
476 assert.isNull(projected.run?.checkpointId ?? null);
477 }),
478 );
479
480 it.effect("records the checkpoint of a cancelled run and keeps it cancelled", () =>
481 Effect.gen(function* () {
482 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
483 const now = yield* DateTime.now;
484 const cancelledAt = DateTime.add(now, { seconds: 1 });
485 const cancelledThreadId = ThreadId.make("thread:checkpoint-capture-cancelled");
486 const cancelledRunId = RunId.make("run:checkpoint-capture-cancelled");
487 const cancelledScopeId = CheckpointScopeId.make("scope:checkpoint-capture-cancelled");
488 const cancelledRootNodeId = NodeId.make("node:checkpoint-capture-cancelled-root");
489 const cancelledProviderThreadId = ProviderThreadId.make(
490 "provider-thread:checkpoint-capture-cancelled",
491 );
492 yield* projectionStore.apply({
493 id: EventId.make("event:checkpoint-capture-cancelled:thread"),
494 type: "thread.created",
495 threadId: cancelledThreadId,
496 occurredAt: now,
497 payload: {
498 createdBy: "user",
499 creationSource: "web",
500 id: cancelledThreadId,
501 projectId,
502 title: "Checkpoint capture after cancel",
503 providerInstanceId,
504 modelSelection,
505 runtimeMode: "full-access",
506 interactionMode: "default",
507 branch: null,
508 worktreePath: null,
509 activeProviderThreadId: null,
510 lineage: {
511 parentThreadId: null,
512 relationshipToParent: null,
513 rootThreadId: cancelledThreadId,
514 },
515 forkedFrom: null,
516 createdAt: now,
517 updatedAt: now,
518 archivedAt: null,
519 settledOverride: null,
520 settledAt: null,
521 lastVisitedAt: null,
522 deletedAt: null,
523 },
524 });
525 const runningRun: OrchestrationV2Run = {
526 id: cancelledRunId,
527 threadId: cancelledThreadId,
528 ordinal: 1,
529 providerInstanceId,
530 modelSelection,
531 providerThreadId: cancelledProviderThreadId,
532 userMessageId: MessageId.make("message:checkpoint-capture-cancelled"),
533 rootNodeId: cancelledRootNodeId,
534 activeAttemptId: null,
535 status: "running",
536 requestedAt: now,
537 startedAt: now,
538 completedAt: null,
539 checkpointId: null,
540 contextHandoffId: null,
541 };
542 const runningRootNode = {
543 id: cancelledRootNodeId,
544 threadId: cancelledThreadId,
545 runId: cancelledRunId,
546 parentNodeId: null,
547 rootNodeId: cancelledRootNodeId,
548 kind: "root_turn" as const,
549 status: "running" as const,
550 countsForRun: true,
551 providerThreadId: cancelledProviderThreadId,
552 providerTurnId: null,
553 nativeItemRef: null,
554 runtimeRequestId: null,
555 checkpointScopeId: cancelledScopeId,
556 startedAt: now,
557 completedAt: null,
558 };
559 const scope = {
560 id: cancelledScopeId,
561 threadId: cancelledThreadId,
562 runId: cancelledRunId,
563 nodeId: cancelledRootNodeId,
564 parentScopeId: null,
565 providerThreadId: cancelledProviderThreadId,
566 kind: "root_run" as const,
567 ordinalWithinParent: 0,
568 advancesAppRunCount: true,
569 cwd: "/repo",
570 createdAt: now,
571 };
572 yield* projectionStore.apply({
573 id: EventId.make("event:checkpoint-capture-cancelled:provider-thread"),
574 type: "provider-thread.updated",
575 threadId: cancelledThreadId,
576 nodeId: cancelledRootNodeId,
577 driver,
578 providerInstanceId,
579 occurredAt: now,
580 payload: {
581 id: cancelledProviderThreadId,
582 driver,
583 providerInstanceId,
584 providerSessionId: null,
585 appThreadId: cancelledThreadId,
586 ownerNodeId: cancelledRootNodeId,
587 nativeThreadRef: null,
588 nativeConversationHeadRef: null,
589 status: "idle",
590 firstRunOrdinal: 1,
591 lastRunOrdinal: 1,
592 handoffIds: [],
593 forkedFrom: null,
594 createdAt: now,
595 updatedAt: now,
596 },
597 });
598 yield* projectionStore.apply({
599 id: EventId.make("event:checkpoint-capture-cancelled:scope"),
600 type: "checkpoint-scope.created",
601 threadId: cancelledThreadId,
602 runId: cancelledRunId,
603 nodeId: cancelledRootNodeId,
604 occurredAt: now,
605 payload: scope,
606 });
607 yield* projectionStore.apply({
608 id: EventId.make("event:checkpoint-capture-cancelled:baseline"),
609 type: "checkpoint.captured",
610 threadId: cancelledThreadId,
611 nodeId: cancelledRootNodeId,
612 driver,
613 providerInstanceId,
614 occurredAt: now,
615 payload: {
616 id: CheckpointId.make("checkpoint:cancelled-baseline-0"),
617 threadId: cancelledThreadId,
618 scopeId: cancelledScopeId,
619 runId: null,
620 nodeId: cancelledRootNodeId,
621 parentCheckpointId: null,
622 ordinalWithinScope: 0,
623 appRunOrdinal: null,
624 ref: CheckpointRef.make("checkpoint-ref:cancelled-baseline-0"),
625 status: "ready",
626 files: [],
627 capturedAt: now,
628 },
629 });
630 for (const [status, completedAt] of [
631 ["running", null],
632 ["cancelled", cancelledAt],
633 ] as const) {
634 yield* projectionStore.apply({
635 id: EventId.make(`event:checkpoint-capture-cancelled:run-${status}`),
636 type: "run.updated",
637 threadId: cancelledThreadId,
638 runId: cancelledRunId,
639 nodeId: cancelledRootNodeId,
640 providerInstanceId,
641 occurredAt: completedAt ?? now,
642 payload: { ...runningRun, status, completedAt },
643 });
644 yield* projectionStore.apply({
645 id: EventId.make(`event:checkpoint-capture-cancelled:node-${status}`),
646 type: "node.updated",
647 threadId: cancelledThreadId,
648 runId: cancelledRunId,
649 nodeId: cancelledRootNodeId,
650 providerInstanceId,
651 occurredAt: completedAt ?? now,
652 payload: { ...runningRootNode, status, completedAt },
653 });
654 }
655
656 const captured = {
657 id: CheckpointId.make("checkpoint:cancelled-captured-1"),
658 threadId: cancelledThreadId,
659 scopeId: cancelledScopeId,
660 runId: cancelledRunId,
661 nodeId: cancelledRootNodeId,
662 parentCheckpointId: CheckpointId.make("checkpoint:cancelled-baseline-0"),
663 ordinalWithinScope: 1,
664 appRunOrdinal: 1,
665 ref: CheckpointRef.make("checkpoint-ref:cancelled-captured-1"),
666 status: "ready" as const,
667 files: [],
668 capturedAt: cancelledAt,
669 };
670 const commits = yield* Ref.make(0);
671 const layerCapture = CheckpointCaptureService.layer.pipe(
672 Layer.provide(
673 Layer.mergeAll(
674 IdAllocator.layer,
675 Layer.mock(CheckpointService.CheckpointServiceV2)({
676 materializeBaselineCheckpoint: () =>
677 Effect.die("baseline materialization must be skipped when ordinal 0 is ready"),
678 capture: () => Effect.succeed(captured),
679 }),
680 Layer.mock(EventSink.EventSinkV2)({
681 commitCommand: (input) =>
682 Effect.forEach(input.events, (event) => projectionStore.apply(event)).pipe(
683 Effect.andThen(Ref.update(commits, (count) => count + 1)),
684 Effect.as({ committed: true } as never),
685 Effect.orDie,
686 ),
687 }),
688 ),
689 ),
690 );
691
692 yield* Effect.gen(function* () {
693 const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2;
694 yield* service.execute({
695 threadId: cancelledThreadId,
696 runId: cancelledRunId,
697 scopeId: cancelledScopeId,
698 });
699 yield* service.execute({
700 threadId: cancelledThreadId,
701 runId: cancelledRunId,
702 scopeId: cancelledScopeId,
703 });
704 }).pipe(Effect.provide(layerCapture));
705
706 assert.equal(yield* Ref.get(commits), 1);
707 const projected = yield* projectionStore.getCheckpointCaptureContext(cancelledThreadId, {
708 runId: cancelledRunId,
709 scopeId: cancelledScopeId,
710 });
711 assert.equal(projected.run?.status, "cancelled");
712 assert.equal(projected.run?.checkpointId, captured.id);
713 const completedAt = projected.run?.completedAt;
714 assert.equal(
715 completedAt ? DateTime.formatIso(completedAt) : completedAt,
716 DateTime.formatIso(cancelledAt),
717 );
718 assert.equal(projected.rootNode?.status, "cancelled");
719 assert.deepEqual([...projected.readyCheckpointOrdinals].toSorted(), [0, 1]);
720 }),
721 );
722
723 it.effect("completes a side chat run with a missing checkpoint and never touches git", () =>
724 Effect.gen(function* () {
725 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
726 const now = yield* DateTime.now;
727 const sideChatThreadId = ThreadId.make("thread:checkpoint-capture-side-chat");
728 const sideChatRunId = RunId.make("run:checkpoint-capture-side-chat");
729 const sideChatScopeId = CheckpointScopeId.make("scope:checkpoint-capture-side-chat");
730 const sideChatRootNodeId = NodeId.make("node:checkpoint-capture-side-chat-root");
731 const sideChatProviderThreadId = ProviderThreadId.make(
732 "provider-thread:checkpoint-capture-side-chat",
733 );
734 const event = { threadId: sideChatThreadId, occurredAt: now };
735 const events: ReadonlyArray<OrchestrationV2DomainEvent> = [
736 {
737 ...event,
738 id: EventId.make("event:checkpoint-capture-side-chat:thread"),
739 type: "thread.created",
740 payload: {
741 createdBy: "user",
742 creationSource: "web",
743 id: sideChatThreadId,
744 projectId,
745 title: "Side chat",
746 providerInstanceId,
747 modelSelection,
748 runtimeMode: "approval-required",
749 interactionMode: "default",
750 branch: null,
751 worktreePath: "/repo",
752 activeProviderThreadId: null,
753 lineage: {
754 parentThreadId: threadId,
755 relationshipToParent: "fork",
756 rootThreadId: threadId,
757 sideChat: true,
758 },
759 forkedFrom: null,
760 createdAt: now,
761 updatedAt: now,
762 archivedAt: null,
763 settledOverride: null,
764 settledAt: null,
765 lastVisitedAt: null,
766 deletedAt: null,
767 },
768 },
769 {
770 ...event,
771 id: EventId.make("event:checkpoint-capture-side-chat:provider-thread"),
772 type: "provider-thread.updated",
773 driver,
774 providerInstanceId,
775 payload: {
776 id: sideChatProviderThreadId,
777 driver,
778 providerInstanceId,
779 providerSessionId: null,
780 appThreadId: sideChatThreadId,
781 ownerNodeId: null,
782 nativeThreadRef: null,
783 nativeConversationHeadRef: null,
784 status: "idle",
785 firstRunOrdinal: 1,
786 lastRunOrdinal: 1,
787 handoffIds: [],
788 forkedFrom: null,
789 createdAt: now,
790 updatedAt: now,
791 },
792 },
793 {
794 ...event,
795 id: EventId.make("event:checkpoint-capture-side-chat:run"),
796 type: "run.updated",
797 runId: sideChatRunId,
798 payload: {
799 id: sideChatRunId,
800 threadId: sideChatThreadId,
801 ordinal: 1,
802 providerInstanceId,
803 modelSelection,
804 providerThreadId: sideChatProviderThreadId,
805 userMessageId: MessageId.make("message:checkpoint-capture-side-chat"),
806 rootNodeId: sideChatRootNodeId,
807 activeAttemptId: null,
808 status: "waiting",
809 requestedAt: now,
810 startedAt: now,
811 completedAt: null,
812 checkpointId: null,
813 contextHandoffId: null,
814 },
815 },
816 {
817 ...event,
818 id: EventId.make("event:checkpoint-capture-side-chat:node"),
819 type: "node.updated",
820 runId: sideChatRunId,
821 nodeId: sideChatRootNodeId,
822 payload: {
823 id: sideChatRootNodeId,
824 threadId: sideChatThreadId,
825 runId: sideChatRunId,
826 parentNodeId: null,
827 rootNodeId: sideChatRootNodeId,
828 kind: "root_turn",
829 status: "waiting",
830 countsForRun: true,
831 providerThreadId: sideChatProviderThreadId,
832 providerTurnId: null,
833 nativeItemRef: null,
834 runtimeRequestId: null,
835 checkpointScopeId: sideChatScopeId,
836 startedAt: now,
837 completedAt: null,
838 },
839 },
840 {
841 ...event,
842 id: EventId.make("event:checkpoint-capture-side-chat:scope"),
843 type: "checkpoint-scope.created",
844 runId: sideChatRunId,
845 nodeId: sideChatRootNodeId,
846 payload: {
847 id: sideChatScopeId,
848 threadId: sideChatThreadId,
849 runId: sideChatRunId,
850 nodeId: sideChatRootNodeId,
851 parentScopeId: null,
852 providerThreadId: sideChatProviderThreadId,
853 kind: "root_run",
854 ordinalWithinParent: 0,
855 advancesAppRunCount: true,
856 cwd: "/repo",
857 createdAt: now,
858 },
859 },
860 ];
861 yield* Effect.forEach(events, (candidate) => projectionStore.apply(candidate));
862 const gitUnavailable = () => Effect.die("side chats must not snapshot the shared worktree");
863 const layerCapture = CheckpointCaptureService.layer.pipe(
864 Layer.provide(
865 Layer.mergeAll(
866 IdAllocator.layer,
867 CheckpointService.layer.pipe(
868 Layer.provide(
869 Layer.mergeAll(
870 IdAllocator.layer,
871 NodeCrypto.layer,
872 Layer.mock(CheckpointStore.CheckpointStore)({
873 isGitRepository: gitUnavailable,
874 captureCheckpoint: gitUnavailable,
875 hasCheckpointRef: gitUnavailable,
876 }),
877 ),
878 ),
879 ),
880 Layer.mock(EventSink.EventSinkV2)({
881 commitCommand: (input) =>
882 Effect.forEach(input.events, (committed) => projectionStore.apply(committed)).pipe(
883 Effect.as({ committed: true } as never),
884 Effect.orDie,
885 ),
886 }),
887 ),
888 ),
889 );
890
891 yield* CheckpointCaptureService.CheckpointCaptureServiceV2.use((service) =>
892 service.execute({
893 threadId: sideChatThreadId,
894 runId: sideChatRunId,
895 scopeId: sideChatScopeId,
896 }),
897 ).pipe(Effect.provide(layerCapture));
898
899 const { checkpoints, runs } = yield* projectionStore.getThreadRecords(sideChatThreadId, [
900 "runs",
901 "checkpoints",
902 ]);
903 assert.equal(runs[0]?.status, "completed");
904 const checkpoint = checkpoints.find((candidate) => candidate.id === runs[0]?.checkpointId);
905 assert.equal(checkpoint?.status, "missing");
906 }),
907 );
908});