Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointScopeId,
4 type CommandId,
5 latestProviderTurnForAttempt,
6 type OrchestrationV2DomainEvent,
7 ProviderThreadId,
8 repositoryRewindCheckpoint,
9 ThreadId,
10 VcsProcessExitError,
11} from "@t3tools/contracts";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21
22import * as GitWorkflowService from "../git/GitWorkflowService.ts";
23import type * as ServerConfig from "../config.ts";
24import type * as ServerSettings from "../serverSettings.ts";
25import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
26import * as TaskFolders from "../workspace/TaskFolders.ts";
27import {
28 withCheckpointRestoreReservation,
29 withWorkspaceLease,
30} from "../workspace/workspaceLease.ts";
31import {
32 isCheckpointRestoreIsolated,
33 SHARED_WORKSPACE_RESTORE_MESSAGE,
34} from "./CheckpointRestoreSafety.ts";
35import { CheckpointRestoreError, CheckpointServiceV2 } from "./CheckpointService.ts";
36import { EventSinkV2 } from "./EventSink.ts";
37import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38import { ProjectionStoreV2 } from "./ProjectionStore.ts";
39import { GIT_INDEX_LOCKED_DETAIL } from "../vcs/VcsProcess.ts";
40import * as ProjectStore from "./ProjectStore.ts";
41import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
42import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
43import { RuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts";
44import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
45
46export const ROLLBACK_FAILED_MESSAGE =
47 "The provider could not roll back this conversation. Try again; if it keeps failing, check the provider and server logs.";
48
49export class CheckpointRollbackExecutionError extends Schema.TaggedError<CheckpointRollbackExecutionError>()(
50 "CheckpointRollbackExecutionError",
51 {
52 reason: Schema.Literals([
53 "rollback-target-invalid",
54 "active-provider-changed",
55 "provider-turn-unavailable",
56 "unexpected-failure",
57 "shared-workspace",
58 ]),
59 threadId: ThreadId,
60 providerThreadId: ProviderThreadId,
61 checkpointId: CheckpointId,
62 cause: Schema.optional(Schema.Defect()),
63 },
64) {
65 override get message(): string {
66 switch (this.reason) {
67 case "rollback-target-invalid":
68 return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`;
69 case "active-provider-changed":
70 return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
71 case "provider-turn-unavailable":
72 return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
73 case "shared-workspace":
74 return SHARED_WORKSPACE_RESTORE_MESSAGE;
75 case "unexpected-failure":
76 return ROLLBACK_FAILED_MESSAGE;
77 }
78 }
79}
80
81const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
82const isVcsProcessExitError = Schema.is(VcsProcessExitError);
83const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
84const isRuntimePolicyAboveCeilingError = Schema.is(RuntimePolicyAboveCeilingError);
85
86/**
87 * The message clients see when a rollback fails. Only a held Git index lock
88 * gets its own explanation; other reasons carry internal ids or raw Git
89 * output, so they fall back to the generic message.
90 */
91export function rollbackFailureClientMessage(error: CheckpointRollbackExecutionError): string {
92 if (isRuntimePolicyAboveCeilingError(error.cause)) return error.cause.message;
93 const restoreCause = isCheckpointRestoreError(error.cause) ? error.cause.cause : undefined;
94 return isVcsProcessExitError(restoreCause) && restoreCause.detail === GIT_INDEX_LOCKED_DETAIL
95 ? GIT_INDEX_LOCKED_DETAIL
96 : ROLLBACK_FAILED_MESSAGE;
97}
98
99export interface CheckpointRollbackServiceV2Shape {
100 readonly execute: (input: {
101 readonly threadId: ThreadId;
102 readonly providerThreadId: ProviderThreadId;
103 readonly checkpointId: CheckpointId;
104 readonly scopeId: CheckpointScopeId;
105 readonly restoreFiles?: boolean;
106 /** The rewind command: names the request when repositories are reported as left unrestored. */
107 readonly requestId?: CommandId;
108 }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
109}
110
111export class CheckpointRollbackServiceV2 extends Context.Service<
112 CheckpointRollbackServiceV2,
113 CheckpointRollbackServiceV2Shape
114>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
115
116export const layer: Layer.Layer<
117 CheckpointRollbackServiceV2,
118 never,
119 | CheckpointServiceV2
120 | GitWorkflowService.GitWorkflowService
121 | EventSinkV2
122 | IdAllocator.IdAllocatorV2
123 | ProjectionStoreV2
124 | ProviderSessionManagerV2
125 | RuntimePolicyV2
126 | FileSystem.FileSystem
127 | Path.Path
128 | ProjectStore.ProjectStoreV2
129 | ServerConfig.ServerConfig
130 | ServerSettings.ServerSettingsService
131 | TaskFolders.TaskFolders
132 | ThreadCommandExecutor.ThreadCommandExecutor
133> = Layer.effect(
134 CheckpointRollbackServiceV2,
135 Effect.gen(function* () {
136 const checkpoints = yield* CheckpointServiceV2;
137 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
138 const eventSink = yield* EventSinkV2;
139 const ids = yield* IdAllocator.IdAllocatorV2;
140 const projections = yield* ProjectionStoreV2;
141 const sessions = yield* ProviderSessionManagerV2;
142 const runtimePolicy = yield* RuntimePolicyV2;
143 const fileSystem = yield* FileSystem.FileSystem;
144 const projects = yield* ProjectStore.ProjectStoreV2;
145 const path = yield* Path.Path;
146 const taskFolders = yield* TaskFolders.TaskFolders;
147 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
148 const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
149
150 const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
151 readonly threadId: ThreadId;
152 readonly providerThreadId: ProviderThreadId;
153 readonly checkpointId: CheckpointId;
154 readonly scopeId: CheckpointScopeId;
155 readonly restoreFiles?: boolean;
156 readonly requestId?: CommandId;
157 }) {
158 const context = yield* projections.getCheckpointRollbackContext(input.threadId, input);
159 if (context.thread.deletedAt !== null) return;
160 const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } =
161 context;
162 const restoreFiles = input.restoreFiles !== false;
163 const { worktreePath, branch } = context.thread;
164 const taskFolder = worktreePath === null ? null : yield* taskFolders.find(worktreePath);
165 // A linked project folder is not a repository: it has no snapshot, by design.
166 const linkedProjectFolder = taskFolder !== null && !taskFolder.projectIsWorktree;
167 const invalidTarget = () =>
168 new CheckpointRollbackExecutionError({
169 reason: "rollback-target-invalid",
170 threadId: input.threadId,
171 providerThreadId: input.providerThreadId,
172 checkpointId: input.checkpointId,
173 });
174 if (
175 providerThread === undefined ||
176 providerThread.providerSessionId === null ||
177 checkpoint === undefined ||
178 scope === undefined ||
179 // A repository's checkpoints follow the thread's; they are not a place to rewind to.
180 typeof scope.repositoryPath === "string" ||
181 checkpoint.scopeId !== scope.id ||
182 // Missing or failed snapshots support conversation rewind; missing ones also restoring a
183 // task folder's repositories.
184 (checkpoint.status !== "ready" &&
185 !(checkpoint.status === "error" && !restoreFiles) &&
186 !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder)))
187 ) {
188 return yield* invalidTarget();
189 }
190 if (
191 providerThread.id !== context.thread.activeProviderThreadId ||
192 providerThread.providerInstanceId !== context.thread.modelSelection.instanceId
193 ) {
194 return yield* new CheckpointRollbackExecutionError({
195 reason: "active-provider-changed",
196 threadId: input.threadId,
197 providerThreadId: input.providerThreadId,
198 checkpointId: input.checkpointId,
199 });
200 }
201
202 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
203 const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget =
204 targetOrdinal === 0
205 ? {
206 type: "thread_start",
207 checkpointId: checkpoint.id,
208 appRunOrdinal: 0,
209 }
210 : yield* Effect.gen(function* () {
211 const targetTurn =
212 latestProviderTurnForAttempt(context.providerTurns, targetAttempt?.id) ??
213 context.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
214 if (
215 targetAttempt === undefined ||
216 targetTurn === undefined ||
217 targetTurn.providerThreadId !== providerThread.id
218 ) {
219 return yield* new CheckpointRollbackExecutionError({
220 reason: "provider-turn-unavailable",
221 threadId: input.threadId,
222 providerThreadId: input.providerThreadId,
223 checkpointId: input.checkpointId,
224 });
225 }
226 const { attempt } = yield* projections.getProviderControlContext(input.threadId, {
227 providerThreadId: providerThread.id,
228 providerTurnId: targetTurn.id,
229 attemptId: targetAttempt.id,
230 });
231 const message =
232 attempt === undefined
233 ? undefined
234 : yield* projections.getRunMessage(input.threadId, attempt.runId);
235 return {
236 type: "provider_turn" as const,
237 checkpointId: checkpoint.id,
238 appRunOrdinal: targetOrdinal,
239 providerTurn: targetTurn,
240 ...(message === undefined ? {} : { message }),
241 };
242 });
243
244 const isolated = isCheckpointRestoreIsolated(context.thread, scope, taskFolder, {
245 fileSystem,
246 projections,
247 projects,
248 path,
249 });
250 const sharedWorkspace = () =>
251 new CheckpointRollbackExecutionError({
252 reason: "shared-workspace",
253 threadId: input.threadId,
254 providerThreadId: input.providerThreadId,
255 checkpointId: input.checkpointId,
256 });
257
258 if (taskFolder !== null && branch != null) {
259 // Cleanup can remove any of the folder's checkouts; the linked project folder has none.
260 yield* taskFolders.restore({
261 taskFolder,
262 branch,
263 projectCommands: TaskFolders.projectCommandsForLink(context.thread.linkOrigin),
264 recreate: (checkout) =>
265 gitWorkflow.pruneWorktrees({ cwd: checkout.repositoryPath }).pipe(
266 Effect.andThen(
267 gitWorkflow.createWorktree({
268 cwd: checkout.repositoryPath,
269 refName: branch,
270 path: checkout.worktreePath,
271 }),
272 ),
273 ),
274 });
275 } else if (worktreePath != null && branch != null) {
276 // Recreated only where the server would have made it, as turn start does.
277 // A failed removal can leave the folder without its checkout; only a file restore replaces it.
278 const leftover =
279 restoreFiles &&
280 (yield* fileSystem.exists(worktreePath)) &&
281 !(yield* fileSystem.exists(path.join(worktreePath, ".git")));
282 if (
283 (leftover || !(yield* fileSystem.exists(worktreePath))) &&
284 (yield* isManagedWorktreePath(worktreePath))
285 ) {
286 const project = yield* projects.get(context.thread.projectId);
287 if (Option.isSome(project)) {
288 const recreate = gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }).pipe(
289 Effect.andThen(
290 gitWorkflow.createWorktree({
291 cwd: project.value.workspaceRoot,
292 refName: branch,
293 path: worktreePath,
294 }),
295 ),
296 );
297 if (leftover) {
298 if (!(yield* isolated)) return yield* sharedWorkspace();
299 // Set aside, not removed: a checkout that fails puts the folder and its files back.
300 yield* Effect.acquireUseRelease(
301 Effect.gen(function* () {
302 const aside = yield* fileSystem.makeTempDirectory({
303 directory: path.dirname(worktreePath),
304 prefix: ".t3-replaced-",
305 });
306 yield* fileSystem.rename(worktreePath, path.join(aside, "folder"));
307 return aside;
308 }),
309 () => recreate,
310 (aside, exit) =>
311 (Exit.isSuccess(exit)
312 ? Effect.void
313 : fileSystem
314 .remove(worktreePath, { recursive: true, force: true })
315 .pipe(
316 Effect.andThen(
317 fileSystem.rename(path.join(aside, "folder"), worktreePath),
318 ),
319 )
320 ).pipe(
321 Effect.andThen(fileSystem.remove(aside, { recursive: true, force: true })),
322 Effect.catchCause((cause) =>
323 Effect.logWarning("Edit from here left a worktree folder set aside", {
324 worktreePath,
325 setAside: path.join(aside, "folder"),
326 cause,
327 }),
328 ),
329 ),
330 );
331 } else {
332 yield* recreate;
333 }
334 }
335 }
336 }
337
338 if (restoreFiles && !(yield* isolated)) return yield* sharedWorkspace();
339
340 // Before the provider conversation changes: a rewind with nothing to restore is refused.
341 const readable =
342 restoreFiles && taskFolder !== null
343 ? yield* checkpoints.repositoryScopesIfReadable({
344 rootScope: scope,
345 projectId: context.thread.projectId,
346 worktreePath,
347 })
348 : [];
349 // Unknown repositories are not "none": the rewind would leave their changes unmentioned.
350 if (readable === null) {
351 return yield* new CheckpointRollbackExecutionError({
352 reason: "unexpected-failure",
353 threadId: input.threadId,
354 providerThreadId: input.providerThreadId,
355 checkpointId: input.checkpointId,
356 cause: new Error("The thread's repositories could not be read."),
357 });
358 }
359 const repositories = readable;
360 const recorded =
361 repositories.length === 0
362 ? []
363 : (yield* projections.getCheckpointContext(input.threadId)).checkpoints;
364 const repositoryTargets = repositories.flatMap((repository) => {
365 const target = repositoryRewindCheckpoint(
366 recorded.filter((candidate) => candidate.scopeId === repository.id),
367 targetOrdinal,
368 );
369 return target === null ? [] : [{ scope: repository, checkpoint: target }];
370 });
371 // Changed by a discarded run, with no snapshot of how it was before: left as it is.
372 const unrestorable = repositories.filter(
373 (repository) =>
374 !repositoryTargets.some((target) => target.scope.id === repository.id) &&
375 recorded.some(
376 (candidate) =>
377 candidate.scopeId === repository.id &&
378 candidate.ordinalWithinScope > targetOrdinal &&
379 (candidate.status === "ready" || candidate.runId !== null),
380 ),
381 );
382 if (unrestorable.length > 0) {
383 yield* Effect.logWarning("Edit from here cannot restore repositories without a snapshot", {
384 threadId: input.threadId,
385 repositories: unrestorable.map((repository) => repository.cwd),
386 });
387 }
388 const restoreTargets = [
389 ...(checkpoint.status === "ready" ? [{ scope, checkpoint }] : []),
390 ...repositoryTargets,
391 ];
392 if (restoreFiles && restoreTargets.length === 0) return yield* invalidTarget();
393
394 const modelSelection = context.thread.modelSelection;
395 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
396 thread: context.thread,
397 modelSelection,
398 });
399 const existingSession = context.providerSession;
400 const session = yield* sessions.open({
401 threadId: input.threadId,
402 providerSessionId: providerThread.providerSessionId,
403 modelSelection,
404 runtimePolicy: resolvedRuntimePolicy,
405 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
406 ...(providerThread.nativeThreadRef?.nativeId == null
407 ? {}
408 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
409 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
410 ? {}
411 : {
412 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
413 }),
414 });
415
416 // Rolled-back turns remain in audit history but no longer exist in the provider conversation.
417 const rolledBackAttemptIds = new Set(context.rolledBackAttemptIds);
418 const providerThreadTurns = context.providerTurns.filter(
419 (turn) =>
420 turn.providerThreadId === providerThread.id &&
421 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
422 );
423
424 const snapshot =
425 runsToRollback.length === 0
426 ? { providerThread }
427 : yield* session.rollbackThread({
428 providerThread,
429 target: rollbackTarget,
430 providerThreadTurns,
431 });
432 if (restoreFiles) {
433 yield* checkpoints.restore({ targets: restoreTargets, scopes: [scope, ...repositories] });
434 }
435 const staleScopeCheckpoints = staleCheckpoints.filter((stale) => stale.scopeId === scope.id);
436 if (staleScopeCheckpoints.length > 0) {
437 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleScopeCheckpoints });
438 }
439 yield* checkpoints.discardRepositorySnapshots({
440 rootScope: scope,
441 thread: context.thread,
442 ordinals: runsToRollback.map((run) => run.ordinal),
443 });
444
445 // Lock against full-row thread writes that could restore the old native session after rollback.
446 yield* threadCommands.withLock(
447 input.threadId,
448 Effect.gen(function* () {
449 const now = yield* DateTime.now;
450 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
451 Effect.map(
452 ids.allocate.event({ threadId: event.threadId }),
453 (id) =>
454 ({
455 ...event,
456 id,
457 }) as Event,
458 );
459 const events: Array<OrchestrationV2DomainEvent> = [];
460 // First, so a client that sees the runs rolled back already knows what was left.
461 if (input.requestId !== undefined && unrestorable.length > 0) {
462 const thread = yield* projections.getThread(input.threadId);
463 events.push(
464 yield* makeEvent({
465 type: "thread.metadata-updated",
466 threadId: input.threadId,
467 providerInstanceId: thread.providerInstanceId,
468 occurredAt: now,
469 payload: {
470 ...thread,
471 rollbackUnrestored: {
472 requestId: input.requestId,
473 repositories: unrestorable.map(
474 (repository) => repository.label ?? path.basename(repository.cwd),
475 ),
476 },
477 updatedAt: now,
478 },
479 }),
480 );
481 }
482 events.push(
483 yield* makeEvent({
484 type: "provider-thread.updated",
485 threadId: input.threadId,
486 driver: providerThread.driver,
487 providerInstanceId: providerThread.providerInstanceId,
488 occurredAt: now,
489 payload: {
490 ...snapshot.providerThread,
491 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
492 updatedAt: now,
493 },
494 }),
495 );
496 for (const staleCheckpoint of staleCheckpoints) {
497 events.push(
498 yield* makeEvent({
499 type: "checkpoint.captured",
500 threadId: input.threadId,
501 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
502 nodeId: staleCheckpoint.nodeId,
503 providerInstanceId: providerThread.providerInstanceId,
504 occurredAt: now,
505 payload: { ...staleCheckpoint, status: "stale" },
506 }),
507 );
508 }
509 for (const run of runsToRollback) {
510 const rootNode = context.rootNodes.find((candidate) => candidate.id === run.rootNodeId);
511 events.push(
512 yield* makeEvent({
513 type: "run.updated",
514 threadId: input.threadId,
515 runId: run.id,
516 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
517 providerInstanceId: run.providerInstanceId,
518 occurredAt: now,
519 payload: { ...run, status: "rolled_back", completedAt: now },
520 }),
521 );
522 if (rootNode !== undefined) {
523 events.push(
524 yield* makeEvent({
525 type: "node.updated",
526 threadId: input.threadId,
527 runId: run.id,
528 nodeId: rootNode.id,
529 providerInstanceId: run.providerInstanceId,
530 occurredAt: now,
531 payload: { ...rootNode, status: "rolled_back", completedAt: now },
532 }),
533 );
534 }
535 }
536 yield* eventSink.write({ events });
537 }),
538 );
539 });
540
541 return CheckpointRollbackServiceV2.of({
542 // The inner execute owns the rollback span; this wrapper selects the workspace lease.
543 execute: Effect.fnUntraced(
544 function* (input) {
545 // Storage cleanup removes worktrees under the same lease.
546 const thread = yield* projections.getThread(input.threadId);
547 if (thread.worktreePath === null) return yield* execute(input);
548 const worktreePath = path.resolve(thread.worktreePath);
549 const rollback = withWorkspaceLease(worktreePath, execute(input));
550 // Shared-workspace restores are rejected and conversation-only rewinds
551 // touch no files; reserving for them would stall turn starts on the
552 // slow provider rollback for nothing.
553 yield* input.restoreFiles === false
554 ? rollback
555 : withCheckpointRestoreReservation(fileSystem, path, worktreePath, rollback);
556 },
557 (effect, input) =>
558 effect.pipe(
559 Effect.mapError((cause) =>
560 isCheckpointRollbackExecutionError(cause)
561 ? cause
562 : new CheckpointRollbackExecutionError({
563 reason: "unexpected-failure",
564 threadId: input.threadId,
565 providerThreadId: input.providerThreadId,
566 checkpointId: input.checkpointId,
567 cause,
568 }),
569 ),
570 ),
571 ),
572 });
573 }),
574);