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 const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } =
160 context;
161 const restoreFiles = input.restoreFiles !== false;
162 const { worktreePath, branch } = context.thread;
163 const taskFolder = worktreePath === null ? null : yield* taskFolders.find(worktreePath);
164 // A linked project folder is not a repository: it has no snapshot, by design.
165 const linkedProjectFolder = taskFolder !== null && !taskFolder.projectIsWorktree;
166 const invalidTarget = () =>
167 new CheckpointRollbackExecutionError({
168 reason: "rollback-target-invalid",
169 threadId: input.threadId,
170 providerThreadId: input.providerThreadId,
171 checkpointId: input.checkpointId,
172 });
173 if (
174 providerThread === undefined ||
175 providerThread.providerSessionId === null ||
176 checkpoint === undefined ||
177 scope === undefined ||
178 // A repository's checkpoints follow the thread's; they are not a place to rewind to.
179 typeof scope.repositoryPath === "string" ||
180 checkpoint.scopeId !== scope.id ||
181 // Missing snapshots support conversation rewind, and restoring a task folder's repositories.
182 (checkpoint.status !== "ready" &&
183 !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder)))
184 ) {
185 return yield* invalidTarget();
186 }
187 if (
188 providerThread.id !== context.thread.activeProviderThreadId ||
189 providerThread.providerInstanceId !== context.thread.modelSelection.instanceId
190 ) {
191 return yield* new CheckpointRollbackExecutionError({
192 reason: "active-provider-changed",
193 threadId: input.threadId,
194 providerThreadId: input.providerThreadId,
195 checkpointId: input.checkpointId,
196 });
197 }
198
199 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
200 const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget =
201 targetOrdinal === 0
202 ? {
203 type: "thread_start",
204 checkpointId: checkpoint.id,
205 appRunOrdinal: 0,
206 }
207 : yield* Effect.gen(function* () {
208 const targetTurn =
209 latestProviderTurnForAttempt(context.providerTurns, targetAttempt?.id) ??
210 context.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
211 if (
212 targetAttempt === undefined ||
213 targetTurn === undefined ||
214 targetTurn.providerThreadId !== providerThread.id
215 ) {
216 return yield* new CheckpointRollbackExecutionError({
217 reason: "provider-turn-unavailable",
218 threadId: input.threadId,
219 providerThreadId: input.providerThreadId,
220 checkpointId: input.checkpointId,
221 });
222 }
223 const { attempt } = yield* projections.getProviderControlContext(input.threadId, {
224 providerThreadId: providerThread.id,
225 providerTurnId: targetTurn.id,
226 attemptId: targetAttempt.id,
227 });
228 const message =
229 attempt === undefined
230 ? undefined
231 : yield* projections.getRunMessage(input.threadId, attempt.runId);
232 return {
233 type: "provider_turn" as const,
234 checkpointId: checkpoint.id,
235 appRunOrdinal: targetOrdinal,
236 providerTurn: targetTurn,
237 ...(message === undefined ? {} : { message }),
238 };
239 });
240
241 const isolated = isCheckpointRestoreIsolated(context.thread, scope, taskFolder, {
242 fileSystem,
243 projections,
244 projects,
245 path,
246 });
247 const sharedWorkspace = () =>
248 new CheckpointRollbackExecutionError({
249 reason: "shared-workspace",
250 threadId: input.threadId,
251 providerThreadId: input.providerThreadId,
252 checkpointId: input.checkpointId,
253 });
254
255 if (taskFolder !== null && branch != null) {
256 // Cleanup can remove any of the folder's checkouts; the linked project folder has none.
257 yield* taskFolders.restore({
258 taskFolder,
259 branch,
260 recreate: (checkout) =>
261 gitWorkflow.pruneWorktrees({ cwd: checkout.repositoryPath }).pipe(
262 Effect.andThen(
263 gitWorkflow.createWorktree({
264 cwd: checkout.repositoryPath,
265 refName: branch,
266 path: checkout.worktreePath,
267 }),
268 ),
269 ),
270 });
271 } else if (worktreePath != null && branch != null) {
272 // Recreated only where the server would have made it, as turn start does.
273 // A failed removal can leave the folder without its checkout; only a file restore replaces it.
274 const leftover =
275 restoreFiles &&
276 (yield* fileSystem.exists(worktreePath)) &&
277 !(yield* fileSystem.exists(path.join(worktreePath, ".git")));
278 if (
279 (leftover || !(yield* fileSystem.exists(worktreePath))) &&
280 (yield* isManagedWorktreePath(worktreePath))
281 ) {
282 const project = yield* projects.get(context.thread.projectId);
283 if (Option.isSome(project)) {
284 const recreate = gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }).pipe(
285 Effect.andThen(
286 gitWorkflow.createWorktree({
287 cwd: project.value.workspaceRoot,
288 refName: branch,
289 path: worktreePath,
290 }),
291 ),
292 );
293 if (leftover) {
294 if (!(yield* isolated)) return yield* sharedWorkspace();
295 // Set aside, not removed: a checkout that fails puts the folder and its files back.
296 yield* Effect.acquireUseRelease(
297 Effect.gen(function* () {
298 const aside = yield* fileSystem.makeTempDirectory({
299 directory: path.dirname(worktreePath),
300 prefix: ".t3-replaced-",
301 });
302 yield* fileSystem.rename(worktreePath, path.join(aside, "folder"));
303 return aside;
304 }),
305 () => recreate,
306 (aside, exit) =>
307 (Exit.isSuccess(exit)
308 ? Effect.void
309 : fileSystem
310 .remove(worktreePath, { recursive: true, force: true })
311 .pipe(
312 Effect.andThen(
313 fileSystem.rename(path.join(aside, "folder"), worktreePath),
314 ),
315 )
316 ).pipe(
317 Effect.andThen(fileSystem.remove(aside, { recursive: true, force: true })),
318 Effect.catchCause((cause) =>
319 Effect.logWarning("Edit from here left a worktree folder set aside", {
320 worktreePath,
321 setAside: path.join(aside, "folder"),
322 cause,
323 }),
324 ),
325 ),
326 );
327 } else {
328 yield* recreate;
329 }
330 }
331 }
332 }
333
334 if (restoreFiles && !(yield* isolated)) return yield* sharedWorkspace();
335
336 // Before the provider conversation changes: a rewind with nothing to restore is refused.
337 const readable =
338 restoreFiles && taskFolder !== null
339 ? yield* checkpoints.repositoryScopesIfReadable({
340 rootScope: scope,
341 projectId: context.thread.projectId,
342 worktreePath,
343 })
344 : [];
345 // Unknown repositories are not "none": the rewind would leave their changes unmentioned.
346 if (readable === null) {
347 return yield* new CheckpointRollbackExecutionError({
348 reason: "unexpected-failure",
349 threadId: input.threadId,
350 providerThreadId: input.providerThreadId,
351 checkpointId: input.checkpointId,
352 cause: new Error("The thread's repositories could not be read."),
353 });
354 }
355 const repositories = readable;
356 const recorded =
357 repositories.length === 0
358 ? []
359 : (yield* projections.getCheckpointContext(input.threadId)).checkpoints;
360 const repositoryTargets = repositories.flatMap((repository) => {
361 const target = repositoryRewindCheckpoint(
362 recorded.filter((candidate) => candidate.scopeId === repository.id),
363 targetOrdinal,
364 );
365 return target === null ? [] : [{ scope: repository, checkpoint: target }];
366 });
367 // Changed by a discarded run, with no snapshot of how it was before: left as it is.
368 const unrestorable = repositories.filter(
369 (repository) =>
370 !repositoryTargets.some((target) => target.scope.id === repository.id) &&
371 recorded.some(
372 (candidate) =>
373 candidate.scopeId === repository.id &&
374 candidate.ordinalWithinScope > targetOrdinal &&
375 (candidate.status === "ready" || candidate.runId !== null),
376 ),
377 );
378 if (unrestorable.length > 0) {
379 yield* Effect.logWarning("Edit from here cannot restore repositories without a snapshot", {
380 threadId: input.threadId,
381 repositories: unrestorable.map((repository) => repository.cwd),
382 });
383 }
384 const restoreTargets = [
385 ...(checkpoint.status === "ready" ? [{ scope, checkpoint }] : []),
386 ...repositoryTargets,
387 ];
388 if (restoreFiles && restoreTargets.length === 0) return yield* invalidTarget();
389
390 const modelSelection = context.thread.modelSelection;
391 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
392 thread: context.thread,
393 modelSelection,
394 });
395 const existingSession = context.providerSession;
396 const session = yield* sessions.open({
397 threadId: input.threadId,
398 providerSessionId: providerThread.providerSessionId,
399 modelSelection,
400 runtimePolicy: resolvedRuntimePolicy,
401 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
402 ...(providerThread.nativeThreadRef?.nativeId == null
403 ? {}
404 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
405 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
406 ? {}
407 : {
408 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
409 }),
410 });
411
412 // Rolled-back turns remain in audit history but no longer exist in the provider conversation.
413 const rolledBackAttemptIds = new Set(context.rolledBackAttemptIds);
414 const providerThreadTurns = context.providerTurns.filter(
415 (turn) =>
416 turn.providerThreadId === providerThread.id &&
417 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
418 );
419
420 const snapshot =
421 runsToRollback.length === 0
422 ? { providerThread }
423 : yield* session.rollbackThread({
424 providerThread,
425 target: rollbackTarget,
426 providerThreadTurns,
427 });
428 if (restoreFiles) {
429 yield* checkpoints.restore({ targets: restoreTargets, scopes: [scope, ...repositories] });
430 }
431 const staleScopeCheckpoints = staleCheckpoints.filter((stale) => stale.scopeId === scope.id);
432 if (staleScopeCheckpoints.length > 0) {
433 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleScopeCheckpoints });
434 }
435 yield* checkpoints.discardRepositorySnapshots({
436 rootScope: scope,
437 thread: context.thread,
438 ordinals: runsToRollback.map((run) => run.ordinal),
439 });
440
441 // Lock against full-row thread writes that could restore the old native session after rollback.
442 yield* threadCommands.withLock(
443 input.threadId,
444 Effect.gen(function* () {
445 const now = yield* DateTime.now;
446 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
447 Effect.map(
448 ids.allocate.event({ threadId: event.threadId }),
449 (id) =>
450 ({
451 ...event,
452 id,
453 }) as Event,
454 );
455 const events: Array<OrchestrationV2DomainEvent> = [];
456 // First, so a client that sees the runs rolled back already knows what was left.
457 if (input.requestId !== undefined && unrestorable.length > 0) {
458 const thread = yield* projections.getThread(input.threadId);
459 events.push(
460 yield* makeEvent({
461 type: "thread.metadata-updated",
462 threadId: input.threadId,
463 providerInstanceId: thread.providerInstanceId,
464 occurredAt: now,
465 payload: {
466 ...thread,
467 rollbackUnrestored: {
468 requestId: input.requestId,
469 repositories: unrestorable.map(
470 (repository) => repository.label ?? path.basename(repository.cwd),
471 ),
472 },
473 updatedAt: now,
474 },
475 }),
476 );
477 }
478 events.push(
479 yield* makeEvent({
480 type: "provider-thread.updated",
481 threadId: input.threadId,
482 driver: providerThread.driver,
483 providerInstanceId: providerThread.providerInstanceId,
484 occurredAt: now,
485 payload: {
486 ...snapshot.providerThread,
487 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
488 updatedAt: now,
489 },
490 }),
491 );
492 for (const staleCheckpoint of staleCheckpoints) {
493 events.push(
494 yield* makeEvent({
495 type: "checkpoint.captured",
496 threadId: input.threadId,
497 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
498 nodeId: staleCheckpoint.nodeId,
499 providerInstanceId: providerThread.providerInstanceId,
500 occurredAt: now,
501 payload: { ...staleCheckpoint, status: "stale" },
502 }),
503 );
504 }
505 for (const run of runsToRollback) {
506 const rootNode = context.rootNodes.find((candidate) => candidate.id === run.rootNodeId);
507 events.push(
508 yield* makeEvent({
509 type: "run.updated",
510 threadId: input.threadId,
511 runId: run.id,
512 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
513 providerInstanceId: run.providerInstanceId,
514 occurredAt: now,
515 payload: { ...run, status: "rolled_back", completedAt: now },
516 }),
517 );
518 if (rootNode !== undefined) {
519 events.push(
520 yield* makeEvent({
521 type: "node.updated",
522 threadId: input.threadId,
523 runId: run.id,
524 nodeId: rootNode.id,
525 providerInstanceId: run.providerInstanceId,
526 occurredAt: now,
527 payload: { ...rootNode, status: "rolled_back", completedAt: now },
528 }),
529 );
530 }
531 }
532 yield* eventSink.write({ events });
533 }),
534 );
535 });
536
537 return CheckpointRollbackServiceV2.of({
538 // The inner execute owns the rollback span; this wrapper selects the workspace lease.
539 execute: Effect.fnUntraced(
540 function* (input) {
541 // Storage cleanup removes worktrees under the same lease.
542 const thread = yield* projections.getThread(input.threadId);
543 if (thread.worktreePath === null) return yield* execute(input);
544 const worktreePath = path.resolve(thread.worktreePath);
545 const rollback = withWorkspaceLease(worktreePath, execute(input));
546 // Shared-workspace restores are rejected and conversation-only rewinds
547 // touch no files; reserving for them would stall turn starts on the
548 // slow provider rollback for nothing.
549 yield* input.restoreFiles === false
550 ? rollback
551 : withCheckpointRestoreReservation(fileSystem, path, worktreePath, rollback);
552 },
553 (effect, input) =>
554 effect.pipe(
555 Effect.mapError((cause) =>
556 isCheckpointRollbackExecutionError(cause)
557 ? cause
558 : new CheckpointRollbackExecutionError({
559 reason: "unexpected-failure",
560 threadId: input.threadId,
561 providerThreadId: input.providerThreadId,
562 checkpointId: input.checkpointId,
563 cause,
564 }),
565 ),
566 ),
567 ),
568 });
569 }),
570);