Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointScopeId,
4 latestProviderTurnForAttempt,
5 type OrchestrationV2DomainEvent,
6 ProviderThreadId,
7 ThreadId,
8 VcsProcessExitError,
9} from "@t3tools/contracts";
10import * as Context from "effect/Context";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as Schema from "effect/Schema";
18
19import * as GitWorkflowService from "../git/GitWorkflowService.ts";
20import type * as ServerConfig from "../config.ts";
21import type * as ServerSettings from "../serverSettings.ts";
22import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";
23import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
24import {
25 isCheckpointRestoreIsolated,
26 SHARED_WORKSPACE_RESTORE_MESSAGE,
27} from "./CheckpointRestoreSafety.ts";
28import { CheckpointRestoreError, CheckpointServiceV2 } from "./CheckpointService.ts";
29import { EventSinkV2 } from "./EventSink.ts";
30import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
31import { ProjectionStoreV2 } from "./ProjectionStore.ts";
32import { GIT_INDEX_LOCKED_DETAIL } from "../vcs/VcsProcess.ts";
33import * as ProjectStore from "./ProjectStore.ts";
34import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
35import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
36import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
37import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
38
39export const ROLLBACK_FAILED_MESSAGE =
40 "The provider could not roll back this conversation. Try again; if it keeps failing, check the provider and server logs.";
41
42export class CheckpointRollbackExecutionError extends Schema.TaggedError<CheckpointRollbackExecutionError>()(
43 "CheckpointRollbackExecutionError",
44 {
45 reason: Schema.Literals([
46 "rollback-target-invalid",
47 "active-provider-changed",
48 "provider-turn-unavailable",
49 "unexpected-failure",
50 "shared-workspace",
51 ]),
52 threadId: ThreadId,
53 providerThreadId: ProviderThreadId,
54 checkpointId: CheckpointId,
55 cause: Schema.optional(Schema.Defect()),
56 },
57) {
58 override get message(): string {
59 switch (this.reason) {
60 case "rollback-target-invalid":
61 return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`;
62 case "active-provider-changed":
63 return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
64 case "provider-turn-unavailable":
65 return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
66 case "shared-workspace":
67 return SHARED_WORKSPACE_RESTORE_MESSAGE;
68 case "unexpected-failure":
69 return ROLLBACK_FAILED_MESSAGE;
70 }
71 }
72}
73
74const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
75const isVcsProcessExitError = Schema.is(VcsProcessExitError);
76const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
77
78/**
79 * The message clients see when a rollback fails. Only a held Git index lock
80 * gets its own explanation; other reasons carry internal ids or raw Git
81 * output, so they fall back to the generic message.
82 */
83export function rollbackFailureClientMessage(error: CheckpointRollbackExecutionError): string {
84 const restoreCause = isCheckpointRestoreError(error.cause) ? error.cause.cause : undefined;
85 return isVcsProcessExitError(restoreCause) && restoreCause.detail === GIT_INDEX_LOCKED_DETAIL
86 ? GIT_INDEX_LOCKED_DETAIL
87 : ROLLBACK_FAILED_MESSAGE;
88}
89
90export interface CheckpointRollbackServiceV2Shape {
91 readonly execute: (input: {
92 readonly threadId: ThreadId;
93 readonly providerThreadId: ProviderThreadId;
94 readonly checkpointId: CheckpointId;
95 readonly scopeId: CheckpointScopeId;
96 readonly restoreFiles?: boolean;
97 }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
98}
99
100export class CheckpointRollbackServiceV2 extends Context.Service<
101 CheckpointRollbackServiceV2,
102 CheckpointRollbackServiceV2Shape
103>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
104
105export const layer: Layer.Layer<
106 CheckpointRollbackServiceV2,
107 never,
108 | CheckpointServiceV2
109 | GitWorkflowService.GitWorkflowService
110 | EventSinkV2
111 | IdAllocator.IdAllocatorV2
112 | ProjectionStoreV2
113 | ProviderSessionManagerV2
114 | RuntimePolicyV2
115 | FileSystem.FileSystem
116 | Path.Path
117 | ProjectStore.ProjectStoreV2
118 | ServerConfig.ServerConfig
119 | ServerSettings.ServerSettingsService
120 | ThreadCommandExecutor.ThreadCommandExecutor
121> = Layer.effect(
122 CheckpointRollbackServiceV2,
123 Effect.gen(function* () {
124 const checkpoints = yield* CheckpointServiceV2;
125 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
126 const eventSink = yield* EventSinkV2;
127 const ids = yield* IdAllocator.IdAllocatorV2;
128 const projections = yield* ProjectionStoreV2;
129 const sessions = yield* ProviderSessionManagerV2;
130 const runtimePolicy = yield* RuntimePolicyV2;
131 const fileSystem = yield* FileSystem.FileSystem;
132 const projects = yield* ProjectStore.ProjectStoreV2;
133 const path = yield* Path.Path;
134 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
135 const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
136
137 const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
138 readonly threadId: ThreadId;
139 readonly providerThreadId: ProviderThreadId;
140 readonly checkpointId: CheckpointId;
141 readonly scopeId: CheckpointScopeId;
142 readonly restoreFiles?: boolean;
143 }) {
144 const context = yield* projections.getCheckpointRollbackContext(input.threadId, input);
145 const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } =
146 context;
147 if (
148 providerThread === undefined ||
149 providerThread.providerSessionId === null ||
150 checkpoint === undefined ||
151 scope === undefined ||
152 checkpoint.scopeId !== scope.id ||
153 checkpoint.status !== "ready"
154 ) {
155 return yield* new CheckpointRollbackExecutionError({
156 reason: "rollback-target-invalid",
157 threadId: input.threadId,
158 providerThreadId: input.providerThreadId,
159 checkpointId: input.checkpointId,
160 });
161 }
162 if (
163 providerThread.id !== context.thread.activeProviderThreadId ||
164 providerThread.providerInstanceId !== context.thread.modelSelection.instanceId
165 ) {
166 return yield* new CheckpointRollbackExecutionError({
167 reason: "active-provider-changed",
168 threadId: input.threadId,
169 providerThreadId: input.providerThreadId,
170 checkpointId: input.checkpointId,
171 });
172 }
173
174 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
175 const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget =
176 targetOrdinal === 0
177 ? {
178 type: "thread_start",
179 checkpointId: checkpoint.id,
180 appRunOrdinal: 0,
181 }
182 : yield* Effect.gen(function* () {
183 const targetTurn =
184 latestProviderTurnForAttempt(context.providerTurns, targetAttempt?.id) ??
185 context.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId);
186 if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
187 return yield* new CheckpointRollbackExecutionError({
188 reason: "provider-turn-unavailable",
189 threadId: input.threadId,
190 providerThreadId: input.providerThreadId,
191 checkpointId: input.checkpointId,
192 });
193 }
194 return {
195 type: "provider_turn" as const,
196 checkpointId: checkpoint.id,
197 appRunOrdinal: targetOrdinal,
198 providerTurn: targetTurn,
199 };
200 });
201
202 const { worktreePath, branch } = context.thread;
203 // Recreated only where the server would have made it, as turn start does.
204 if (
205 worktreePath != null &&
206 branch != null &&
207 !(yield* fileSystem.exists(worktreePath)) &&
208 (yield* isManagedWorktreePath(worktreePath))
209 ) {
210 const project = yield* projects.get(context.thread.projectId);
211 if (Option.isSome(project)) {
212 yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot });
213 yield* gitWorkflow.createWorktree({
214 cwd: project.value.workspaceRoot,
215 refName: branch,
216 path: worktreePath,
217 });
218 }
219 }
220
221 if (
222 input.restoreFiles !== false &&
223 !(yield* isCheckpointRestoreIsolated(context.thread, scope, {
224 fileSystem,
225 projections,
226 projects,
227 path,
228 }))
229 ) {
230 return yield* new CheckpointRollbackExecutionError({
231 reason: "shared-workspace",
232 threadId: input.threadId,
233 providerThreadId: input.providerThreadId,
234 checkpointId: input.checkpointId,
235 });
236 }
237
238 const modelSelection = context.thread.modelSelection;
239 const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
240 thread: context.thread,
241 modelSelection,
242 });
243 const existingSession = context.providerSession;
244 const session = yield* sessions.open({
245 threadId: input.threadId,
246 providerSessionId: providerThread.providerSessionId,
247 modelSelection,
248 runtimePolicy: resolvedRuntimePolicy,
249 ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
250 ...(providerThread.nativeThreadRef?.nativeId == null
251 ? {}
252 : { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
253 ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
254 ? {}
255 : {
256 initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
257 }),
258 });
259
260 // Rolled-back turns remain in audit history but no longer exist in the provider conversation.
261 const rolledBackAttemptIds = new Set(context.rolledBackAttemptIds);
262 const providerThreadTurns = context.providerTurns.filter(
263 (turn) =>
264 turn.providerThreadId === providerThread.id &&
265 (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
266 );
267
268 const snapshot =
269 runsToRollback.length === 0
270 ? { providerThread }
271 : yield* session.rollbackThread({
272 providerThread,
273 target: rollbackTarget,
274 providerThreadTurns,
275 });
276 if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
277 if (staleCheckpoints.length > 0) {
278 yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
279 }
280
281 // Thread commands write full provider thread rows under this lock. Without
282 // it, a message sent during the rollback can plan against the old native
283 // session and commit after this, undoing the provider's fork.
284 yield* threadCommands.withLock(
285 input.threadId,
286 Effect.gen(function* () {
287 const now = yield* DateTime.now;
288 const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
289 Effect.map(
290 ids.allocate.event({ threadId: event.threadId }),
291 (id) =>
292 ({
293 ...event,
294 id,
295 }) as Event,
296 );
297 const events: Array<OrchestrationV2DomainEvent> = [];
298 events.push(
299 yield* makeEvent({
300 type: "provider-thread.updated",
301 threadId: input.threadId,
302 driver: providerThread.driver,
303 providerInstanceId: providerThread.providerInstanceId,
304 occurredAt: now,
305 payload: {
306 ...snapshot.providerThread,
307 lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
308 updatedAt: now,
309 },
310 }),
311 );
312 for (const staleCheckpoint of staleCheckpoints) {
313 events.push(
314 yield* makeEvent({
315 type: "checkpoint.captured",
316 threadId: input.threadId,
317 ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
318 nodeId: staleCheckpoint.nodeId,
319 providerInstanceId: providerThread.providerInstanceId,
320 occurredAt: now,
321 payload: { ...staleCheckpoint, status: "stale" },
322 }),
323 );
324 }
325 for (const run of runsToRollback) {
326 const rootNode = context.rootNodes.find((candidate) => candidate.id === run.rootNodeId);
327 events.push(
328 yield* makeEvent({
329 type: "run.updated",
330 threadId: input.threadId,
331 runId: run.id,
332 ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
333 providerInstanceId: run.providerInstanceId,
334 occurredAt: now,
335 payload: { ...run, status: "rolled_back", completedAt: now },
336 }),
337 );
338 if (rootNode !== undefined) {
339 events.push(
340 yield* makeEvent({
341 type: "node.updated",
342 threadId: input.threadId,
343 runId: run.id,
344 nodeId: rootNode.id,
345 providerInstanceId: run.providerInstanceId,
346 occurredAt: now,
347 payload: { ...rootNode, status: "rolled_back", completedAt: now },
348 }),
349 );
350 }
351 }
352 yield* eventSink.write({ events });
353 }),
354 );
355 });
356
357 return CheckpointRollbackServiceV2.of({
358 // The inner execute owns the rollback span; this wrapper selects the workspace lease.
359 execute: Effect.fnUntraced(
360 function* (input) {
361 // Storage cleanup removes worktrees under the same lease.
362 const thread = yield* projections.getThread(input.threadId);
363 yield* thread.worktreePath === null
364 ? execute(input)
365 : withWorkspaceLease(path.resolve(thread.worktreePath), execute(input));
366 },
367 (effect, input) =>
368 effect.pipe(
369 Effect.mapError((cause) =>
370 isCheckpointRollbackExecutionError(cause)
371 ? cause
372 : new CheckpointRollbackExecutionError({
373 reason: "unexpected-failure",
374 threadId: input.threadId,
375 providerThreadId: input.providerThreadId,
376 checkpointId: input.checkpointId,
377 cause,
378 }),
379 ),
380 ),
381 ),
382 });
383 }),
384);