Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointRef,
4 CheckpointScopeId,
5 NodeId,
6 OrchestrationV2Checkpoint,
7 OrchestrationV2CheckpointScope,
8 ProviderThreadId,
9 RunId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as Digest from "effect/crypto/Digest";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Base64Url from "effect/encoding/Base64Url";
17import * as Hex from "effect/encoding/Hex";
18import * as KeyedLock from "@t3tools/shared/KeyedLock";
19import * as Layer from "effect/Layer";
20import * as Schema from "effect/Schema";
21
22import { isGitImport, parseTurnDiffFilesFromNumstat } from "../checkpointing/Diffs.ts";
23import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
24import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
25
26const CHECKPOINT_REFS_PREFIX = "refs/t3/orchestration-v2/checkpoints";
27const ROOT_CHECKPOINT_SCOPE_NAME = "root";
28
29export class CheckpointRootScopePrepareError extends Schema.TaggedError<CheckpointRootScopePrepareError>()(
30 "CheckpointRootScopePrepareError",
31 {
32 threadId: ThreadId,
33 runId: RunId,
34 cause: Schema.Defect(),
35 },
36) {
37 override get message(): string {
38 return `Failed to prepare root checkpoint scope for run ${this.runId}.`;
39 }
40}
41
42export class CheckpointBaselineCaptureError extends Schema.TaggedError<CheckpointBaselineCaptureError>()(
43 "CheckpointBaselineCaptureError",
44 {
45 scopeId: CheckpointScopeId,
46 ordinalWithinScope: Schema.Number,
47 cause: Schema.Defect(),
48 },
49) {
50 override get message(): string {
51 return `Failed to capture checkpoint baseline ${this.ordinalWithinScope} for scope ${this.scopeId}.`;
52 }
53}
54
55export class CheckpointCaptureError extends Schema.TaggedError<CheckpointCaptureError>()(
56 "CheckpointCaptureError",
57 {
58 scopeId: CheckpointScopeId,
59 parentCheckpointId: Schema.optional(CheckpointId),
60 cause: Schema.Defect(),
61 },
62) {
63 override get message(): string {
64 return `Failed to capture checkpoint for scope ${this.scopeId}.`;
65 }
66}
67
68export class CheckpointRestoreError extends Schema.TaggedError<CheckpointRestoreError>()(
69 "CheckpointRestoreError",
70 {
71 scopeId: CheckpointScopeId,
72 checkpointId: CheckpointId,
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return `Failed to restore checkpoint ${this.checkpointId} for scope ${this.scopeId}.`;
78 }
79}
80
81export class CheckpointDeleteStaleRefsError extends Schema.TaggedError<CheckpointDeleteStaleRefsError>()(
82 "CheckpointDeleteStaleRefsError",
83 {
84 scopeId: CheckpointScopeId,
85 checkpointIds: Schema.Array(CheckpointId),
86 cause: Schema.Defect(),
87 },
88) {
89 override get message(): string {
90 return `Failed to delete stale checkpoint refs for scope ${this.scopeId}.`;
91 }
92}
93
94export const CheckpointServiceV2Error = Schema.Union([
95 CheckpointRootScopePrepareError,
96 CheckpointBaselineCaptureError,
97 CheckpointCaptureError,
98 CheckpointRestoreError,
99 CheckpointDeleteStaleRefsError,
100]);
101export type CheckpointServiceV2Error = typeof CheckpointServiceV2Error.Type;
102
103const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
104
105export interface CheckpointServiceV2Shape {
106 readonly prepareRootRunScope: (input: {
107 readonly threadId: ThreadId;
108 readonly runId: RunId;
109 readonly rootNodeId: NodeId;
110 readonly providerThreadId: ProviderThreadId;
111 readonly cwd: string;
112 readonly createdAt: DateTime.Utc;
113 }) => Effect.Effect<OrchestrationV2CheckpointScope, CheckpointServiceV2Error>;
114 readonly captureBaseline: (input: {
115 readonly scope: OrchestrationV2CheckpointScope;
116 readonly ordinalWithinScope: number;
117 }) => Effect.Effect<void, CheckpointServiceV2Error>;
118 readonly materializeBaselineCheckpoint: (input: {
119 readonly scope: OrchestrationV2CheckpointScope;
120 readonly ordinalWithinScope: number;
121 /** Records a missing checkpoint without touching git, for side chats sharing a parent's worktree. */
122 readonly forceMissing?: boolean;
123 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
124 readonly capture: (input: {
125 readonly scope: OrchestrationV2CheckpointScope;
126 readonly runId: RunId | null;
127 readonly nodeId: NodeId;
128 readonly ordinalWithinScope: number;
129 readonly appRunOrdinal: number | null;
130 readonly capturedAt: DateTime.Utc;
131 readonly forceMissing?: boolean;
132 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
133 readonly restore: (input: {
134 readonly scope: OrchestrationV2CheckpointScope;
135 readonly checkpoint: OrchestrationV2Checkpoint;
136 }) => Effect.Effect<void, CheckpointServiceV2Error>;
137 readonly deleteStaleRefs: (input: {
138 readonly scope: OrchestrationV2CheckpointScope;
139 readonly checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>;
140 }) => Effect.Effect<void, CheckpointServiceV2Error>;
141}
142
143export class CheckpointServiceV2 extends Context.Service<
144 CheckpointServiceV2,
145 CheckpointServiceV2Shape
146>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
147
148export const checkpointRefForScopeOrdinal = Effect.fn("checkpointRefForScopeOrdinal")(
149 function* (input: { readonly scopeId: CheckpointScopeId; readonly ordinalWithinScope: number }) {
150 const crypto = yield* Digest.Digest;
151 const digest = yield* crypto
152 .digest(Digest.sha256, new TextEncoder().encode(input.scopeId))
153 .pipe(Effect.orDie);
154 const scopeKey = Hex.encode(digest).slice(0, 32);
155 return CheckpointRef.make(
156 `${CHECKPOINT_REFS_PREFIX}/${Base64Url.encode(scopeKey)}/ordinal/${input.ordinalWithinScope}`,
157 );
158 },
159);
160
161function checkpointIdForScopeOrdinal(
162 idAllocator: IdAllocator.IdAllocatorV2["Service"],
163 input: {
164 readonly scopeId: CheckpointScopeId;
165 readonly ordinalWithinScope: number;
166 },
167) {
168 return idAllocator.allocate.checkpoint({
169 checkpointScopeId: input.scopeId,
170 name: String(input.ordinalWithinScope),
171 });
172}
173
174const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: {
175 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
176 readonly threadId: ThreadId;
177 readonly runId: RunId;
178 readonly rootNodeId: NodeId;
179 readonly providerThreadId: ProviderThreadId;
180 readonly cwd: string;
181 readonly createdAt: DateTime.Utc;
182}) {
183 const scopeId = yield* input.idAllocator.allocate.checkpointScope({
184 threadId: input.threadId,
185 name: ROOT_CHECKPOINT_SCOPE_NAME,
186 });
187 return {
188 id: scopeId,
189 threadId: input.threadId,
190 runId: input.runId,
191 nodeId: input.rootNodeId,
192 parentScopeId: null,
193 providerThreadId: input.providerThreadId,
194 kind: "root_run",
195 ordinalWithinParent: 0,
196 advancesAppRunCount: true,
197 cwd: input.cwd,
198 createdAt: input.createdAt,
199 } satisfies OrchestrationV2CheckpointScope;
200});
201
202function makeCheckpoint(input: {
203 readonly id: CheckpointId;
204 readonly scope: OrchestrationV2CheckpointScope;
205 readonly runId: RunId | null;
206 readonly nodeId: NodeId;
207 readonly parentCheckpointId: CheckpointId | null;
208 readonly ordinalWithinScope: number;
209 readonly appRunOrdinal: number | null;
210 readonly ref: CheckpointRef;
211 readonly status: OrchestrationV2Checkpoint["status"];
212 readonly files: OrchestrationV2Checkpoint["files"];
213 readonly capturedAt: DateTime.Utc;
214}): OrchestrationV2Checkpoint {
215 return {
216 id: input.id,
217 threadId: input.scope.threadId,
218 scopeId: input.scope.id,
219 runId: input.runId,
220 nodeId: input.nodeId,
221 parentCheckpointId: input.parentCheckpointId,
222 ordinalWithinScope: input.ordinalWithinScope,
223 appRunOrdinal: input.appRunOrdinal,
224 ref: input.ref,
225 status: input.status,
226 files: input.files,
227 capturedAt: input.capturedAt,
228 };
229}
230
231export const layer: Layer.Layer<
232 CheckpointServiceV2,
233 never,
234 CheckpointStore.CheckpointStore | Digest.Digest | IdAllocator.IdAllocatorV2
235> = Layer.effect(
236 CheckpointServiceV2,
237 Effect.gen(function* () {
238 const checkpointStore = yield* CheckpointStore.CheckpointStore;
239 const crypto = yield* Digest.Digest;
240 const checkpointRefFor = (input: Parameters<typeof checkpointRefForScopeOrdinal>[0]) =>
241 checkpointRefForScopeOrdinal(input).pipe(Effect.provideService(Digest.Digest, crypto));
242 const idAllocator = yield* IdAllocator.IdAllocatorV2;
243 const workspaceLocks = yield* KeyedLock.make<string>();
244 const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
245 workspaceLocks.withLock(cwd, effect);
246
247 const isGitCheckpointable = (cwd: string) =>
248 checkpointStore.isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false));
249
250 const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = (input) =>
251 withWorkspaceLock(
252 input.scope.cwd,
253 Effect.gen(function* () {
254 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
255 return;
256 }
257
258 const checkpointRef = yield* checkpointRefFor({
259 scopeId: input.scope.id,
260 ordinalWithinScope: input.ordinalWithinScope,
261 });
262 const exists = yield* checkpointStore.hasCheckpointRef({
263 cwd: input.scope.cwd,
264 checkpointRef,
265 });
266 if (exists) {
267 return;
268 }
269
270 yield* checkpointStore
271 .captureCheckpoint({
272 cwd: input.scope.cwd,
273 checkpointRef,
274 })
275 .pipe(
276 Effect.catchTags({
277 VcsUnsupportedOperationError: () => Effect.void,
278 }),
279 );
280 }),
281 ).pipe(
282 Effect.mapError(
283 (cause) =>
284 new CheckpointBaselineCaptureError({
285 scopeId: input.scope.id,
286 ordinalWithinScope: input.ordinalWithinScope,
287 cause,
288 }),
289 ),
290 );
291
292 const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
293 (input) =>
294 withWorkspaceLock(
295 input.scope.cwd,
296 Effect.gen(function* () {
297 const checkpointRef = yield* checkpointRefFor({
298 scopeId: input.scope.id,
299 ordinalWithinScope: input.ordinalWithinScope,
300 });
301 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
302 scopeId: input.scope.id,
303 ordinalWithinScope: input.ordinalWithinScope,
304 });
305 const checkpointable =
306 input.forceMissing !== true && (yield* isGitCheckpointable(input.scope.cwd));
307 const available = checkpointable
308 ? yield* checkpointStore
309 .hasCheckpointRef({
310 cwd: input.scope.cwd,
311 checkpointRef,
312 })
313 .pipe(
314 Effect.catch((cause) =>
315 Effect.logWarning("orchestration V2 baseline ref lookup failed", {
316 scopeId: input.scope.id,
317 checkpointRef,
318 cause: String(cause),
319 }).pipe(Effect.as(false)),
320 ),
321 )
322 : false;
323 return makeCheckpoint({
324 id: checkpointId,
325 scope: input.scope,
326 runId: null,
327 nodeId: input.scope.nodeId,
328 parentCheckpointId: null,
329 ordinalWithinScope: input.ordinalWithinScope,
330 appRunOrdinal: null,
331 ref: checkpointRef,
332 status: available ? "ready" : "missing",
333 files: [],
334 capturedAt: input.scope.createdAt,
335 });
336 }),
337 ).pipe(
338 Effect.mapError(
339 (cause) =>
340 new CheckpointCaptureError({
341 scopeId: input.scope.id,
342 cause,
343 }),
344 ),
345 );
346
347 const capture: CheckpointServiceV2Shape["capture"] = (input) =>
348 withWorkspaceLock(
349 input.scope.cwd,
350 Effect.gen(function* () {
351 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
352 scopeId: input.scope.id,
353 ordinalWithinScope: input.ordinalWithinScope,
354 });
355 const parentCheckpointId =
356 input.ordinalWithinScope > 0
357 ? yield* checkpointIdForScopeOrdinal(idAllocator, {
358 scopeId: input.scope.id,
359 ordinalWithinScope: input.ordinalWithinScope - 1,
360 })
361 : null;
362 const checkpointRef = yield* checkpointRefFor({
363 scopeId: input.scope.id,
364 ordinalWithinScope: input.ordinalWithinScope,
365 });
366 const previousCheckpointRef = yield* checkpointRefFor({
367 scopeId: input.scope.id,
368 ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
369 });
370
371 if (input.forceMissing === true || !(yield* isGitCheckpointable(input.scope.cwd))) {
372 return makeCheckpoint({
373 id: checkpointId,
374 scope: input.scope,
375 runId: input.runId,
376 nodeId: input.nodeId,
377 parentCheckpointId,
378 ordinalWithinScope: input.ordinalWithinScope,
379 appRunOrdinal: input.appRunOrdinal,
380 ref: checkpointRef,
381 status: "missing",
382 files: [],
383 capturedAt: input.capturedAt,
384 });
385 }
386
387 const captureStatus = yield* checkpointStore
388 .captureCheckpoint({
389 cwd: input.scope.cwd,
390 checkpointRef,
391 })
392 .pipe(
393 Effect.as("ready" as const),
394 Effect.catchTags({
395 VcsUnsupportedOperationError: () => Effect.succeed("missing" as const),
396 }),
397 Effect.catch((cause) =>
398 Effect.logWarning("orchestration V2 checkpoint capture failed", {
399 scopeId: input.scope.id,
400 checkpointRef,
401 cause: String(cause),
402 }).pipe(Effect.as("error" as const)),
403 ),
404 );
405
406 if (captureStatus !== "ready") {
407 return makeCheckpoint({
408 id: checkpointId,
409 scope: input.scope,
410 runId: input.runId,
411 nodeId: input.nodeId,
412 parentCheckpointId,
413 ordinalWithinScope: input.ordinalWithinScope,
414 appRunOrdinal: input.appRunOrdinal,
415 ref: checkpointRef,
416 status: captureStatus,
417 files: [],
418 capturedAt: input.capturedAt,
419 });
420 }
421
422 const previousExists = yield* checkpointStore
423 .hasCheckpointRef({
424 cwd: input.scope.cwd,
425 checkpointRef: previousCheckpointRef,
426 })
427 .pipe(
428 Effect.catch((cause) =>
429 Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", {
430 scopeId: input.scope.id,
431 checkpointRef: previousCheckpointRef,
432 cause: String(cause),
433 }).pipe(Effect.as(false)),
434 ),
435 );
436 const refs = {
437 cwd: input.scope.cwd,
438 fromCheckpointRef: previousCheckpointRef,
439 toCheckpointRef: checkpointRef,
440 };
441 // A pull or rebase can change thousands of files the turn did not write.
442 const files = previousExists
443 ? yield* Effect.all([
444 checkpointStore.diffCheckpoints({
445 ...refs,
446 fallbackFromToHead: false,
447 ignoreWhitespace: false,
448 format: "numstat",
449 }),
450 checkpointStore.listAuthoredPaths(refs).pipe(
451 Effect.catch((cause) =>
452 Effect.logWarning("orchestration V2 checkpoint authored paths failed", {
453 scopeId: input.scope.id,
454 checkpointRef,
455 cause: String(cause),
456 }).pipe(Effect.as(null)),
457 ),
458 ),
459 ]).pipe(
460 Effect.map(([diff, authoredPaths]) =>
461 parseTurnDiffFilesFromNumstat(diff)
462 .filter((file) => !isGitImport(file, authoredPaths))
463 .map((file) => ({
464 path: file.path,
465 kind: "modified",
466 additions: file.additions,
467 deletions: file.deletions,
468 })),
469 ),
470 Effect.catch((cause) =>
471 Effect.logWarning("orchestration V2 checkpoint diff summary failed", {
472 scopeId: input.scope.id,
473 checkpointRef,
474 cause: String(cause),
475 }).pipe(Effect.as([])),
476 ),
477 )
478 : [];
479
480 return makeCheckpoint({
481 id: checkpointId,
482 scope: input.scope,
483 runId: input.runId,
484 nodeId: input.nodeId,
485 parentCheckpointId,
486 ordinalWithinScope: input.ordinalWithinScope,
487 appRunOrdinal: input.appRunOrdinal,
488 ref: checkpointRef,
489 status: "ready",
490 files,
491 capturedAt: input.capturedAt,
492 });
493 }),
494 ).pipe(
495 Effect.mapError(
496 (cause) =>
497 new CheckpointCaptureError({
498 scopeId: input.scope.id,
499 cause,
500 }),
501 ),
502 );
503
504 const restore: CheckpointServiceV2Shape["restore"] = (input) =>
505 withWorkspaceLock(
506 input.scope.cwd,
507 Effect.gen(function* () {
508 if (input.checkpoint.status !== "ready") {
509 return yield* new CheckpointRestoreError({
510 scopeId: input.scope.id,
511 checkpointId: input.checkpoint.id,
512 cause: `Checkpoint status is ${input.checkpoint.status}.`,
513 });
514 }
515
516 const restored = yield* checkpointStore.restoreCheckpoint({
517 cwd: input.scope.cwd,
518 checkpointRef: input.checkpoint.ref,
519 fallbackToHead: false,
520 });
521 if (!restored) {
522 return yield* new CheckpointRestoreError({
523 scopeId: input.scope.id,
524 checkpointId: input.checkpoint.id,
525 cause: "Checkpoint ref is unavailable.",
526 });
527 }
528 }),
529 ).pipe(
530 Effect.mapError((cause) =>
531 isCheckpointRestoreError(cause)
532 ? cause
533 : new CheckpointRestoreError({
534 scopeId: input.scope.id,
535 checkpointId: input.checkpoint.id,
536 cause,
537 }),
538 ),
539 );
540
541 const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) =>
542 withWorkspaceLock(
543 input.scope.cwd,
544 checkpointStore.deleteCheckpointRefs({
545 cwd: input.scope.cwd,
546 checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref),
547 }),
548 ).pipe(
549 Effect.mapError(
550 (cause) =>
551 new CheckpointDeleteStaleRefsError({
552 scopeId: input.scope.id,
553 checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id),
554 cause,
555 }),
556 ),
557 );
558
559 return CheckpointServiceV2.of({
560 prepareRootRunScope: (input) =>
561 makeRootRunScope({ ...input, idAllocator }).pipe(
562 Effect.mapError(
563 (cause) =>
564 new CheckpointRootScopePrepareError({
565 threadId: input.threadId,
566 runId: input.runId,
567 cause,
568 }),
569 ),
570 ),
571 captureBaseline,
572 materializeBaselineCheckpoint,
573 capture,
574 restore,
575 deleteStaleRefs,
576 } satisfies CheckpointServiceV2Shape);
577 }),
578);