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

CheckpointDiffQuery.ts

285 lines9.6 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 const firstScope =
165 input.fromTurnCount === 0
166 ? projection.checkpointScopes.find((scope) => scope.kind === "root_run")
167 : undefined;
168 const fromCheckpointRef =
169 input.fromTurnCount === 0
170 ? firstScope === undefined
171 ? undefined
172 : yield* checkpointRefForScopeOrdinal({
173 scopeId: firstScope.id,
174 ordinalWithinScope: 0,
175 }).pipe(Effect.provideService(Crypto.Crypto, crypto))
176 : readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)
177 ?.ref;
178 if (fromCheckpointRef === undefined) {
179 return yield* new CheckpointRefUnavailableError({
180 operation,
181 threadId: input.threadId,
182 turnCount: input.fromTurnCount,
183 checkpoint: "from",
184 });
185 }
186​
187 const comparison = {
188 cwd: toScope.cwd,
189 fromCheckpointRef,
190 toCheckpointRef: toCheckpoint.ref,
191 fallbackFromToHead: false,
192 ignoreWhitespace,
193 };
194 const authoredPaths = yield* checkpointStore
195 .listAuthoredPaths(comparison)
196 .pipe(Effect.orElseSucceed(() => null));
197 const files =
198 authoredPaths === null
199 ? []
200 : yield* checkpointStore.diffCheckpoints({ ...comparison, format: "numstat" }).pipe(
201 Effect.map(parseTurnDiffFilesFromNumstat),
202 Effect.orElseSucceed(() => []),
203 );
204 const retainedFiles = files.filter((file) => !isGitImport(file, authoredPaths));
205 // Select retained paths before generating a patch, so imported bulk cannot exhaust its output limit.
206 const diff =
207 retainedFiles.length === files.length
208 ? yield* checkpointStore
209 .diffCheckpoints(comparison)
210 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"))
211 : (yield* Effect.forEach(
212 batchFilePaths(retainedFiles),
213 (filePaths) =>
214 checkpointStore
215 .diffCheckpoints({ ...comparison, filePaths })
216 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints")),
217 { concurrency: 4 },
218 )).join("");
219​
220 const turnDiff = buildTurnDiffResult(input, diff);
221 if (!isTurnDiffResult(turnDiff)) {
222 return yield* new CheckpointDiffResultInvalidError({
223 operation,
224 threadId: input.threadId,
225 });
226 }
227​
228 return turnDiff;
229 },
230 );
231​
232 const getFullThreadDiff: CheckpointDiffQuery["Service"]["getFullThreadDiff"] = Effect.fn(
233 "CheckpointDiffQuery.getFullThreadDiff",
234 )(function* (input) {
235 const operation = "CheckpointDiffQuery.getFullThreadDiff";
236 const ignoreWhitespace = input.ignoreWhitespace ?? true;
237 yield* Effect.annotateCurrentSpan({
238 "checkpoint.thread_id": input.threadId,
239 "checkpoint.from_turn_count": 0,
240 "checkpoint.to_turn_count": input.toTurnCount,
241 "checkpoint.ignore_whitespace": ignoreWhitespace,
242 "checkpoint.diff_kind": "full-thread",
243 });
244​
245 if (input.toTurnCount === 0) {
246 const emptyDiff = buildTurnDiffResult(
247 {
248 threadId: input.threadId,
249 fromTurnCount: 0,
250 toTurnCount: 0,
251 },
252 "",
253 );
254 if (!isTurnDiffResult(emptyDiff)) {
255 return yield* new CheckpointDiffResultInvalidError({
256 operation,
257 threadId: input.threadId,
258 });
259 }
260 return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
261 }
262​
263 const turnDiff = yield* getTurnDiff({
264 threadId: input.threadId,
265 fromTurnCount: 0,
266 toTurnCount: input.toTurnCount,
267 ignoreWhitespace,
268 });
269 if (!isTurnDiffResult(turnDiff)) {
270 return yield* new CheckpointDiffResultInvalidError({
271 operation,
272 threadId: input.threadId,
273 });
274 }
275​
276 return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
277 });
278​
279 return CheckpointDiffQuery.of({
280 getTurnDiff,
281 getFullThreadDiff,
282 });
283});
284​
285export const layer = Layer.effect(CheckpointDiffQuery, make);