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 /** The run materializing the baseline: its root node, and when it was requested. */
122 readonly nodeId: NodeId;
123 readonly capturedAt: DateTime.Utc;
124 /** Records a missing checkpoint without touching git, for side chats sharing a parent's worktree. */
125 readonly forceMissing?: boolean;
126 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
127 readonly capture: (input: {
128 readonly scope: OrchestrationV2CheckpointScope;
129 readonly runId: RunId | null;
130 readonly nodeId: NodeId;
131 readonly ordinalWithinScope: number;
132 readonly appRunOrdinal: number | null;
133 readonly capturedAt: DateTime.Utc;
134 readonly forceMissing?: boolean;
135 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
136 readonly restore: (input: {
137 readonly scope: OrchestrationV2CheckpointScope;
138 readonly checkpoint: OrchestrationV2Checkpoint;
139 }) => Effect.Effect<void, CheckpointServiceV2Error>;
140 readonly deleteStaleRefs: (input: {
141 readonly scope: OrchestrationV2CheckpointScope;
142 readonly checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>;
143 }) => Effect.Effect<void, CheckpointServiceV2Error>;
144}
145
146export class CheckpointServiceV2 extends Context.Service<
147 CheckpointServiceV2,
148 CheckpointServiceV2Shape
149>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
150
151export const checkpointRefForScopeOrdinal = Effect.fn("checkpointRefForScopeOrdinal")(
152 function* (input: { readonly scopeId: CheckpointScopeId; readonly ordinalWithinScope: number }) {
153 const crypto = yield* Digest.Digest;
154 const digest = yield* crypto
155 .digest(Digest.sha256, new TextEncoder().encode(input.scopeId))
156 .pipe(Effect.orDie);
157 const scopeKey = Hex.encode(digest).slice(0, 32);
158 return CheckpointRef.make(
159 `${CHECKPOINT_REFS_PREFIX}/${Base64Url.encode(scopeKey)}/ordinal/${input.ordinalWithinScope}`,
160 );
161 },
162);
163
164function checkpointIdForScopeOrdinal(
165 idAllocator: IdAllocator.IdAllocatorV2["Service"],
166 input: {
167 readonly scopeId: CheckpointScopeId;
168 readonly ordinalWithinScope: number;
169 },
170) {
171 return idAllocator.allocate.checkpoint({
172 checkpointScopeId: input.scopeId,
173 name: String(input.ordinalWithinScope),
174 });
175}
176
177const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: {
178 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
179 readonly threadId: ThreadId;
180 readonly runId: RunId;
181 readonly rootNodeId: NodeId;
182 readonly providerThreadId: ProviderThreadId;
183 readonly cwd: string;
184 readonly createdAt: DateTime.Utc;
185}) {
186 const scopeId = yield* input.idAllocator.allocate.checkpointScope({
187 threadId: input.threadId,
188 name: ROOT_CHECKPOINT_SCOPE_NAME,
189 });
190 return {
191 id: scopeId,
192 threadId: input.threadId,
193 runId: input.runId,
194 nodeId: input.rootNodeId,
195 parentScopeId: null,
196 providerThreadId: input.providerThreadId,
197 kind: "root_run",
198 ordinalWithinParent: 0,
199 advancesAppRunCount: true,
200 cwd: input.cwd,
201 createdAt: input.createdAt,
202 } satisfies OrchestrationV2CheckpointScope;
203});
204
205function makeCheckpoint(input: {
206 readonly id: CheckpointId;
207 readonly scope: OrchestrationV2CheckpointScope;
208 readonly runId: RunId | null;
209 readonly nodeId: NodeId;
210 readonly parentCheckpointId: CheckpointId | null;
211 readonly ordinalWithinScope: number;
212 readonly appRunOrdinal: number | null;
213 readonly ref: CheckpointRef;
214 readonly status: OrchestrationV2Checkpoint["status"];
215 readonly files: OrchestrationV2Checkpoint["files"];
216 readonly capturedAt: DateTime.Utc;
217}): OrchestrationV2Checkpoint {
218 return {
219 id: input.id,
220 threadId: input.scope.threadId,
221 scopeId: input.scope.id,
222 runId: input.runId,
223 nodeId: input.nodeId,
224 parentCheckpointId: input.parentCheckpointId,
225 ordinalWithinScope: input.ordinalWithinScope,
226 appRunOrdinal: input.appRunOrdinal,
227 ref: input.ref,
228 status: input.status,
229 files: input.files,
230 capturedAt: input.capturedAt,
231 };
232}
233
234export const layer: Layer.Layer<
235 CheckpointServiceV2,
236 never,
237 CheckpointStore.CheckpointStore | Digest.Digest | IdAllocator.IdAllocatorV2
238> = Layer.effect(
239 CheckpointServiceV2,
240 Effect.gen(function* () {
241 const checkpointStore = yield* CheckpointStore.CheckpointStore;
242 const crypto = yield* Digest.Digest;
243 const checkpointRefFor = (input: Parameters<typeof checkpointRefForScopeOrdinal>[0]) =>
244 checkpointRefForScopeOrdinal(input).pipe(Effect.provideService(Digest.Digest, crypto));
245 const idAllocator = yield* IdAllocator.IdAllocatorV2;
246 const workspaceLocks = yield* KeyedLock.make<string>();
247 const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
248 workspaceLocks.withLock(cwd, effect);
249
250 // A failed probe is an operational error, not proof that the workspace has no repository.
251 const probeRepository = (scope: OrchestrationV2CheckpointScope) =>
252 checkpointStore.isGitRepository(scope.cwd).pipe(
253 Effect.map((isRepository) =>
254 isRepository ? ("repository" as const) : ("missing" as const),
255 ),
256 Effect.catch((cause) =>
257 Effect.logWarning("orchestration V2 checkpoint repository probe failed", {
258 scopeId: scope.id,
259 cause: String(cause),
260 }).pipe(Effect.as("error" as const)),
261 ),
262 );
263
264 const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = (input) =>
265 withWorkspaceLock(
266 input.scope.cwd,
267 Effect.gen(function* () {
268 if (!(yield* checkpointStore.isGitRepository(input.scope.cwd))) {
269 return;
270 }
271
272 const checkpointRef = yield* checkpointRefFor({
273 scopeId: input.scope.id,
274 ordinalWithinScope: input.ordinalWithinScope,
275 });
276 const exists = yield* checkpointStore.hasCheckpointRef({
277 cwd: input.scope.cwd,
278 checkpointRef,
279 });
280 if (exists) {
281 return;
282 }
283
284 yield* checkpointStore
285 .captureCheckpoint({
286 cwd: input.scope.cwd,
287 checkpointRef,
288 })
289 .pipe(
290 Effect.catchTags({
291 VcsUnsupportedOperationError: () => Effect.void,
292 }),
293 );
294 }),
295 ).pipe(
296 Effect.mapError(
297 (cause) =>
298 new CheckpointBaselineCaptureError({
299 scopeId: input.scope.id,
300 ordinalWithinScope: input.ordinalWithinScope,
301 cause,
302 }),
303 ),
304 );
305
306 const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
307 (input) =>
308 withWorkspaceLock(
309 input.scope.cwd,
310 Effect.gen(function* () {
311 const checkpointRef = yield* checkpointRefFor({
312 scopeId: input.scope.id,
313 ordinalWithinScope: input.ordinalWithinScope,
314 });
315 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
316 scopeId: input.scope.id,
317 ordinalWithinScope: input.ordinalWithinScope,
318 });
319 const repository =
320 input.forceMissing === true ? "missing" : yield* probeRepository(input.scope);
321 const status =
322 repository === "repository"
323 ? yield* checkpointStore
324 .hasCheckpointRef({
325 cwd: input.scope.cwd,
326 checkpointRef,
327 })
328 .pipe(
329 Effect.map((exists) => (exists ? ("ready" as const) : ("missing" as const))),
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("error" as const)),
336 ),
337 )
338 : repository;
339 return makeCheckpoint({
340 id: checkpointId,
341 scope: input.scope,
342 runId: null,
343 nodeId: input.nodeId,
344 parentCheckpointId: null,
345 ordinalWithinScope: input.ordinalWithinScope,
346 appRunOrdinal: null,
347 ref: checkpointRef,
348 status,
349 files: [],
350 capturedAt: input.capturedAt,
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 const repository =
388 input.forceMissing === true ? "missing" : yield* probeRepository(input.scope);
389 if (repository !== "repository") {
390 return makeCheckpoint({
391 id: checkpointId,
392 scope: input.scope,
393 runId: input.runId,
394 nodeId: input.nodeId,
395 parentCheckpointId,
396 ordinalWithinScope: input.ordinalWithinScope,
397 appRunOrdinal: input.appRunOrdinal,
398 ref: checkpointRef,
399 status: repository,
400 files: [],
401 capturedAt: input.capturedAt,
402 });
403 }
404
405 const captureStatus = yield* checkpointStore
406 .captureCheckpoint({
407 cwd: input.scope.cwd,
408 checkpointRef,
409 })
410 .pipe(
411 Effect.as("ready" as const),
412 Effect.catchTags({
413 VcsUnsupportedOperationError: () => Effect.succeed("missing" as const),
414 }),
415 Effect.catch((cause) =>
416 Effect.logWarning("orchestration V2 checkpoint capture failed", {
417 scopeId: input.scope.id,
418 checkpointRef,
419 cause: String(cause),
420 }).pipe(Effect.as("error" as const)),
421 ),
422 );
423
424 if (captureStatus !== "ready") {
425 return makeCheckpoint({
426 id: checkpointId,
427 scope: input.scope,
428 runId: input.runId,
429 nodeId: input.nodeId,
430 parentCheckpointId,
431 ordinalWithinScope: input.ordinalWithinScope,
432 appRunOrdinal: input.appRunOrdinal,
433 ref: checkpointRef,
434 status: captureStatus,
435 files: [],
436 capturedAt: input.capturedAt,
437 });
438 }
439
440 const previousExists = yield* checkpointStore
441 .hasCheckpointRef({
442 cwd: input.scope.cwd,
443 checkpointRef: previousCheckpointRef,
444 })
445 .pipe(
446 Effect.catch((cause) =>
447 Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", {
448 scopeId: input.scope.id,
449 checkpointRef: previousCheckpointRef,
450 cause: String(cause),
451 }).pipe(Effect.as(false)),
452 ),
453 );
454 const refs = {
455 cwd: input.scope.cwd,
456 fromCheckpointRef: previousCheckpointRef,
457 toCheckpointRef: checkpointRef,
458 };
459 // A pull or rebase can change thousands of files the turn did not write.
460 const files = previousExists
461 ? yield* Effect.all([
462 checkpointStore.diffCheckpoints({
463 ...refs,
464 fallbackFromToHead: false,
465 ignoreWhitespace: false,
466 format: "numstat",
467 }),
468 checkpointStore.listAuthoredPaths(refs).pipe(
469 Effect.catch((cause) =>
470 Effect.logWarning("orchestration V2 checkpoint authored paths failed", {
471 scopeId: input.scope.id,
472 checkpointRef,
473 cause: String(cause),
474 }).pipe(Effect.as(null)),
475 ),
476 ),
477 ]).pipe(
478 Effect.map(([diff, authoredPaths]) =>
479 parseTurnDiffFilesFromNumstat(diff)
480 .filter((file) => !isGitImport(file, authoredPaths))
481 .map((file) => ({
482 path: file.path,
483 kind: "modified",
484 additions: file.additions,
485 deletions: file.deletions,
486 })),
487 ),
488 Effect.catch((cause) =>
489 Effect.logWarning("orchestration V2 checkpoint diff summary failed", {
490 scopeId: input.scope.id,
491 checkpointRef,
492 cause: String(cause),
493 }).pipe(Effect.as([])),
494 ),
495 )
496 : [];
497
498 return makeCheckpoint({
499 id: checkpointId,
500 scope: input.scope,
501 runId: input.runId,
502 nodeId: input.nodeId,
503 parentCheckpointId,
504 ordinalWithinScope: input.ordinalWithinScope,
505 appRunOrdinal: input.appRunOrdinal,
506 ref: checkpointRef,
507 status: "ready",
508 files,
509 capturedAt: input.capturedAt,
510 });
511 }),
512 ).pipe(
513 Effect.mapError(
514 (cause) =>
515 new CheckpointCaptureError({
516 scopeId: input.scope.id,
517 cause,
518 }),
519 ),
520 );
521
522 const restore: CheckpointServiceV2Shape["restore"] = (input) =>
523 withWorkspaceLock(
524 input.scope.cwd,
525 Effect.gen(function* () {
526 if (input.checkpoint.status !== "ready") {
527 return yield* new CheckpointRestoreError({
528 scopeId: input.scope.id,
529 checkpointId: input.checkpoint.id,
530 cause: `Checkpoint status is ${input.checkpoint.status}.`,
531 });
532 }
533
534 const restored = yield* checkpointStore.restoreCheckpoint({
535 cwd: input.scope.cwd,
536 checkpointRef: input.checkpoint.ref,
537 fallbackToHead: false,
538 });
539 if (!restored) {
540 return yield* new CheckpointRestoreError({
541 scopeId: input.scope.id,
542 checkpointId: input.checkpoint.id,
543 cause: "Checkpoint ref is unavailable.",
544 });
545 }
546 }),
547 ).pipe(
548 Effect.mapError((cause) =>
549 isCheckpointRestoreError(cause)
550 ? cause
551 : new CheckpointRestoreError({
552 scopeId: input.scope.id,
553 checkpointId: input.checkpoint.id,
554 cause,
555 }),
556 ),
557 );
558
559 const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) =>
560 withWorkspaceLock(
561 input.scope.cwd,
562 checkpointStore.deleteCheckpointRefs({
563 cwd: input.scope.cwd,
564 checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref),
565 }),
566 ).pipe(
567 Effect.mapError(
568 (cause) =>
569 new CheckpointDeleteStaleRefsError({
570 scopeId: input.scope.id,
571 checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id),
572 cause,
573 }),
574 ),
575 );
576
577 return CheckpointServiceV2.of({
578 prepareRootRunScope: (input) =>
579 makeRootRunScope({ ...input, idAllocator }).pipe(
580 Effect.mapError(
581 (cause) =>
582 new CheckpointRootScopePrepareError({
583 threadId: input.threadId,
584 runId: input.runId,
585 cause,
586 }),
587 ),
588 ),
589 captureBaseline,
590 materializeBaselineCheckpoint,
591 capture,
592 restore,
593 deleteStaleRefs,
594 } satisfies CheckpointServiceV2Shape);
595 }),
596);