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

WorktreeMcpService.ts

524 lines20.5 KB

1import {
2 CommandId,
3 type GitCommandError,
4 type TaskFolderError,
5 MessageId,
6 type ProjectId,
7 WorktreeMcpFailure,
8 type WorktreeMcpContinuationStatus,
9 type WorktreeMcpHandoffInput,
10 type WorktreeMcpHandoffResult,
11 type WorktreeMcpSetupScriptStatus,
12 type WorktreeMcpStatusResult,
13 type VcsListRefsInput,
14 type VcsListRefsResult,
15} from "@t3tools/contracts";
16import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
17import * as Cause from "effect/Cause";
18import * as Context from "effect/Context";
19import * as SecureRandom from "effect/crypto/SecureRandom";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import type * as PlatformError from "effect/PlatformError";
25​
26import * as GitWorkflowService from "../git/GitWorkflowService.ts";
27import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
28import * as ProjectService from "../project/ProjectService.ts";
29import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
30import * as ServerSettings from "../serverSettings.ts";
31import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
32import * as TaskFolders from "../workspace/TaskFolders.ts";
33import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
34​
35export class WorktreeMcpService extends Context.Service<
36 WorktreeMcpService,
37 {
38 readonly handoff: (
39 scope: McpInvocationScope,
40 input: WorktreeMcpHandoffInput,
41 ) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
42 readonly status: (
43 scope: McpInvocationScope,
44 ) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
45 readonly listRefs: (
46 input: Omit<VcsListRefsInput, "cwd"> & {
47 readonly worktreePath: string | null;
48 readonly workspaceRoot: string;
49 },
50 ) => Effect.Effect<VcsListRefsResult, GitCommandError | PlatformError.PlatformError>;
51 }
52>()("t3/mcp/WorktreeMcpService") {}
53​
54function failure(code: WorktreeMcpFailure["code"], message: string): WorktreeMcpFailure {
55 return new WorktreeMcpFailure({ code, message });
57​
58function errorMessage(error: unknown): string {
59 if (error instanceof Error) return error.message;
60 if (typeof error === "object" && error !== null && "message" in error) {
61 return String((error as { message: unknown }).message);
62 }
63 return String(error);
65​
66const asOperationFailed = (prefix: string) =>
67 Effect.mapError((error: unknown) =>
68 failure("operation_failed", `${prefix}: ${errorMessage(error)}`),
69 );
70​
71const make = Effect.gen(function* () {
72 const random = yield* SecureRandom.SecureRandom;
73 const fileSystem = yield* FileSystem.FileSystem;
74 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
75 const projects = yield* ProjectService.ProjectService;
76 const serverSettings = yield* ServerSettings.ServerSettingsService;
77 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
78 const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
79 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
80 const taskFolders = yield* TaskFolders.TaskFolders;
81​
82 // Serialize handoffs per thread to avoid creating two worktrees and orphaning one.
83 const handoffThreadsInFlight = new Set<string>();
84​
85 const requireThreadScope = (scope: McpInvocationScope) =>
86 scope.thread === undefined
87 ? Effect.fail(
88 failure(
89 "thread_credential_required",
90 "Worktree handoff and status act as the calling T3 thread, so they need an agent running inside T3 Code.",
91 ),
92 )
93 : Effect.succeed(scope as McpThreadInvocationScope);
94​
95 const requireCapability = (scope: McpInvocationScope) =>
96 scope.capabilities.has("worktree")
97 ? Effect.void
98 : Effect.fail(
99 failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
100 );
101​
102 const loadThread = (scope: McpThreadInvocationScope) =>
103 threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
104 Effect.mapError((error) =>
105 error._tag === "OrchestratorProjectionError"
106 ? failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`)
107 : failure(
108 "operation_failed",
109 `Unable to read thread ${scope.thread.threadId}: ${errorMessage(error)}`,
110 ),
111 ),
112 Effect.filterOrFail(
113 (projection) => projection.thread.deletedAt === null,
114 () => failure("thread_not_found", `Thread '${scope.thread.threadId}' was not found.`),
115 ),
116 );
117​
118 const loadProject = (scope: McpThreadInvocationScope, projectId: ProjectId) =>
119 projects.getById(projectId).pipe(
120 asOperationFailed(`Unable to read project ${projectId}`),
121 Effect.flatMap(
122 Option.match({
123 onNone: () =>
124 Effect.fail(
125 failure(
126 "project_not_found",
127 `Project '${projectId}' was not found for thread '${scope.thread.threadId}'.`,
128 ),
129 ),
130 onSome: Effect.succeed,
131 }),
132 ),
133 );
134​
135 const readDefaultStartFromOrigin = (projectId: ProjectId) =>
136 serverSettings.getSettings.pipe(
137 Effect.map(
138 (settings) =>
139 resolveProjectSettings(settings, projectId).settings.newWorktreesStartFromOrigin,
140 ),
141 asOperationFailed("Unable to read server settings"),
142 );
143​
144 const handoffIds = (scope: McpThreadInvocationScope) =>
145 random.uuidV4().pipe(
146 Effect.map((uuid) => {
147 const part = (kind: string, operation: string) =>
148 [kind, "mcp", encodeURIComponent(scope.thread.providerSessionId), operation, uuid].join(
149 ":",
150 );
151 return {
152 commandId: CommandId.make(part("command", "worktree-handoff")),
153 continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
154 };
155 }),
156 Effect.orDie,
157 );
158​
159 const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
160 scope: McpThreadInvocationScope,
161 input: WorktreeMcpHandoffInput,
162 ) {
163 const alreadyInWorktree = (worktreePath: string) =>
164 failure(
165 "already_in_worktree",
166 `Thread '${scope.thread.threadId}' is already attached to worktree '${worktreePath}'.`,
167 );
168​
169 const projection = yield* loadThread(scope);
170 if (projection.thread.worktreePath !== null) {
171 return yield* alreadyInWorktree(projection.thread.worktreePath);
172 }
173 if (projection.thread.archivedAt !== null) {
174 return yield* failure(
175 "invalid_request",
176 `Thread '${scope.thread.threadId}' is archived and cannot be handed off to a worktree.`,
177 );
178 }
179​
180 const project = yield* loadProject(scope, projection.thread.projectId);
181 const projectCwd = project.workspaceRoot;
182​
183 // A project that tracks repositories moves into a task folder: its own folder, which need
184 // not be a repository, and a worktree of each tracked one.
185 const taskPlan = yield* taskFolders
186 .plan({ projectId: project.id })
187 .pipe(asOperationFailed("Unable to read the project's repositories"));
188 const projectIsRepository = taskPlan === null || taskPlan.projectIsRepository;
189 const localStatus = yield* gitWorkflow
190 .localStatus({ cwd: projectCwd })
191 .pipe(asOperationFailed("Unable to read git status"));
192 if (projectIsRepository && !localStatus.isRepo) {
193 return yield* failure(
194 "invalid_request",
195 `Project workspace '${projectCwd}' is not a git repository.`,
196 );
197 }
198​
199 const localBranchNames = projectIsRepository
200 ? yield* gitWorkflow
201 .listLocalBranchNames(projectCwd)
202 .pipe(asOperationFailed("Unable to list branches"))
203 : [];
204 if (localBranchNames.includes(input.branch)) {
205 const existingRef = yield* gitWorkflow
206 .listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
207 .pipe(
208 Effect.map((result) =>
209 result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
210 ),
211 Effect.orElseSucceed(() => undefined),
212 );
213 const checkoutPath = existingRef?.worktreePath ?? null;
214 return yield* failure(
215 "invalid_request",
216 `Branch '${input.branch}' already exists${
217 checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
218 }. Choose a different branch name, or delete the existing branch${
219 checkoutPath === null ? "" : " and its worktree"
220 } first.`,
221 );
222 }
223​
224 let baseRef = input.baseRef;
225 if (baseRef === undefined && !projectIsRepository) {
226 // Each repository starts from its own default branch.
227 baseRef = "HEAD";
228 } else if (baseRef === undefined) {
229 if (localStatus.refName === null) {
230 return yield* failure(
231 "invalid_request",
232 "Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
233 );
234 }
235 baseRef = localStatus.refName;
236 }
237​
238 const startFromOrigin =
239 input.startFromOrigin ?? (yield* readDefaultStartFromOrigin(project.id));
240​
241 let worktreeBaseRef = baseRef;
242 let baseRefName = baseRef;
243 let startedFromOrigin = false;
244 if (startFromOrigin && projectIsRepository) {
245 const resolvedRemoteBase = yield* gitWorkflow
246 .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef })
247 .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`));
248 if (resolvedRemoteBase !== null) {
249 worktreeBaseRef = resolvedRemoteBase.commitSha;
250 baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`;
251 startedFromOrigin = true;
252 }
253 }
254​
255 const ids = yield* handoffIds(scope);
256​
257 // Mask interruption after worktree creation through setup; binding can detach and interrupt the caller.
258 return yield* Effect.uninterruptibleMask((restore) =>
259 Effect.gen(function* () {
260 const worktree = yield* restore(
261 Effect.suspend(
262 (): Effect.Effect<
263 {
264 readonly path: string;
265 readonly refName: string;
266 readonly taskFolder: string | null;
267 },
268 GitCommandError | TaskFolderError
269 > =>
270 taskPlan === null
271 ? gitWorkflow
272 .createWorktree({
273 cwd: projectCwd,
274 refName: worktreeBaseRef,
275 newRefName: input.branch,
276 baseRefName,
277 path: null,
278 })
279 .pipe(Effect.map((created) => ({ ...created.worktree, taskFolder: null })))
280 : taskFolders
281 .create({
282 plan: taskPlan,
283 branch: input.branch,
284 projectStart: { refName: worktreeBaseRef, baseRefName },
285 baseBranch: input.baseRef,
286 startFromOrigin,
287 })
288 .pipe(
289 Effect.map((created) => {
290 // A layout command is handed the branch name, not the fetched commit.
291 startedFromOrigin =
292 !created.laidOutByProject &&
293 (startedFromOrigin || created.repositoriesStartedFromOrigin);
294 return {
295 path: created.taskFolder.projectPath,
296 refName: created.branch,
297 taskFolder: created.taskFolder.root,
298 };
299 }),
300 ),
301 ).pipe(asOperationFailed("Unable to create the worktree")),
302 );
303 const worktreePath = worktree.path;
304​
305 const reportFailed = (logMessage: string) =>
306 Effect.catchCause((cause: Cause.Cause<unknown>) => {
307 const detail = errorMessage(Cause.squash(cause));
308 return Effect.logWarning(logMessage, {
309 threadId: scope.thread.threadId,
310 worktreePath,
311 detail,
312 }).pipe(Effect.as({ status: "failed", detail } as const));
313 });
314​
315 const removeCreatedWorktree = Effect.suspend(
316 (): Effect.Effect<unknown, GitCommandError | TaskFolderError> =>
317 worktree.taskFolder === null
318 ? gitWorkflow
319 .removeWorktree({ cwd: projectCwd, path: worktreePath, force: true })
320 .pipe(
321 Effect.andThen(
322 Effect.suspend(() =>
323 gitWorkflow.deleteLocalBranch({
324 cwd: projectCwd,
325 refName: worktree.refName,
326 force: true,
327 }),
328 ),
329 ),
330 )
331 : taskFolders.remove({
332 root: worktree.taskFolder,
333 force: true,
334 forget: true,
335 deleteBranch: worktree.refName,
336 }),
337 ).pipe(Effect.ignoreCause({ log: true }));
338​
339 const recheckAndBind = Effect.gen(function* () {
340 // A concurrent UI binding may have landed during git work; do not orphan a second worktree.
341 const recheck = yield* loadThread(scope);
342 if (recheck.thread.worktreePath !== null) {
343 return yield* alreadyInWorktree(recheck.thread.worktreePath);
344 }
345 if (recheck.thread.archivedAt !== null) {
346 return yield* failure(
347 "invalid_request",
348 `Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
349 );
350 }
351 return yield* threadManagement
352 .dispatch({
353 type: "thread.metadata.update",
354 commandId: ids.commandId,
355 threadId: scope.thread.threadId,
356 branch: worktree.refName,
357 worktreePath,
358 expectedWorktreePath: null,
359 // Binding detaches the session and ends the caller; a later send could lose the race.
360 ...(input.continuationPrompt === undefined
361 ? {}
362 : {
363 continuation: {
364 messageId: ids.continuationMessageId,
365 text: input.continuationPrompt,
366 },
367 }),
368 })
369 .pipe(
370 Effect.catchCause((cause) =>
371 Cause.hasInterruptsOnly(cause)
372 ? Effect.failCause(cause as Cause.Cause<never>)
373 : Effect.fail(
374 failure(
375 "operation_failed",
376 `Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
377 ),
378 ),
379 ),
380 );
381 }).pipe(
382 // Do not remove on interruption alone; the thread binding may already have committed.
383 Effect.onError((cause) =>
384 Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
385 ),
386 );
387​
388 const bound = yield* recheckAndBind;
389 const continuation: WorktreeMcpContinuationStatus =
390 input.continuationPrompt === undefined
391 ? { status: "skipped" }
392 : {
393 status: "scheduled",
394 delivery: bound.storedEvents.some(
395 ({ event }) => event.type === "run.created" && event.payload.status !== "queued",
396 )
397 ? "started"
398 : "queued",
399 };
400​
401 yield* vcsStatusBroadcaster
402 .refreshStatus(worktreePath)
403 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
404​
405 let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
406 if (input.runSetupScript ?? true) {
407 setupScript = yield* setupScriptRunner
408 .runForThread({
409 threadId: scope.thread.threadId,
410 projectId: projection.thread.projectId,
411 projectCwd,
412 worktreePath,
413 project: {
414 id: project.id,
415 workspaceRoot: project.workspaceRoot,
416 scripts: project.scripts,
417 },
418 })
419 .pipe(
420 Effect.map((result): WorktreeMcpSetupScriptStatus =>
421 result.status === "started"
422 ? {
423 status: "started",
424 scriptName: result.scriptName,
425 terminalId: result.terminalId,
426 }
427 : result.status === "skipped-for-link"
428 ? { status: "skipped" }
429 : { status: "no-script" },
430 ),
431 reportFailed("worktree handoff setup script failed"),
432 );
433 }
434​
435 const result: WorktreeMcpHandoffResult = {
436 worktreePath,
437 branch: worktree.refName,
438 baseRef,
439 startedFromOrigin,
440 setupScript,
441 continuation,
442 note:
443 continuation.status === "scheduled"
444 ? "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."
445 : "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.",
446 };
447 return result;
448 }),
449 );
450 });
451​
452 const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
453 function* (callerScope, input) {
454 yield* requireCapability(callerScope);
455 const scope = yield* requireThreadScope(callerScope);
456 // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart.
457 return yield* Effect.uninterruptibleMask((restore) =>
458 Effect.suspend(() => {
459 if (handoffThreadsInFlight.has(scope.thread.threadId)) {
460 return Effect.fail(
461 failure(
462 "handoff_in_progress",
463 `A worktree handoff is already in progress for thread '${scope.thread.threadId}'.`,
464 ),
465 );
466 }
467 handoffThreadsInFlight.add(scope.thread.threadId);
468 return restore(performHandoff(scope, input)).pipe(
469 Effect.ensuring(
470 Effect.sync(() => handoffThreadsInFlight.delete(scope.thread.threadId)),
471 ),
472 );
473 }),
474 );
475 },
476 );
477​
478 const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
479 function* (callerScope) {
480 yield* requireCapability(callerScope);
481 const scope = yield* requireThreadScope(callerScope);
482 const projection = yield* loadThread(scope);
483 const project = yield* loadProject(scope, projection.thread.projectId);
484​
485 const defaultStartFromOrigin = yield* readDefaultStartFromOrigin(project.id);
486​
487 const result: WorktreeMcpStatusResult = {
488 attached: projection.thread.worktreePath !== null,
489 worktreePath: projection.thread.worktreePath,
490 branch: projection.thread.branch,
491 projectWorkspaceRoot: project.workspaceRoot,
492 defaultStartFromOrigin,
493 };
494 return result;
495 },
496 );
497​
498 const listRefs: WorktreeMcpService["Service"]["listRefs"] = Effect.fn(
499 "WorktreeMcpService.listRefs",
500 )(function* ({ worktreePath, workspaceRoot, ...refs }) {
501 // Storage cleanup removes a worktree but keeps its path on the thread.
502 const cwd =
503 worktreePath !== null && (yield* fileSystem.exists(worktreePath))
504 ? worktreePath
505 : workspaceRoot;
506 return yield* gitWorkflow.listRefs({ ...refs, cwd });
507 });
508​
509 return WorktreeMcpService.of({ handoff, status, listRefs });
510});
511​
512export const layer: Layer.Layer<
513 WorktreeMcpService,
514 never,
515 | SecureRandom.SecureRandom
516 | FileSystem.FileSystem
517 | ThreadManagementService.ThreadManagementService
518 | ProjectService.ProjectService
519 | ServerSettings.ServerSettingsService
520 | GitWorkflowService.GitWorkflowService
521 | ProjectSetupScriptRunner.ProjectSetupScriptRunner
522 | VcsStatusBroadcaster.VcsStatusBroadcaster
523 | TaskFolders.TaskFolders
524> = Layer.effect(WorktreeMcpService, make);