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