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