Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorktreeMcpService.ts

494 lines20.7 KB

1import {
2 CommandId,
3 MessageId,
4 type ProjectId,
5 WorktreeMcpFailure,
6 type WorktreeMcpContinuationStatus,
7 type WorktreeMcpHandoffInput,
8 type WorktreeMcpHandoffResult,
9 type WorktreeMcpSetupScriptStatus,
10 type WorktreeMcpStatusResult,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Context from "effect/Context";
14import * as Crypto from "effect/Crypto";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19​
20import * as GitWorkflowService from "../git/GitWorkflowService.ts";
21import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
22import * as ProjectService from "../project/ProjectService.ts";
23import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
24import * as ServerSettings from "../serverSettings.ts";
25import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
26import type { McpInvocationScope } from "./McpInvocationContext.ts";
27​
28export class WorktreeMcpService extends Context.Service<
29 WorktreeMcpService,
30 {
31 readonly handoff: (
32 scope: McpInvocationScope,
33 input: WorktreeMcpHandoffInput,
34 ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
35 readonly status: (
36 scope: McpInvocationScope,
37 ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
38 }
39>()("t3/mcp/WorktreeMcpService") {}
40​
41function failure(code: WorktreeMcpFailure["code"], message: string): WorktreeMcpFailure {
42 return new WorktreeMcpFailure({ code, message });
44​
45function errorMessage(error: unknown): string {
46 if (error instanceof Error) return error.message;
47 if (typeof error === "object" && error !== null && "message" in error) {
48 return String((error as { message: unknown }).message);
49 }
50 return String(error);
52​
53const asOperationFailed = (prefix: string) =>
54 Effect.mapError((error: unknown) =>
55 failure("operation_failed", `${prefix}: ${errorMessage(error)}`),
56 );
57​
58const make = Effect.gen(function* () {
59 const crypto = yield* Crypto.Crypto;
60 const path = yield* Path.Path;
61 const threadManagement = yield* ThreadManagementService;
62 const projects = yield* ProjectService.ProjectService;
63 const serverSettings = yield* ServerSettings.ServerSettingsService;
64 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
65 const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
66 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
67​
68 // Serializes handoffs per thread: two concurrent calls could otherwise both
69 // pass the worktreePath === null check and each create a worktree, leaving
70 // one untracked on disk.
71 const handoffThreadsInFlight = new Set<string>();
72​
73 const requireCapability = (scope: McpInvocationScope) =>
74 scope.capabilities.has("worktree")
75 ? Effect.void
76 : Effect.fail(
77 failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
78 );
79​
80 const loadThread = (scope: McpInvocationScope) =>
81 threadManagement.getThreadProjection(scope.threadId).pipe(
82 Effect.mapError((error) =>
83 error._tag === "OrchestratorProjectionError"
84 ? failure("thread_not_found", `Thread '${scope.threadId}' was not found.`)
85 : failure(
86 "operation_failed",
87 `Unable to read thread ${scope.threadId}: ${errorMessage(error)}`,
88 ),
89 ),
90 Effect.filterOrFail(
91 (projection) => projection.thread.deletedAt === null,
92 () => failure("thread_not_found", `Thread '${scope.threadId}' was not found.`),
93 ),
94 );
95​
96 const loadProject = (scope: McpInvocationScope, projectId: ProjectId) =>
97 projects.getById(projectId).pipe(
98 asOperationFailed(`Unable to read project ${projectId}`),
99 Effect.flatMap(
100 Option.match({
101 onNone: () =>
102 Effect.fail(
103 failure(
104 "project_not_found",
105 `Project '${projectId}' was not found for thread '${scope.threadId}'.`,
106 ),
107 ),
108 onSome: Effect.succeed,
109 }),
110 ),
111 );
112​
113 const readDefaultStartFromOrigin = serverSettings.getSettings.pipe(
114 Effect.map((settings) => settings.newWorktreesStartFromOrigin),
115 asOperationFailed("Unable to read server settings"),
116 );
117​
118 const handoffIds = (scope: McpInvocationScope) =>
119 crypto.randomUUIDv4.pipe(
120 Effect.map((uuid) => {
121 const part = (kind: string, operation: string) =>
122 [kind, "mcp", encodeURIComponent(scope.providerSessionId), operation, uuid].join(":");
123 return {
124 commandId: CommandId.make(part("command", "worktree-handoff")),
125 continuationCommandId: CommandId.make(part("command", "worktree-continuation")),
126 continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
127 };
128 }),
129 Effect.orDie,
130 );
131​
132 const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
133 scope: McpInvocationScope,
134 input: WorktreeMcpHandoffInput,
135 ) {
136 const alreadyInWorktree = (worktreePath: string) =>
137 failure(
138 "already_in_worktree",
139 `Thread '${scope.threadId}' is already attached to worktree '${worktreePath}'.`,
140 );
141​
142 const projection = yield* loadThread(scope);
143 if (projection.thread.worktreePath !== null) {
144 return yield* alreadyInWorktree(projection.thread.worktreePath);
145 }
146 // An archived thread would accept the binding but refuse the continuation
147 // message (and any other follow-up), so reject the handoff outright.
148 if (projection.thread.archivedAt !== null) {
149 return yield* failure(
150 "invalid_request",
151 `Thread '${scope.threadId}' is archived and cannot be handed off to a worktree.`,
152 );
153 }
154​
155 const project = yield* loadProject(scope, projection.thread.projectId);
156 const projectCwd = project.workspaceRoot;
157​
158 if (input.path !== undefined && !path.isAbsolute(input.path)) {
159 return yield* failure(
160 "invalid_request",
161 `path must be an absolute filesystem path, got '${input.path}'. A relative path would be created relative to the project workspace but stored verbatim as the thread's worktree binding.`,
162 );
163 }
164​
165 // The repo check runs regardless of whether baseRef was supplied, so a
166 // non-repository workspace fails with an actionable error instead of an
167 // opaque git failure further down.
168 const localStatus = yield* gitWorkflow
169 .localStatus({ cwd: projectCwd })
170 .pipe(asOperationFailed("Unable to read git status"));
171 if (!localStatus.isRepo) {
172 return yield* failure(
173 "invalid_request",
174 `Project workspace '${projectCwd}' is not a git repository.`,
175 );
176 }
177​
178 // Fail fast with an actionable message when the branch already exists:
179 // the git driver deliberately keeps stderr out of its errors, so letting
180 // `git worktree add` fail would surface only an opaque failure. The
181 // existence check uses the complete local branch list (exact match); the
182 // paginated substring search only enriches the message with the checkout
183 // location when available.
184 const localBranchNames = yield* gitWorkflow
185 .listLocalBranchNames(projectCwd)
186 .pipe(asOperationFailed("Unable to list branches"));
187 if (localBranchNames.includes(input.branch)) {
188 const existingRef = yield* gitWorkflow
189 .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
190 .pipe(
191 Effect.map((result) =>
192 result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
193 ),
194 Effect.orElseSucceed(() => undefined),
195 );
196 const checkoutPath = existingRef?.worktreePath ?? null;
197 return yield* failure(
198 "invalid_request",
199 `Branch '${input.branch}' already exists${
200 checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
201 }. Choose a different branch name, or delete the existing branch${
202 checkoutPath === null ? "" : " and its worktree"
203 } first.`,
204 );
205 }
206​
207 let baseRef = input.baseRef;
208 if (baseRef === undefined) {
209 if (localStatus.refName === null) {
210 return yield* failure(
211 "invalid_request",
212 "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
213 );
214 }
215 baseRef = localStatus.refName;
216 }
217​
218 const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin);
219​
220 let worktreeBaseRef = baseRef;
221 if (startFromOrigin) {
222 yield* gitWorkflow
223 .fetchRemote({ cwd: projectCwd, remoteName: "origin" })
224 .pipe(asOperationFailed("Unable to fetch origin"));
225 const resolvedRemoteBase = yield* gitWorkflow
226 .resolveRemoteTrackingCommit({
227 cwd: projectCwd,
228 refName: baseRef,
229 fallbackRemoteName: "origin",
230 })
231 .pipe(asOperationFailed(`Unable to resolve the remote-tracking commit of '${baseRef}'`));
232 worktreeBaseRef = resolvedRemoteBase.commitSha;
233 }
234​
235 const ids = yield* handoffIds(scope);
236​
237 // uninterruptibleMask: only the potentially slow worktree creation itself
238 // stays interruptible (restore). From the moment it succeeds, through the
239 // binding, continuation queue, setup script launch, and result
240 // construction, there is no interruptible gap: a client cancel can
241 // therefore neither orphan the created worktree before the rollback is
242 // armed, nor skip setting up a worktree the thread was just bound to
243 // (once the binding commits, the scheduled session detach can sever this
244 // request's connection and interrupt the fiber).
245 return yield* Effect.uninterruptibleMask((restore) =>
246 Effect.gen(function* () {
247 const worktree = yield* restore(
248 gitWorkflow
249 .createWorktree({
250 cwd: projectCwd,
251 refName: worktreeBaseRef,
252 newRefName: input.branch,
253 baseRefName: baseRef,
254 path: input.path ?? null,
255 })
256 .pipe(asOperationFailed("Unable to create the worktree")),
257 );
258 const worktreePath = worktree.worktree.path;
259​
260 // Shared shape for "the handoff already succeeded, so report the failure
261 // in the result instead of failing the call" (continuation, setup script).
262 const reportFailed = (logMessage: string) =>
263 Effect.catchCause((cause: Cause.Cause<unknown>) => {
264 const detail = errorMessage(Cause.squash(cause));
265 return Effect.logWarning(logMessage, {
266 threadId: scope.threadId,
267 worktreePath,
268 detail,
269 }).pipe(Effect.as({ status: "failed", detail } as const));
270 });
271​
272 // suspend: build the rollback only if cleanup actually runs. Removing
273 // the worktree must succeed before deleting its freshly created branch;
274 // otherwise the branch may still be checked out there.
275 const removeCreatedWorktree = Effect.suspend(() =>
276 gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }).pipe(
277 Effect.andThen(
278 Effect.suspend(() =>
279 gitWorkflow.deleteLocalBranch({
280 cwd: projectCwd,
281 refName: worktree.worktree.refName,
282 force: true,
283 }),
284 ),
285 ),
286 ),
287 ).pipe(Effect.ignoreCause({ log: true }));
288​
289 const recheckAndBind = Effect.gen(function* () {
290 // The projection was read before the potentially slow git work
291 // above; a concurrent binding (for example from the UI) could have
292 // attached the thread in the meantime. Re-check before committing so
293 // the race cannot leave a second, untracked worktree.
294 const recheck = yield* loadThread(scope);
295 if (recheck.thread.worktreePath !== null) {
296 return yield* alreadyInWorktree(recheck.thread.worktreePath);
297 }
298 // Mirror the up-front archived check: the thread may have been
299 // archived during the slow git work, and an archived thread must
300 // not be bound to a fresh worktree it can never use.
301 if (recheck.thread.archivedAt !== null) {
302 return yield* failure(
303 "invalid_request",
304 `Thread '${scope.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
305 );
306 }
307 yield* threadManagement
308 .dispatch({
309 type: "thread.metadata.update",
310 commandId: ids.commandId,
311 threadId: scope.threadId,
312 branch: worktree.worktree.refName,
313 worktreePath,
314 expectedWorktreePath: null,
315 })
316 .pipe(
317 Effect.catchCause((cause) =>
318 // Interrupt-only causes propagate unchanged: whether the
319 // dispatch committed is unknown, so neither a typed failure
320 // nor a rollback would be correct. Failures and defects
321 // (including mixed causes) map to a typed operation_failed.
322 Cause.hasInterruptsOnly(cause)
323 ? Effect.failCause(cause as Cause.Cause<never>)
324 : Effect.fail(
325 failure(
326 "operation_failed",
327 `Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
328 ),
329 ),
330 ),
331 );
332 }).pipe(
333 // onError: the worktree was already created, so any failure between
334 // here and the committed binding (recheck read, recheck race,
335 // dispatch typed failure or defect) must remove it again so a failed
336 // handoff leaves nothing behind on disk. Interrupt-only causes skip
337 // the removal: the binding may have committed, and force-deleting a
338 // worktree the thread now points at would be worse than leaking one.
339 Effect.onError((cause) =>
340 Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
341 ),
342 );
343​
344 // Queue the continuation right after the binding commits: the detach
345 // that the metadata update schedules will terminate the calling
346 // session, and a durably queued message is what guarantees the thread
347 // re-launches inside the worktree. When the dying run reaches a
348 // terminal state the orchestrator promotes the queued run, which
349 // derives its cwd from the updated projection.
350 // suspend: build the send effect only when the binding has succeeded,
351 // so a failed dispatch never even constructs the continuation call.
352 const queueContinuation: Effect.Effect<WorktreeMcpContinuationStatus, WorktreeMcpFailure> =
353 Effect.suspend(() =>
354 input.continuationPrompt === undefined
355 ? Effect.succeed<WorktreeMcpContinuationStatus>({ status: "skipped" })
356 : threadManagement
357 .sendToThread({
358 projectId: projection.thread.projectId,
359 commandId: ids.continuationCommandId,
360 threadId: scope.threadId,
361 messageId: ids.continuationMessageId,
362 text: input.continuationPrompt,
363 attachments: [],
364 mode: "queue",
365 createdBy: "agent",
366 creationSource: "mcp",
367 })
368 .pipe(
369 Effect.map(
370 (sendResult): WorktreeMcpContinuationStatus => ({
371 status: "scheduled",
372 delivery: sendResult.delivery,
373 }),
374 ),
375 // catchCause via reportFailed: the binding is already recorded,
376 // so a failed continuation must be reported, not fail the handoff.
377 reportFailed("worktree handoff continuation failed to queue"),
378 ),
379 );
380​
381 const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
382​
383 yield* vcsStatusBroadcaster
384 .refreshStatus(worktreePath)
385 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
386​
387 let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
388 if (input.runSetupScript ?? true) {
389 setupScript = yield* setupScriptRunner
390 .runForThread({
391 threadId: scope.threadId,
392 projectId: projection.thread.projectId,
393 projectCwd,
394 worktreePath,
395 project: {
396 workspaceRoot: project.workspaceRoot,
397 scripts: project.scripts,
398 },
399 })
400 .pipe(
401 Effect.map(
402 (result): WorktreeMcpSetupScriptStatus =>
403 result.status === "started"
404 ? {
405 status: "started",
406 scriptName: result.scriptName,
407 terminalId: result.terminalId,
408 }
409 : { status: "no-script" },
410 ),
411 // catchCause via reportFailed: the thread is already re-pointed at the
412 // worktree, so even a defect in the setup runner must not fail the handoff.
413 reportFailed("worktree handoff setup script failed"),
414 );
415 }
416​
417 const result: WorktreeMcpHandoffResult = {
418 worktreePath,
419 branch: worktree.worktree.refName,
420 baseRef,
421 startedFromOrigin: startFromOrigin,
422 setupScript,
423 continuation,
424 note:
425 continuation.status === "scheduled"
426 ? "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the queued continuation prompt then starts the next turn inside the worktree with the conversation preserved. The worktree is not removed automatically when the thread is deleted."
427 : "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.",
428 };
429 return result;
430 }),
431 );
432 });
433​
434 const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
435 function* (scope, input) {
436 yield* requireCapability(scope);
437 // uninterruptibleMask: the guard acquisition and the registration of the
438 // releasing finalizer happen with no interruptible gap in between. An
439 // interrupt landing between a bare add() and the start of an ensured
440 // effect would otherwise leak the guard entry and block every future
441 // handoff for this thread until restart.
442 return yield* Effect.uninterruptibleMask((restore) =>
443 Effect.suspend(() => {
444 if (handoffThreadsInFlight.has(scope.threadId)) {
445 return Effect.fail(
446 failure(
447 "handoff_in_progress",
448 `A worktree handoff is already in progress for thread '${scope.threadId}'.`,
449 ),
450 );
451 }
452 handoffThreadsInFlight.add(scope.threadId);
453 return restore(performHandoff(scope, input)).pipe(
454 Effect.ensuring(Effect.sync(() => handoffThreadsInFlight.delete(scope.threadId))),
455 );
456 }),
457 );
458 },
459 );
460​
461 const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
462 function* (scope) {
463 yield* requireCapability(scope);
464 const projection = yield* loadThread(scope);
465 const project = yield* loadProject(scope, projection.thread.projectId);
466​
467 const defaultStartFromOrigin = yield* readDefaultStartFromOrigin;
468​
469 const result: WorktreeMcpStatusResult = {
470 attached: projection.thread.worktreePath !== null,
471 worktreePath: projection.thread.worktreePath,
472 branch: projection.thread.branch,
473 projectWorkspaceRoot: project.workspaceRoot,
474 defaultStartFromOrigin,
475 };
476 return result;
477 },
478 );
479​
480 return WorktreeMcpService.of({ handoff, status });
481});
482​
483export const layer: Layer.Layer<
484 WorktreeMcpService,
485 never,
486 | Crypto.Crypto
487 | Path.Path
488 | ThreadManagementService
489 | ProjectService.ProjectService
490 | ServerSettings.ServerSettingsService
491 | GitWorkflowService.GitWorkflowService
492 | ProjectSetupScriptRunner.ProjectSetupScriptRunner
493 | VcsStatusBroadcaster.VcsStatusBroadcaster
494> = Layer.effect(WorktreeMcpService, make);