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

CheckpointDiffQuery.ts

301 lines10.2 KB

1import {
2 OrchestrationGetTurnDiffResult,
3 type OrchestrationGetFullThreadDiffInput,
4 type OrchestrationGetFullThreadDiffResult,
5 type OrchestrationGetTurnDiffInput,
6 type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as Crypto from "effect/Crypto";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Schema from "effect/Schema";
14​
15import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
16import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
17import {
18 CheckpointDiffResultInvalidError,
19 CheckpointRefUnavailableError,
20 CheckpointThreadNotFoundError,
21 CheckpointTurnRangeUnavailableError,
22 CheckpointWorkspacePathMissingError,
23 type CheckpointServiceError,
24} from "./Errors.ts";
25import * as CheckpointStore from "./CheckpointStore.ts";
26import { isGitImport, parseTurnDiffFilesFromNumstat, type TurnDiffFileSummary } from "./Diffs.ts";
27​
28// Windows limits a command line to 32,767 characters. Leave room for the rest of git's arguments.
29const MAX_PATHSPEC_CHARS = 24_000;
30​
31function batchFilePaths(files: ReadonlyArray<TurnDiffFileSummary>) {
32 const batches: string[][] = [];
33 let batch: string[] = [];
34 let length = 0;
35 for (const file of files) {
36 const paths = file.previousPath === undefined ? [file.path] : [file.previousPath, file.path];
37 const size = paths.reduce((total, path) => total + path.length + 16, 0);
38 if (batch.length > 0 && length + size > MAX_PATHSPEC_CHARS) {
39 batches.push(batch);
40 batch = [];
41 length = 0;
42 }
43 batch.push(...paths);
44 length += size;
45 }
46 if (batch.length > 0) batches.push(batch);
47 return batches;
49​
50export class CheckpointDiffQuery extends Context.Service<
51 CheckpointDiffQuery,
52 {
53 readonly getTurnDiff: (
54 input: OrchestrationGetTurnDiffInput,
55 ) => Effect.Effect<OrchestrationGetTurnDiffResultType, CheckpointServiceError>;
56​
57 readonly getFullThreadDiff: (
58 input: OrchestrationGetFullThreadDiffInput,
59 ) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
60 }
61>()("t3/checkpointing/CheckpointDiffQuery") {}
62​
63const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
64​
65function buildTurnDiffResult(
66 input: {
67 readonly threadId: ThreadId;
68 readonly fromTurnCount: number;
69 readonly toTurnCount: number;
70 },
71 diff: string,
72): OrchestrationGetTurnDiffResultType {
73 return {
74 threadId: input.threadId,
75 fromTurnCount: input.fromTurnCount,
76 toTurnCount: input.toTurnCount,
77 diff,
78 };
80​
81/** @public Service construction is part of the canonical Effect module API. */
82export const make = Effect.gen(function* () {
83 const threads = yield* ThreadManagement.ThreadManagementService;
84 const checkpointStore = yield* CheckpointStore.CheckpointStore;
85 const crypto = yield* Crypto.Crypto;
86​
87 const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
88 function* (input) {
89 const operation = "CheckpointDiffQuery.getTurnDiff";
90 const ignoreWhitespace = input.ignoreWhitespace ?? true;
91 yield* Effect.annotateCurrentSpan({
92 "checkpoint.thread_id": input.threadId,
93 "checkpoint.from_turn_count": input.fromTurnCount,
94 "checkpoint.to_turn_count": input.toTurnCount,
95 "checkpoint.ignore_whitespace": ignoreWhitespace,
96 });
97​
98 if (input.fromTurnCount === input.toTurnCount) {
99 const emptyDiff = buildTurnDiffResult(input, "");
100 if (!isTurnDiffResult(emptyDiff)) {
101 return yield* new CheckpointDiffResultInvalidError({
102 operation,
103 threadId: input.threadId,
104 });
105 }
106 return emptyDiff;
107 }
108​
109 const projection = yield* threads.getCheckpointContext(input.threadId).pipe(
110 Effect.mapError(
111 () =>
112 new CheckpointThreadNotFoundError({
113 operation,
114 threadId: input.threadId,
115 }),
116 ),
117 Effect.withSpan("checkpoint.turnDiff.lookupContext"),
118 );
119 const completedRunIds = new Set(
120 projection.runs.filter((run) => run.status === "completed").map((run) => run.id),
121 );
122 const readyCheckpoints = projection.checkpoints.filter(
123 (checkpoint) =>
124 checkpoint.status === "ready" &&
125 checkpoint.appRunOrdinal !== null &&
126 checkpoint.runId !== null &&
127 completedRunIds.has(checkpoint.runId),
128 );
129 const maxTurnCount = readyCheckpoints.reduce(
130 (max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0),
131 0,
132 );
133 if (input.toTurnCount > maxTurnCount) {
134 return yield* new CheckpointTurnRangeUnavailableError({
135 operation,
136 threadId: input.threadId,
137 requestedTurnCount: input.toTurnCount,
138 availableTurnCount: maxTurnCount,
139 });
140 }
141​
142 const toCheckpoint = readyCheckpoints.find(
143 (checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount,
144 );
145 if (toCheckpoint === undefined) {
146 return yield* new CheckpointRefUnavailableError({
147 operation,
148 threadId: input.threadId,
149 turnCount: input.toTurnCount,
150 checkpoint: "to",
151 });
152 }
153​
154 const toScope = projection.checkpointScopes.find(
155 (scope) => scope.id === toCheckpoint.scopeId,
156 );
157 if (toScope === undefined) {
158 return yield* new CheckpointWorkspacePathMissingError({
159 operation,
160 threadId: input.threadId,
161 });
162 }
163​
164 // Capture compares against the preceding scope ordinal, even when that
165 // checkpoint belongs to a stopped run or has no run.
166 const parentCheckpoint =
167 input.fromTurnCount === input.toTurnCount - 1
168 ? projection.checkpoints.find(
169 (checkpoint) =>
170 checkpoint.status === "ready" &&
171 checkpoint.scopeId === toCheckpoint.scopeId &&
172 checkpoint.ordinalWithinScope === toCheckpoint.ordinalWithinScope - 1,
173 )
174 : undefined;
175​
176 const firstScope =
177 input.fromTurnCount === 0
178 ? projection.checkpointScopes.find((scope) => scope.kind === "root_run")
179 : undefined;
180 const fromCheckpointRef =
181 input.fromTurnCount === 0
182 ? firstScope === undefined
183 ? undefined
184 : yield* checkpointRefForScopeOrdinal({
185 scopeId: firstScope.id,
186 ordinalWithinScope: 0,
187 }).pipe(Effect.provideService(Crypto.Crypto, crypto))
188 : (
189 parentCheckpoint ??
190 readyCheckpoints.find(
191 (checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount,
192 )
193 )?.ref;
194 if (fromCheckpointRef === undefined) {
195 return yield* new CheckpointRefUnavailableError({
196 operation,
197 threadId: input.threadId,
198 turnCount: input.fromTurnCount,
199 checkpoint: "from",
200 });
201 }
202​
203 const comparison = {
204 cwd: toScope.cwd,
205 fromCheckpointRef,
206 toCheckpointRef: toCheckpoint.ref,
207 fallbackFromToHead: false,
208 ignoreWhitespace,
209 };
210 const authoredPaths = yield* checkpointStore
211 .listAuthoredPaths(comparison)
212 .pipe(Effect.orElseSucceed(() => null));
213 const files =
214 authoredPaths === null
215 ? []
216 : yield* checkpointStore.diffCheckpoints({ ...comparison, format: "numstat" }).pipe(
217 Effect.map(parseTurnDiffFilesFromNumstat),
218 Effect.orElseSucceed(() => []),
219 );
220 const retainedFiles = files.filter((file) => !isGitImport(file, authoredPaths));
221 // Select retained paths before generating a patch, so imported bulk cannot exhaust its output limit.
222 const diff =
223 retainedFiles.length === files.length
224 ? yield* checkpointStore
225 .diffCheckpoints(comparison)
226 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"))
227 : (yield* Effect.forEach(
228 batchFilePaths(retainedFiles),
229 (filePaths) =>
230 checkpointStore
231 .diffCheckpoints({ ...comparison, filePaths })
232 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints")),
233 { concurrency: 4 },
234 )).join("");
235​
236 const turnDiff = buildTurnDiffResult(input, diff);
237 if (!isTurnDiffResult(turnDiff)) {
238 return yield* new CheckpointDiffResultInvalidError({
239 operation,
240 threadId: input.threadId,
241 });
242 }
243​
244 return turnDiff;
245 },
246 );
247​
248 const getFullThreadDiff: CheckpointDiffQuery["Service"]["getFullThreadDiff"] = Effect.fn(
249 "CheckpointDiffQuery.getFullThreadDiff",
250 )(function* (input) {
251 const operation = "CheckpointDiffQuery.getFullThreadDiff";
252 const ignoreWhitespace = input.ignoreWhitespace ?? true;
253 yield* Effect.annotateCurrentSpan({
254 "checkpoint.thread_id": input.threadId,
255 "checkpoint.from_turn_count": 0,
256 "checkpoint.to_turn_count": input.toTurnCount,
257 "checkpoint.ignore_whitespace": ignoreWhitespace,
258 "checkpoint.diff_kind": "full-thread",
259 });
260​
261 if (input.toTurnCount === 0) {
262 const emptyDiff = buildTurnDiffResult(
263 {
264 threadId: input.threadId,
265 fromTurnCount: 0,
266 toTurnCount: 0,
267 },
268 "",
269 );
270 if (!isTurnDiffResult(emptyDiff)) {
271 return yield* new CheckpointDiffResultInvalidError({
272 operation,
273 threadId: input.threadId,
274 });
275 }
276 return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
277 }
278​
279 const turnDiff = yield* getTurnDiff({
280 threadId: input.threadId,
281 fromTurnCount: 0,
282 toTurnCount: input.toTurnCount,
283 ignoreWhitespace,
284 });
285 if (!isTurnDiffResult(turnDiff)) {
286 return yield* new CheckpointDiffResultInvalidError({
287 operation,
288 threadId: input.threadId,
289 });
290 }
291​
292 return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
293 });
294​
295 return CheckpointDiffQuery.of({
296 getTurnDiff,
297 getFullThreadDiff,
298 });
299});
300​
301export const layer = Layer.effect(CheckpointDiffQuery, make);