Open History to see the last commit
1/**
2 * CheckpointDiffQuery - Query interface for computed checkpoint diffs.
3 *
4 * Provides read-only diff operations across checkpoint snapshots used by
5 * orchestration APIs.
6 *
7 * @module CheckpointDiffQuery
8 */
9import {
10 OrchestrationGetTurnDiffResult,
11 type OrchestrationGetFullThreadDiffInput,
12 type OrchestrationGetFullThreadDiffResult,
13 type OrchestrationGetTurnDiffInput,
14 type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
15 type ThreadId,
16} from "@t3tools/contracts";
17import * as Context from "effect/Context";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Schema from "effect/Schema";
21
22import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
23import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
24import {
25 CheckpointDiffResultInvalidError,
26 CheckpointRefUnavailableError,
27 CheckpointThreadNotFoundError,
28 CheckpointTurnRangeUnavailableError,
29 CheckpointWorkspacePathMissingError,
30 type CheckpointServiceError,
31} from "./Errors.ts";
32import * as CheckpointStore from "./CheckpointStore.ts";
33
34/** Service tag for checkpoint diff queries. */
35export class CheckpointDiffQuery extends Context.Service<
36 CheckpointDiffQuery,
37 {
38 /**
39 * Read the patch diff for a single turn checkpoint transition.
40 *
41 * Verifies checkpoint availability in both projection state and filesystem.
42 */
43 readonly getTurnDiff: (
44 input: OrchestrationGetTurnDiffInput,
45 ) => Effect.Effect<OrchestrationGetTurnDiffResultType, CheckpointServiceError>;
46
47 /**
48 * Read the full patch diff across a thread range of checkpoints.
49 *
50 * Uses turn-diff semantics with `fromTurnCount = 0`.
51 */
52 readonly getFullThreadDiff: (
53 input: OrchestrationGetFullThreadDiffInput,
54 ) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
55 }
56>()("t3/checkpointing/CheckpointDiffQuery") {}
57
58const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
59
60function buildTurnDiffResult(
61 input: {
62 readonly threadId: ThreadId;
63 readonly fromTurnCount: number;
64 readonly toTurnCount: number;
65 },
66 diff: string,
67): OrchestrationGetTurnDiffResultType {
68 return {
69 threadId: input.threadId,
70 fromTurnCount: input.fromTurnCount,
71 toTurnCount: input.toTurnCount,
72 diff,
73 };
74}
75
76export const make = Effect.gen(function* () {
77 const threads = yield* ThreadManagement.ThreadManagementService;
78 const checkpointStore = yield* CheckpointStore.CheckpointStore;
79
80 const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
81 function* (input) {
82 const operation = "CheckpointDiffQuery.getTurnDiff";
83 const ignoreWhitespace = input.ignoreWhitespace ?? true;
84 yield* Effect.annotateCurrentSpan({
85 "checkpoint.thread_id": input.threadId,
86 "checkpoint.from_turn_count": input.fromTurnCount,
87 "checkpoint.to_turn_count": input.toTurnCount,
88 "checkpoint.ignore_whitespace": ignoreWhitespace,
89 });
90
91 if (input.fromTurnCount === input.toTurnCount) {
92 const emptyDiff = buildTurnDiffResult(input, "");
93 if (!isTurnDiffResult(emptyDiff)) {
94 return yield* new CheckpointDiffResultInvalidError({
95 operation,
96 threadId: input.threadId,
97 });
98 }
99 return emptyDiff;
100 }
101
102 const projection = yield* threads.getThreadProjection(input.threadId).pipe(
103 Effect.mapError(
104 () =>
105 new CheckpointThreadNotFoundError({
106 operation,
107 threadId: input.threadId,
108 }),
109 ),
110 Effect.withSpan("checkpoint.turnDiff.lookupProjection"),
111 );
112 const completedRunIds = new Set(
113 projection.runs.filter((run) => run.status === "completed").map((run) => run.id),
114 );
115 const readyCheckpoints = projection.checkpoints.filter(
116 (checkpoint) =>
117 checkpoint.status === "ready" &&
118 checkpoint.appRunOrdinal !== null &&
119 checkpoint.runId !== null &&
120 completedRunIds.has(checkpoint.runId),
121 );
122 const maxTurnCount = readyCheckpoints.reduce(
123 (max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0),
124 0,
125 );
126 if (input.toTurnCount > maxTurnCount) {
127 return yield* new CheckpointTurnRangeUnavailableError({
128 operation,
129 threadId: input.threadId,
130 requestedTurnCount: input.toTurnCount,
131 availableTurnCount: maxTurnCount,
132 });
133 }
134
135 const toCheckpoint = readyCheckpoints.find(
136 (checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount,
137 );
138 if (toCheckpoint === undefined) {
139 return yield* new CheckpointRefUnavailableError({
140 operation,
141 threadId: input.threadId,
142 turnCount: input.toTurnCount,
143 checkpoint: "to",
144 });
145 }
146
147 const toScope = projection.checkpointScopes.find(
148 (scope) => scope.id === toCheckpoint.scopeId,
149 );
150 if (toScope === undefined) {
151 return yield* new CheckpointWorkspacePathMissingError({
152 operation,
153 threadId: input.threadId,
154 });
155 }
156
157 const fromCheckpointRef =
158 input.fromTurnCount === 0
159 ? (() => {
160 const firstRun = projection.runs.find((run) => run.ordinal === 1);
161 const firstScope = projection.checkpointScopes.find(
162 (scope) => scope.runId === firstRun?.id && scope.kind === "root_run",
163 );
164 return firstScope === undefined
165 ? undefined
166 : checkpointRefForScopeOrdinal({
167 scopeId: firstScope.id,
168 ordinalWithinScope: 0,
169 });
170 })()
171 : readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)
172 ?.ref;
173 if (fromCheckpointRef === undefined) {
174 return yield* new CheckpointRefUnavailableError({
175 operation,
176 threadId: input.threadId,
177 turnCount: input.fromTurnCount,
178 checkpoint: "from",
179 });
180 }
181
182 const diff = yield* checkpointStore
183 .diffCheckpoints({
184 cwd: toScope.cwd,
185 fromCheckpointRef,
186 toCheckpointRef: toCheckpoint.ref,
187 fallbackFromToHead: false,
188 ignoreWhitespace,
189 })
190 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
191
192 const turnDiff = buildTurnDiffResult(input, diff);
193 if (!isTurnDiffResult(turnDiff)) {
194 return yield* new CheckpointDiffResultInvalidError({
195 operation,
196 threadId: input.threadId,
197 });
198 }
199
200 return turnDiff;
201 },
202 );
203
204 const getFullThreadDiff: CheckpointDiffQuery["Service"]["getFullThreadDiff"] = Effect.fn(
205 "CheckpointDiffQuery.getFullThreadDiff",
206 )(function* (input) {
207 const operation = "CheckpointDiffQuery.getFullThreadDiff";
208 const ignoreWhitespace = input.ignoreWhitespace ?? true;
209 yield* Effect.annotateCurrentSpan({
210 "checkpoint.thread_id": input.threadId,
211 "checkpoint.from_turn_count": 0,
212 "checkpoint.to_turn_count": input.toTurnCount,
213 "checkpoint.ignore_whitespace": ignoreWhitespace,
214 "checkpoint.diff_kind": "full-thread",
215 });
216
217 if (input.toTurnCount === 0) {
218 const emptyDiff = buildTurnDiffResult(
219 {
220 threadId: input.threadId,
221 fromTurnCount: 0,
222 toTurnCount: 0,
223 },
224 "",
225 );
226 if (!isTurnDiffResult(emptyDiff)) {
227 return yield* new CheckpointDiffResultInvalidError({
228 operation,
229 threadId: input.threadId,
230 });
231 }
232 return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
233 }
234
235 const turnDiff = yield* getTurnDiff({
236 threadId: input.threadId,
237 fromTurnCount: 0,
238 toTurnCount: input.toTurnCount,
239 ignoreWhitespace,
240 });
241 if (!isTurnDiffResult(turnDiff)) {
242 return yield* new CheckpointDiffResultInvalidError({
243 operation,
244 threadId: input.threadId,
245 });
246 }
247
248 return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
249 });
250
251 return CheckpointDiffQuery.of({
252 getTurnDiff,
253 getFullThreadDiff,
254 });
255});
256
257export const layer = Layer.effect(CheckpointDiffQuery, make);