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
187function makeRootRunScope(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 return Effect.gen(function* () {
197 const scopeId = yield* input.idAllocator.allocate.checkpointScope({
198 threadId: input.threadId,
199 name: ROOT_CHECKPOINT_SCOPE_NAME,
200 });
201 return {
202 id: scopeId,
203 threadId: input.threadId,
204 runId: input.runId,
205 nodeId: input.rootNodeId,
206 parentScopeId: null,
207 providerThreadId: input.providerThreadId,
208 kind: "root_run",
209 ordinalWithinParent: 0,
210 advancesAppRunCount: true,
211 cwd: input.cwd,
212 createdAt: input.createdAt,
213 } satisfies OrchestrationV2CheckpointScope;
214 });
215}
216
217function makeCheckpoint(input: {
218 readonly id: CheckpointId;
219 readonly scope: OrchestrationV2CheckpointScope;
220 readonly runId: RunId | null;
221 readonly nodeId: NodeId;
222 readonly parentCheckpointId: CheckpointId | null;
223 readonly ordinalWithinScope: number;
224 readonly appRunOrdinal: number | null;
225 readonly ref: CheckpointRef;
226 readonly status: OrchestrationV2Checkpoint["status"];
227 readonly files: OrchestrationV2Checkpoint["files"];
228 readonly capturedAt: DateTime.Utc;
229}): OrchestrationV2Checkpoint {
230 return {
231 id: input.id,
232 threadId: input.scope.threadId,
233 scopeId: input.scope.id,
234 runId: input.runId,
235 nodeId: input.nodeId,
236 parentCheckpointId: input.parentCheckpointId,
237 ordinalWithinScope: input.ordinalWithinScope,
238 appRunOrdinal: input.appRunOrdinal,
239 ref: input.ref,
240 status: input.status,
241 files: input.files,
242 capturedAt: input.capturedAt,
243 };
244}
245
246export const layer: Layer.Layer<
247 CheckpointServiceV2,
248 never,
249 CheckpointStore.CheckpointStore | Crypto.Crypto | IdAllocator.IdAllocatorV2
250> = Layer.effect(
251 CheckpointServiceV2,
252 Effect.gen(function* () {
253 const checkpointStore = yield* CheckpointStore.CheckpointStore;
254 const crypto = yield* Crypto.Crypto;
255 const checkpointRefFor = (input: Parameters<typeof checkpointRefForScopeOrdinal>[0]) =>
256 checkpointRefForScopeOrdinal(input).pipe(Effect.provideService(Crypto.Crypto, crypto));
257 const idAllocator = yield* IdAllocator.IdAllocatorV2;
258 const workspaceLocks = yield* KeyedLock.make<string>();
259 const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
260 workspaceLocks.withLock(cwd, effect);
261
262 const isGitCheckpointable = (cwd: string) =>
263 checkpointStore.isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false));
264
265 const ensureScope: CheckpointServiceV2Shape["ensureScope"] = (scope) => Effect.succeed(scope);
266
267 const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = (input) =>
268 withWorkspaceLock(
269 input.scope.cwd,
270 Effect.gen(function* () {
271 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
272 return;
273 }
274
275 const checkpointRef = yield* checkpointRefFor({
276 scopeId: input.scope.id,
277 ordinalWithinScope: input.ordinalWithinScope,
278 });
279 const exists = yield* checkpointStore.hasCheckpointRef({
280 cwd: input.scope.cwd,
281 checkpointRef,
282 });
283 if (exists) {
284 return;
285 }
286
287 yield* checkpointStore
288 .captureCheckpoint({
289 cwd: input.scope.cwd,
290 checkpointRef,
291 })
292 .pipe(
293 Effect.catchTags({
294 VcsUnsupportedOperationError: () => Effect.void,
295 }),
296 );
297 }),
298 ).pipe(
299 Effect.mapError(
300 (cause) =>
301 new CheckpointBaselineCaptureError({
302 scopeId: input.scope.id,
303 ordinalWithinScope: input.ordinalWithinScope,
304 cause,
305 }),
306 ),
307 );
308
309 const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
310 (input) =>
311 withWorkspaceLock(
312 input.scope.cwd,
313 Effect.gen(function* () {
314 const checkpointRef = yield* checkpointRefFor({
315 scopeId: input.scope.id,
316 ordinalWithinScope: input.ordinalWithinScope,
317 });
318 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
319 scopeId: input.scope.id,
320 ordinalWithinScope: input.ordinalWithinScope,
321 });
322 const checkpointable = yield* isGitCheckpointable(input.scope.cwd);
323 const available = checkpointable
324 ? yield* checkpointStore
325 .hasCheckpointRef({
326 cwd: input.scope.cwd,
327 checkpointRef,
328 })
329 .pipe(
330 Effect.catch((cause) =>
331 Effect.logWarning("orchestration V2 baseline ref lookup failed", {
332 scopeId: input.scope.id,
333 checkpointRef,
334 cause: String(cause),
335 }).pipe(Effect.as(false)),
336 ),
337 )
338 : false;
339 return makeCheckpoint({
340 id: checkpointId,
341 scope: input.scope,
342 runId: null,
343 nodeId: input.scope.nodeId,
344 parentCheckpointId: null,
345 ordinalWithinScope: input.ordinalWithinScope,
346 appRunOrdinal: null,
347 ref: checkpointRef,
348 status: available ? "ready" : "missing",
349 files: [],
350 capturedAt: input.scope.createdAt,
351 });
352 }),
353 ).pipe(
354 Effect.mapError(
355 (cause) =>
356 new CheckpointCaptureError({
357 scopeId: input.scope.id,
358 cause,
359 }),
360 ),
361 );
362
363 const capture: CheckpointServiceV2Shape["capture"] = (input) =>
364 withWorkspaceLock(
365 input.scope.cwd,
366 Effect.gen(function* () {
367 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
368 scopeId: input.scope.id,
369 ordinalWithinScope: input.ordinalWithinScope,
370 });
371 const parentCheckpointId =
372 input.ordinalWithinScope > 0
373 ? yield* checkpointIdForScopeOrdinal(idAllocator, {
374 scopeId: input.scope.id,
375 ordinalWithinScope: input.ordinalWithinScope - 1,
376 })
377 : null;
378 const checkpointRef = yield* checkpointRefFor({
379 scopeId: input.scope.id,
380 ordinalWithinScope: input.ordinalWithinScope,
381 });
382 const previousCheckpointRef = yield* checkpointRefFor({
383 scopeId: input.scope.id,
384 ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
385 });
386
387 if (!(yield* isGitCheckpointable(input.scope.cwd))) {
388 return makeCheckpoint({
389 id: checkpointId,
390 scope: input.scope,
391 runId: input.runId,
392 nodeId: input.nodeId,
393 parentCheckpointId,
394 ordinalWithinScope: input.ordinalWithinScope,
395 appRunOrdinal: input.appRunOrdinal,
396 ref: checkpointRef,
397 status: "missing",
398 files: [],
399 capturedAt: input.capturedAt,
400 });
401 }
402
403 const captureStatus = yield* checkpointStore
404 .captureCheckpoint({
405 cwd: input.scope.cwd,
406 checkpointRef,
407 })
408 .pipe(
409 Effect.as("ready" as const),
410 Effect.catchTags({
411 VcsUnsupportedOperationError: () => Effect.succeed("missing" as const),
412 }),
413 Effect.catch((cause) =>
414 Effect.logWarning("orchestration V2 checkpoint capture failed", {
415 scopeId: input.scope.id,
416 checkpointRef,
417 cause: String(cause),
418 }).pipe(Effect.as("error" as const)),
419 ),
420 );
421
422 if (captureStatus !== "ready") {
423 return makeCheckpoint({
424 id: checkpointId,
425 scope: input.scope,
426 runId: input.runId,
427 nodeId: input.nodeId,
428 parentCheckpointId,
429 ordinalWithinScope: input.ordinalWithinScope,
430 appRunOrdinal: input.appRunOrdinal,
431 ref: checkpointRef,
432 status: captureStatus,
433 files: [],
434 capturedAt: input.capturedAt,
435 });
436 }
437
438 const previousExists = yield* checkpointStore
439 .hasCheckpointRef({
440 cwd: input.scope.cwd,
441 checkpointRef: previousCheckpointRef,
442 })
443 .pipe(
444 Effect.catch((cause) =>
445 Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", {
446 scopeId: input.scope.id,
447 checkpointRef: previousCheckpointRef,
448 cause: String(cause),
449 }).pipe(Effect.as(false)),
450 ),
451 );
452 const refs = {
453 cwd: input.scope.cwd,
454 fromCheckpointRef: previousCheckpointRef,
455 toCheckpointRef: checkpointRef,
456 };
457 // A pull or rebase can change thousands of files the turn did not write.
458 const files = previousExists
459 ? yield* Effect.all([
460 checkpointStore.diffCheckpoints({
461 ...refs,
462 fallbackFromToHead: false,
463 ignoreWhitespace: false,
464 format: "numstat",
465 }),
466 checkpointStore.listAuthoredPaths(refs).pipe(
467 Effect.catch((cause) =>
468 Effect.logWarning("orchestration V2 checkpoint authored paths failed", {
469 scopeId: input.scope.id,
470 checkpointRef,
471 cause: String(cause),
472 }).pipe(Effect.as(null)),
473 ),
474 ),
475 ]).pipe(
476 Effect.map(([diff, authoredPaths]) =>
477 parseTurnDiffFilesFromNumstat(diff)
478 .filter((file) => !isGitImport(file, authoredPaths))
479 .map((file) => ({
480 path: file.path,
481 kind: "modified",
482 additions: file.additions,
483 deletions: file.deletions,
484 })),
485 ),
486 Effect.catch((cause) =>
487 Effect.logWarning("orchestration V2 checkpoint diff summary failed", {
488 scopeId: input.scope.id,
489 checkpointRef,
490 cause: String(cause),
491 }).pipe(Effect.as([])),
492 ),
493 )
494 : [];
495
496 return makeCheckpoint({
497 id: checkpointId,
498 scope: input.scope,
499 runId: input.runId,
500 nodeId: input.nodeId,
501 parentCheckpointId,
502 ordinalWithinScope: input.ordinalWithinScope,
503 appRunOrdinal: input.appRunOrdinal,
504 ref: checkpointRef,
505 status: "ready",
506 files,
507 capturedAt: input.capturedAt,
508 });
509 }),
510 ).pipe(
511 Effect.mapError(
512 (cause) =>
513 new CheckpointCaptureError({
514 scopeId: input.scope.id,
515 cause,
516 }),
517 ),
518 );
519
520 const restore: CheckpointServiceV2Shape["restore"] = (input) =>
521 withWorkspaceLock(
522 input.scope.cwd,
523 Effect.gen(function* () {
524 if (input.checkpoint.status !== "ready") {
525 return yield* new CheckpointRestoreError({
526 scopeId: input.scope.id,
527 checkpointId: input.checkpoint.id,
528 cause: `Checkpoint status is ${input.checkpoint.status}.`,
529 });
530 }
531
532 const restored = yield* checkpointStore.restoreCheckpoint({
533 cwd: input.scope.cwd,
534 checkpointRef: input.checkpoint.ref,
535 fallbackToHead: false,
536 });
537 if (!restored) {
538 return yield* new CheckpointRestoreError({
539 scopeId: input.scope.id,
540 checkpointId: input.checkpoint.id,
541 cause: "Checkpoint ref is unavailable.",
542 });
543 }
544 }),
545 ).pipe(
546 Effect.mapError((cause) =>
547 isCheckpointRestoreError(cause)
548 ? cause
549 : new CheckpointRestoreError({
550 scopeId: input.scope.id,
551 checkpointId: input.checkpoint.id,
552 cause,
553 }),
554 ),
555 );
556
557 const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) =>
558 withWorkspaceLock(
559 input.scope.cwd,
560 checkpointStore.deleteCheckpointRefs({
561 cwd: input.scope.cwd,
562 checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref),
563 }),
564 ).pipe(
565 Effect.mapError(
566 (cause) =>
567 new CheckpointDeleteStaleRefsError({
568 scopeId: input.scope.id,
569 checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id),
570 cause,
571 }),
572 ),
573 );
574
575 return CheckpointServiceV2.of({
576 prepareRootRunScope: (input) =>
577 makeRootRunScope({ ...input, idAllocator }).pipe(
578 Effect.mapError(
579 (cause) =>
580 new CheckpointRootScopePrepareError({
581 threadId: input.threadId,
582 runId: input.runId,
583 cause,
584 }),
585 ),
586 ),
587 ensureScope,
588 captureBaseline,
589 materializeBaselineCheckpoint,
590 capture,
591 restore,
592 deleteStaleRefs,
593 } satisfies CheckpointServiceV2Shape);
594 }),
595);