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