Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CheckpointDiffQuery.ts

356 lines11.9 KB

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 type CheckpointRef,
11 OrchestrationGetTurnDiffResult,
12 type OrchestrationGetFullThreadDiffInput,
13 type OrchestrationGetFullThreadDiffResult,
14 type OrchestrationGetTurnDiffInput,
15 type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
16 type ThreadId,
17} from "@t3tools/contracts";
18import * as Context from "effect/Context";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Schema from "effect/Schema";
23​
24import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
25import {
26 CheckpointDiffResultInvalidError,
27 CheckpointRefUnavailableError,
28 CheckpointThreadNotFoundError,
29 CheckpointTurnRangeUnavailableError,
30 CheckpointWorkspacePathMissingError,
31} from "./Errors.ts";
32import type { CheckpointServiceError } from "./Errors.ts";
33import { checkpointRefForThreadTurn } from "./Utils.ts";
34import { filterUnifiedDiffFiles, listUnifiedDiffPaths } from "./Diffs.ts";
35import * as CheckpointStore from "./CheckpointStore.ts";
36​
37/** Service tag for checkpoint diff queries. */
38export class CheckpointDiffQuery extends Context.Service<
39 CheckpointDiffQuery,
40 {
41 /**
42 * Read the patch diff for a single turn checkpoint transition.
43 *
44 * Verifies checkpoint availability in both projection state and filesystem.
45 */
46 readonly getTurnDiff: (
47 input: OrchestrationGetTurnDiffInput,
48 ) => Effect.Effect<OrchestrationGetTurnDiffResultType, CheckpointServiceError>;
49​
50 /**
51 * Read the full patch diff across a thread range of checkpoints.
52 *
53 * Uses turn-diff semantics with `fromTurnCount = 0`.
54 */
55 readonly getFullThreadDiff: (
56 input: OrchestrationGetFullThreadDiffInput,
57 ) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
58 }
59>()("t3/checkpointing/CheckpointDiffQuery") {}
60​
61const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
62​
63function buildTurnDiffResult(
64 input: {
65 readonly threadId: ThreadId;
66 readonly fromTurnCount: number;
67 readonly toTurnCount: number;
68 },
69 diff: string,
70 gitFileCount?: number,
71): OrchestrationGetTurnDiffResultType {
72 return {
73 threadId: input.threadId,
74 fromTurnCount: input.fromTurnCount,
75 toTurnCount: input.toTurnCount,
76 diff,
77 ...(gitFileCount !== undefined ? { gitFileCount } : {}),
78 };
80​
81export const make = Effect.gen(function* () {
82 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
83 const checkpointStore = yield* CheckpointStore.CheckpointStore;
84​
85 // Drop file sections attributed to pre-existing git history from a patch
86 // unless the caller opted in. Attribution failures degrade to the
87 // unfiltered patch — never block the diff on attribution. The returned
88 // gitFileCount comes from the SAME attribution pass that produced the
89 // patch, so UI driven by it always agrees with what is rendered;
90 // undefined means attribution was unavailable and nothing was filtered.
91 const applyAttributionFilter = Effect.fn("applyAttributionFilter")(function* (input: {
92 readonly cwd: string;
93 readonly fromCheckpointRef: CheckpointRef;
94 readonly toCheckpointRef: CheckpointRef;
95 readonly diff: string;
96 readonly includeGitChanges: boolean;
97 }): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> {
98 if (input.diff.trim().length === 0) {
99 return { diff: input.diff, gitFileCount: undefined };
100 }
101 const attribution = yield* checkpointStore
102 .attributeCheckpointDiff({
103 cwd: input.cwd,
104 fromCheckpointRef: input.fromCheckpointRef,
105 toCheckpointRef: input.toCheckpointRef,
106 })
107 .pipe(Effect.catch(() => Effect.succeed(null)));
108 if (attribution === null) {
109 return { diff: input.diff, gitFileCount: undefined };
110 }
111 // Count only git-attributed paths with a section in THIS patch. The
112 // attribution map can include paths absent from the patch (e.g.
113 // whitespace-only changes elided by ignoreWhitespace) — counting those
114 // would advertise hidden files the toggle can never reveal.
115 let gitFileCount = 0;
116 for (const path of listUnifiedDiffPaths(input.diff)) {
117 if (attribution.get(path) === "git") {
118 gitFileCount += 1;
119 }
120 }
121 if (input.includeGitChanges || gitFileCount === 0) {
122 return { diff: input.diff, gitFileCount };
123 }
124 return {
125 diff: filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git"),
126 gitFileCount,
127 };
128 });
129​
130 const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
131 function* (input) {
132 const operation = "CheckpointDiffQuery.getTurnDiff";
133 const ignoreWhitespace = input.ignoreWhitespace ?? true;
134 yield* Effect.annotateCurrentSpan({
135 "checkpoint.thread_id": input.threadId,
136 "checkpoint.from_turn_count": input.fromTurnCount,
137 "checkpoint.to_turn_count": input.toTurnCount,
138 "checkpoint.ignore_whitespace": ignoreWhitespace,
139 });
140​
141 if (input.fromTurnCount === input.toTurnCount) {
142 const emptyDiff: OrchestrationGetTurnDiffResultType = {
143 threadId: input.threadId,
144 fromTurnCount: input.fromTurnCount,
145 toTurnCount: input.toTurnCount,
146 diff: "",
147 };
148 if (!isTurnDiffResult(emptyDiff)) {
149 return yield* new CheckpointDiffResultInvalidError({
150 operation,
151 threadId: input.threadId,
152 });
153 }
154 return emptyDiff;
155 }
156​
157 const threadContext = yield* projectionSnapshotQuery
158 .getThreadCheckpointContext(input.threadId)
159 .pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
160 if (Option.isNone(threadContext)) {
161 return yield* new CheckpointThreadNotFoundError({
162 operation,
163 threadId: input.threadId,
164 });
165 }
166​
167 const maxTurnCount = threadContext.value.checkpoints.reduce(
168 (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
169 0,
170 );
171 if (input.toTurnCount > maxTurnCount) {
172 return yield* new CheckpointTurnRangeUnavailableError({
173 operation,
174 threadId: input.threadId,
175 requestedTurnCount: input.toTurnCount,
176 availableTurnCount: maxTurnCount,
177 });
178 }
179​
180 const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
181 if (!workspaceCwd) {
182 return yield* new CheckpointWorkspacePathMissingError({
183 operation,
184 threadId: input.threadId,
185 });
186 }
187​
188 const fromCheckpointRef =
189 input.fromTurnCount === 0
190 ? checkpointRefForThreadTurn(input.threadId, 0)
191 : threadContext.value.checkpoints.find(
192 (checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
193 )?.checkpointRef;
194 if (!fromCheckpointRef) {
195 return yield* new CheckpointRefUnavailableError({
196 operation,
197 threadId: input.threadId,
198 turnCount: input.fromTurnCount,
199 checkpoint: "from",
200 });
201 }
202​
203 const toCheckpointRef = threadContext.value.checkpoints.find(
204 (checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
205 )?.checkpointRef;
206 if (!toCheckpointRef) {
207 return yield* new CheckpointRefUnavailableError({
208 operation,
209 threadId: input.threadId,
210 turnCount: input.toTurnCount,
211 checkpoint: "to",
212 });
213 }
214​
215 const rawDiff = yield* checkpointStore
216 .diffCheckpoints({
217 cwd: workspaceCwd,
218 fromCheckpointRef,
219 toCheckpointRef,
220 fallbackFromToHead: false,
221 ignoreWhitespace,
222 })
223 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
224 const filtered = yield* applyAttributionFilter({
225 cwd: workspaceCwd,
226 fromCheckpointRef,
227 toCheckpointRef,
228 diff: rawDiff,
229 includeGitChanges: input.includeGitChanges ?? false,
230 });
231​
232 const turnDiff = buildTurnDiffResult(input, filtered.diff, filtered.gitFileCount);
233 if (!isTurnDiffResult(turnDiff)) {
234 return yield* new CheckpointDiffResultInvalidError({
235 operation,
236 threadId: input.threadId,
237 });
238 }
239​
240 return turnDiff;
241 },
242 );
243​
244 const getFullThreadDiff: CheckpointDiffQuery["Service"]["getFullThreadDiff"] = Effect.fn(
245 "CheckpointDiffQuery.getFullThreadDiff",
246 )(function* (input) {
247 const operation = "CheckpointDiffQuery.getFullThreadDiff";
248 const ignoreWhitespace = input.ignoreWhitespace ?? true;
249 yield* Effect.annotateCurrentSpan({
250 "checkpoint.thread_id": input.threadId,
251 "checkpoint.from_turn_count": 0,
252 "checkpoint.to_turn_count": input.toTurnCount,
253 "checkpoint.ignore_whitespace": ignoreWhitespace,
254 "checkpoint.diff_kind": "full-thread",
255 });
256​
257 if (input.toTurnCount === 0) {
258 const emptyDiff = buildTurnDiffResult(
259 {
260 threadId: input.threadId,
261 fromTurnCount: 0,
262 toTurnCount: 0,
263 },
264 "",
265 );
266 if (!isTurnDiffResult(emptyDiff)) {
267 return yield* new CheckpointDiffResultInvalidError({
268 operation,
269 threadId: input.threadId,
270 });
271 }
272 return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
273 }
274​
275 const threadContext = yield* projectionSnapshotQuery
276 .getFullThreadDiffContext(input.threadId, input.toTurnCount)
277 .pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
278​
279 if (Option.isNone(threadContext)) {
280 return yield* new CheckpointThreadNotFoundError({
281 operation,
282 threadId: input.threadId,
283 });
284 }
285​
286 if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
287 return yield* new CheckpointTurnRangeUnavailableError({
288 operation,
289 threadId: input.threadId,
290 requestedTurnCount: input.toTurnCount,
291 availableTurnCount: threadContext.value.latestCheckpointTurnCount,
292 });
293 }
294​
295 const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
296 if (!workspaceCwd) {
297 return yield* new CheckpointWorkspacePathMissingError({
298 operation,
299 threadId: input.threadId,
300 });
301 }
302​
303 if (!threadContext.value.toCheckpointRef) {
304 return yield* new CheckpointRefUnavailableError({
305 operation,
306 threadId: input.threadId,
307 turnCount: input.toTurnCount,
308 checkpoint: "to",
309 });
310 }
311​
312 const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, 0);
313 const toCheckpointRef = threadContext.value.toCheckpointRef as CheckpointRef;
314 const rawDiff = yield* checkpointStore
315 .diffCheckpoints({
316 cwd: workspaceCwd,
317 fromCheckpointRef,
318 toCheckpointRef,
319 fallbackFromToHead: false,
320 ignoreWhitespace,
321 })
322 .pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
323 const filtered = yield* applyAttributionFilter({
324 cwd: workspaceCwd,
325 fromCheckpointRef,
326 toCheckpointRef,
327 diff: rawDiff,
328 includeGitChanges: input.includeGitChanges ?? false,
329 });
330​
331 const turnDiff = buildTurnDiffResult(
332 {
333 threadId: input.threadId,
334 fromTurnCount: 0,
335 toTurnCount: input.toTurnCount,
336 },
337 filtered.diff,
338 filtered.gitFileCount,
339 );
340 if (!isTurnDiffResult(turnDiff)) {
341 return yield* new CheckpointDiffResultInvalidError({
342 operation,
343 threadId: input.threadId,
344 });
345 }
346​
347 return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
348 });
349​
350 return CheckpointDiffQuery.of({
351 getTurnDiff,
352 getFullThreadDiff,
353 });
354});
355​
356export const layer = Layer.effect(CheckpointDiffQuery, make);