Open History to see the last commit
1import {
2 CHECKPOINT_DIFF_TRUNCATED_MARKER,
3 type CheckpointRef,
4 OrchestrationGetTurnDiffResult,
5 type OrchestrationGetFullThreadDiffInput,
6 type OrchestrationGetFullThreadDiffResult,
7 type OrchestrationGetTurnDiffInput,
8 type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
9 type ThreadId,
10 type ThreadTurnRepositoryDiff,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as Digest from "effect/crypto/Digest";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19
20import { CHECKPOINT_DIFF_MAX_OUTPUT_BYTES } from "../vcs/VcsDriver.ts";
21import {
22 checkpointRefForScopeOrdinal,
23 nestedScopePaths,
24} from "../orchestration-v2/CheckpointService.ts";
25import type { ProjectionCheckpointContext } from "../orchestration-v2/ProjectionStore.ts";
26import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
27import {
28 CheckpointDiffResultInvalidError,
29 CheckpointRefUnavailableError,
30 CheckpointThreadNotFoundError,
31 CheckpointTurnRangeUnavailableError,
32 CheckpointWorkspacePathMissingError,
33 type CheckpointServiceError,
34} from "./Errors.ts";
35import * as CheckpointStore from "./CheckpointStore.ts";
36import { isGitImport, parseTurnDiffFilesFromNumstat, type TurnDiffFileSummary } from "./Diffs.ts";
37
38// Windows limits a command line to 32,767 characters. Leave room for the rest of git's arguments.
39const MAX_PATHSPEC_CHARS = 24_000;
40const REPOSITORY_DIFF_CONCURRENCY = 6;
41
42function batchFilePaths(files: ReadonlyArray<TurnDiffFileSummary>) {
43 const batches: string[][] = [];
44 let batch: string[] = [];
45 let length = 0;
46 for (const file of files) {
47 const paths = file.previousPath === undefined ? [file.path] : [file.previousPath, file.path];
48 const size = paths.reduce((total, path) => total + path.length + 16, 0);
49 if (batch.length > 0 && length + size > MAX_PATHSPEC_CHARS) {
50 batches.push(batch);
51 batch = [];
52 length = 0;
53 }
54 batch.push(...paths);
55 length += size;
56 }
57 if (batch.length > 0) batches.push(batch);
58 return batches;
59}
60
61export class CheckpointDiffQuery extends Context.Service<
62 CheckpointDiffQuery,
63 {
64 readonly getTurnDiff: (
65 input: OrchestrationGetTurnDiffInput,
66 ) => Effect.Effect<OrchestrationGetTurnDiffResultType, CheckpointServiceError>;
67
68 readonly getFullThreadDiff: (
69 input: OrchestrationGetFullThreadDiffInput,
70 ) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
71 }
72>()("t3/checkpointing/CheckpointDiffQuery") {}
73
74const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
75
76function buildTurnDiffResult(
77 input: {
78 readonly threadId: ThreadId;
79 readonly fromTurnCount: number;
80 readonly toTurnCount: number;
81 },
82 diff: string,
83 repositories?: ReadonlyArray<ThreadTurnRepositoryDiff>,
84): OrchestrationGetTurnDiffResultType {
85 return {
86 threadId: input.threadId,
87 fromTurnCount: input.fromTurnCount,
88 toTurnCount: input.toTurnCount,
89 diff,
90 ...(repositories === undefined ? {} : { repositories }),
91 };
92}
93
94type ContextCheckpoint = ProjectionCheckpointContext["checkpoints"][number];
95
96/**
97 * A repository's checkpoints for a turn range. Only turns that changed it are recorded, each with
98 * the baseline before it, so the range runs from its first record to its last one inside the
99 * range. None when no turn in the range changed it.
100 */
101function repositoryDiffRange(
102 checkpoints: ReadonlyArray<ContextCheckpoint>,
103 range: { readonly fromTurnCount: number; readonly toTurnCount: number },
104): { readonly from: ContextCheckpoint; readonly to: ContextCheckpoint } | undefined {
105 const ready = checkpoints
106 .filter(
107 (checkpoint) =>
108 checkpoint.status === "ready" &&
109 checkpoint.ordinalWithinScope >= range.fromTurnCount &&
110 checkpoint.ordinalWithinScope <= range.toTurnCount,
111 )
112 .toSorted((left, right) => left.ordinalWithinScope - right.ordinalWithinScope);
113 const from = ready[0];
114 const to = ready.at(-1);
115 return from === undefined || to === undefined || from === to ? undefined : { from, to };
116}
117
118/** @public */
119export const make = Effect.gen(function* () {
120 const threads = yield* ThreadManagement.ThreadManagementService;
121 const checkpointStore = yield* CheckpointStore.CheckpointStore;
122 const digest = yield* Digest.Digest;
123 const fileSystem = yield* FileSystem.FileSystem;
124 const path = yield* Path.Path;
125
126 interface Comparison {
127 readonly cwd: string;
128 readonly fromCheckpointRef: CheckpointRef;
129 readonly toCheckpointRef: CheckpointRef;
130 readonly fallbackFromToHead: false;
131 readonly ignoreWhitespace: boolean;
132 readonly excludePaths?: ReadonlyArray<string>;
133 }
134
135 // What a pull or rebase brought in is not the turn's work. Null keeps every changed file.
136 const retainedFilePaths = Effect.fn("CheckpointDiffQuery.retainedFilePaths")(function* (
137 comparison: Comparison,
138 ) {
139 const authoredPaths = yield* checkpointStore
140 .listAuthoredPaths(comparison)
141 .pipe(Effect.orElseSucceed(() => null));
142 const files =
143 authoredPaths === null
144 ? []
145 : yield* checkpointStore.diffCheckpoints({ ...comparison, format: "numstat" }).pipe(
146 Effect.map(parseTurnDiffFilesFromNumstat),
147 Effect.orElseSucceed(() => []),
148 );
149 const retainedFiles = files.filter((file) => !isGitImport(file, authoredPaths));
150 return retainedFiles.length === files.length ? null : retainedFiles;
151 });
152
153 // Selects retained paths before generating a patch, so imported bulk cannot exhaust the limit.
154 const patchBetween = Effect.fn("CheckpointDiffQuery.patchBetween")(function* (
155 comparison: Comparison,
156 maxBytes: number,
157 ) {
158 const retainedFiles = yield* retainedFilePaths(comparison);
159 const pathBatches = retainedFiles === null ? [undefined] : batchFilePaths(retainedFiles);
160 let diff = "";
161 let remainingBytes = maxBytes;
162 for (const filePaths of pathBatches) {
163 const patch = yield* checkpointStore
164 .diffCheckpoints({
165 ...comparison,
166 ...(filePaths === undefined ? {} : { filePaths }),
167 // One extra byte distinguishes an exact fit from a truncated patch.
168 maxOutputBytes: remainingBytes + 1,
169 })
170 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
171 const patchBytes = Buffer.byteLength(patch);
172 diff += patch;
173 if (patchBytes > remainingBytes) {
174 // Reserve marker space only on overflow, which may trim an earlier batch.
175 // Streaming decode drops an incomplete final UTF-8 character at the byte boundary.
176 diff =
177 new TextDecoder().decode(
178 Buffer.from(diff).subarray(
179 0,
180 Math.max(0, maxBytes - Buffer.byteLength(CHECKPOINT_DIFF_TRUNCATED_MARKER)),
181 ),
182 { stream: true },
183 ) + CHECKPOINT_DIFF_TRUNCATED_MARKER;
184 break;
185 }
186 remainingBytes -= patchBytes;
187 }
188 return diff;
189 });
190
191 // Most tracked repositories are untouched in a turn. A numstat finds the few that changed
192 // before any patch is built, and those patches then share what the thread's own patch left.
193 const repositoryDiffs = Effect.fn("CheckpointDiffQuery.repositoryDiffs")(function* (input: {
194 readonly projection: ProjectionCheckpointContext;
195 readonly threadCwd: string;
196 readonly fromTurnCount: number;
197 readonly toTurnCount: number;
198 readonly ignoreWhitespace: boolean;
199 readonly nested: ReadonlyMap<string, ReadonlyArray<string>>;
200 readonly maxBytes: number;
201 }) {
202 const changed = yield* Effect.forEach(
203 input.projection.checkpointScopes.filter((scope) => typeof scope.repositoryPath === "string"),
204 (scope) => {
205 const range = repositoryDiffRange(
206 input.projection.checkpoints.filter((checkpoint) => checkpoint.scopeId === scope.id),
207 input,
208 );
209 if (range === undefined) return Effect.succeed([]);
210 const excludePaths = input.nested.get(scope.id);
211 const comparison: Comparison = {
212 cwd: scope.cwd,
213 fromCheckpointRef: range.from.ref,
214 toCheckpointRef: range.to.ref,
215 fallbackFromToHead: false,
216 ignoreWhitespace: input.ignoreWhitespace,
217 ...(excludePaths === undefined ? {} : { excludePaths }),
218 };
219 return checkpointStore.diffCheckpoints({ ...comparison, format: "numstat" }).pipe(
220 Effect.map((numstat) => (numstat === "" ? [] : [{ scope, comparison }])),
221 Effect.catch((cause) =>
222 Effect.logWarning("checkpoint repository diff unavailable", {
223 scopeId: scope.id,
224 cause: String(cause),
225 }).pipe(Effect.as([])),
226 ),
227 );
228 },
229 { concurrency: REPOSITORY_DIFF_CONCURRENCY },
230 );
231 const repositories: Array<ThreadTurnRepositoryDiff> = [];
232 let remainingBytes = input.maxBytes;
233 for (const { scope, comparison } of changed.flat()) {
234 const diff = yield* patchBetween(comparison, remainingBytes).pipe(
235 Effect.catch((cause) =>
236 Effect.logWarning("checkpoint repository diff unavailable", {
237 scopeId: scope.id,
238 cause: String(cause),
239 }).pipe(Effect.as("")),
240 ),
241 );
242 if (diff === "") continue;
243 remainingBytes = Math.max(0, remainingBytes - Buffer.byteLength(diff));
244 repositories.push({
245 name: scope.label ?? path.basename(scope.cwd),
246 repositoryPath: scope.repositoryPath ?? scope.cwd,
247 relativePath: path.relative(input.threadCwd, scope.cwd).split(path.sep).join("/"),
248 diff,
249 });
250 }
251 return repositories;
252 });
253
254 const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
255 function* (input) {
256 const operation = "CheckpointDiffQuery.getTurnDiff";
257 const ignoreWhitespace = input.ignoreWhitespace ?? true;
258 yield* Effect.annotateCurrentSpan({
259 "checkpoint.thread_id": input.threadId,
260 "checkpoint.from_turn_count": input.fromTurnCount,
261 "checkpoint.to_turn_count": input.toTurnCount,
262 "checkpoint.ignore_whitespace": ignoreWhitespace,
263 });
264
265 if (input.fromTurnCount === input.toTurnCount) {
266 const emptyDiff = buildTurnDiffResult(input, "");
267 if (!isTurnDiffResult(emptyDiff)) {
268 return yield* new CheckpointDiffResultInvalidError({
269 operation,
270 threadId: input.threadId,
271 });
272 }
273 return emptyDiff;
274 }
275
276 const projection = yield* threads.getCheckpointContext(input.threadId).pipe(
277 Effect.mapError(
278 () =>
279 new CheckpointThreadNotFoundError({
280 operation,
281 threadId: input.threadId,
282 }),
283 ),
284 Effect.withSpan("checkpoint.turnDiff.lookupContext"),
285 );
286 const completedRunIds = new Set(
287 projection.runs.filter((run) => run.status === "completed").map((run) => run.id),
288 );
289 const hasRepositories = projection.checkpointScopes.some(
290 (scope) => typeof scope.repositoryPath === "string",
291 );
292 // A thread folder that is not a Git repository records missing checkpoints; its turns still
293 // exist, for the repositories inside it and as an empty patch while none of them changed.
294 const turnCheckpoints = projection.checkpoints.filter(
295 (checkpoint) =>
296 (checkpoint.status === "ready" || checkpoint.status === "missing") &&
297 checkpoint.appRunOrdinal !== null &&
298 checkpoint.runId !== null &&
299 completedRunIds.has(checkpoint.runId),
300 );
301 const readyCheckpoints = turnCheckpoints.filter(
302 (checkpoint) => checkpoint.status === "ready",
303 );
304 const maxTurnCount = turnCheckpoints.reduce(
305 (max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0),
306 0,
307 );
308 if (input.toTurnCount > maxTurnCount) {
309 return yield* new CheckpointTurnRangeUnavailableError({
310 operation,
311 threadId: input.threadId,
312 requestedTurnCount: input.toTurnCount,
313 availableTurnCount: maxTurnCount,
314 });
315 }
316
317 const toCheckpoint = turnCheckpoints.find(
318 (checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount,
319 );
320 if (toCheckpoint === undefined) {
321 return yield* new CheckpointRefUnavailableError({
322 operation,
323 threadId: input.threadId,
324 turnCount: input.toTurnCount,
325 checkpoint: "to",
326 });
327 }
328
329 const toScope = projection.checkpointScopes.find(
330 (scope) => scope.id === toCheckpoint.scopeId,
331 );
332 if (toScope === undefined) {
333 return yield* new CheckpointWorkspacePathMissingError({
334 operation,
335 threadId: input.threadId,
336 });
337 }
338
339 const nested = hasRepositories
340 ? yield* nestedScopePaths([
341 toScope,
342 // A folder that became a repository after the range still belongs to the thread's patch.
343 ...projection.checkpointScopes.filter(
344 (scope) =>
345 typeof scope.repositoryPath === "string" &&
346 projection.checkpoints.some(
347 (checkpoint) =>
348 checkpoint.scopeId === scope.id &&
349 checkpoint.ordinalWithinScope <= input.toTurnCount,
350 ),
351 ),
352 ]).pipe(
353 Effect.provideService(FileSystem.FileSystem, fileSystem),
354 Effect.provideService(Path.Path, path),
355 )
356 : undefined;
357 const withRepositories = Effect.fnUntraced(function* (diff: string) {
358 const repositories =
359 nested === undefined
360 ? undefined
361 : yield* repositoryDiffs({
362 projection,
363 threadCwd: toScope.cwd,
364 fromTurnCount: input.fromTurnCount,
365 toTurnCount: input.toTurnCount,
366 ignoreWhitespace,
367 nested,
368 maxBytes: Math.max(0, CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - Buffer.byteLength(diff)),
369 });
370 const turnDiff = buildTurnDiffResult(input, diff, repositories);
371 if (!isTurnDiffResult(turnDiff)) {
372 return yield* new CheckpointDiffResultInvalidError({
373 operation,
374 threadId: input.threadId,
375 });
376 }
377 return turnDiff;
378 });
379 if (toCheckpoint.status === "missing") return yield* withRepositories("");
380
381 // Capture compares against the preceding scope ordinal, even when that
382 // checkpoint belongs to a stopped run or has no run.
383 const parentCheckpoint =
384 input.fromTurnCount === input.toTurnCount - 1
385 ? projection.checkpoints.find(
386 (checkpoint) =>
387 checkpoint.status === "ready" &&
388 checkpoint.scopeId === toCheckpoint.scopeId &&
389 checkpoint.ordinalWithinScope === toCheckpoint.ordinalWithinScope - 1,
390 )
391 : undefined;
392
393 const firstScope =
394 input.fromTurnCount === 0
395 ? projection.checkpointScopes.find((scope) => scope.kind === "root_run")
396 : undefined;
397 const fromCheckpointRef =
398 input.fromTurnCount === 0
399 ? firstScope === undefined
400 ? undefined
401 : yield* checkpointRefForScopeOrdinal({
402 scopeId: firstScope.id,
403 ordinalWithinScope: 0,
404 }).pipe(Effect.provideService(Digest.Digest, digest))
405 : (
406 parentCheckpoint ??
407 readyCheckpoints.find(
408 (checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount,
409 )
410 )?.ref;
411 if (fromCheckpointRef === undefined) {
412 return yield* new CheckpointRefUnavailableError({
413 operation,
414 threadId: input.threadId,
415 turnCount: input.fromTurnCount,
416 checkpoint: "from",
417 });
418 }
419
420 const excludePaths = nested?.get(toScope.id);
421 const diff = yield* patchBetween(
422 {
423 cwd: toScope.cwd,
424 fromCheckpointRef,
425 toCheckpointRef: toCheckpoint.ref,
426 fallbackFromToHead: false,
427 ignoreWhitespace,
428 ...(excludePaths === undefined ? {} : { excludePaths }),
429 },
430 CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
431 );
432 return yield* withRepositories(diff);
433 },
434 );
435
436 const getFullThreadDiff: CheckpointDiffQuery["Service"]["getFullThreadDiff"] = Effect.fn(
437 "CheckpointDiffQuery.getFullThreadDiff",
438 )(function* (input) {
439 const operation = "CheckpointDiffQuery.getFullThreadDiff";
440 const ignoreWhitespace = input.ignoreWhitespace ?? true;
441 yield* Effect.annotateCurrentSpan({
442 "checkpoint.thread_id": input.threadId,
443 "checkpoint.from_turn_count": 0,
444 "checkpoint.to_turn_count": input.toTurnCount,
445 "checkpoint.ignore_whitespace": ignoreWhitespace,
446 "checkpoint.diff_kind": "full-thread",
447 });
448
449 if (input.toTurnCount === 0) {
450 const emptyDiff = buildTurnDiffResult(
451 {
452 threadId: input.threadId,
453 fromTurnCount: 0,
454 toTurnCount: 0,
455 },
456 "",
457 );
458 if (!isTurnDiffResult(emptyDiff)) {
459 return yield* new CheckpointDiffResultInvalidError({
460 operation,
461 threadId: input.threadId,
462 });
463 }
464 return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
465 }
466
467 const turnDiff = yield* getTurnDiff({
468 threadId: input.threadId,
469 fromTurnCount: 0,
470 toTurnCount: input.toTurnCount,
471 ignoreWhitespace,
472 });
473 if (!isTurnDiffResult(turnDiff)) {
474 return yield* new CheckpointDiffResultInvalidError({
475 operation,
476 threadId: input.threadId,
477 });
478 }
479
480 return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
481 });
482
483 return CheckpointDiffQuery.of({
484 getTurnDiff,
485 getFullThreadDiff,
486 });
487});
488
489export const layer = Layer.effect(CheckpointDiffQuery, make);