Open History to see the last commit
1import { describe, expect, it, vi } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 CommandId,
5 EnvironmentId,
6 type OrchestrationV2ThreadProjection,
7 type Project,
8 ProjectId,
9 ProviderInstanceId,
10 ThreadId,
11 WorktreeMcpHandoffInput,
12} from "@t3tools/contracts";
13import * as Cause from "effect/Cause";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Schema from "effect/Schema";
21
22import * as GitWorkflowService from "../git/GitWorkflowService.ts";
23import {
24 OrchestratorDispatchError,
25 OrchestratorProjectionError,
26} from "../orchestration-v2/Orchestrator.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 type * as McpInvocationContext from "./McpInvocationContext.ts";
33import * as WorktreeMcpService from "./WorktreeMcpService.ts";
34
35const environmentId = EnvironmentId.make("environment-worktree-test");
36const threadId = ThreadId.make("thread-worktree-test");
37const projectId = ProjectId.make("project-worktree-test");
38const workspaceRoot = "/repo/project";
39
40const makeScope = (
41 capabilities: ReadonlySet<McpInvocationContext.McpCapability>,
42): McpInvocationContext.McpInvocationScope => ({
43 environmentId,
44 requestNamespace: "provider-session-worktree-test",
45 thread: {
46 threadId,
47 providerSessionId: "provider-session-worktree-test",
48 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
49 },
50 client: undefined,
51 capabilities,
52 issuedAt: 1,
53});
54
55interface ThreadFixture {
56 readonly branch?: string | null;
57 readonly worktreePath?: string | null;
58 readonly archivedAt?: string | null;
59 readonly deletedAt?: string | null;
60}
61
62const makeProjection = (overrides: ThreadFixture = {}): OrchestrationV2ThreadProjection =>
63 ({
64 thread: {
65 id: threadId,
66 projectId,
67 title: "Worktree test thread",
68 branch: null,
69 worktreePath: null,
70 archivedAt: null,
71 deletedAt: null,
72 ...overrides,
73 },
74 }) as OrchestrationV2ThreadProjection;
75
76const project: Project = {
77 id: projectId,
78 title: "Worktree test project",
79 workspaceRoot,
80 defaultModelSelection: null,
81 scripts: [],
82 createdAt: "2026-01-01T00:00:00.000Z",
83 updatedAt: "2026-01-01T00:00:00.000Z",
84 deletedAt: null,
85} as Project;
86
87interface HarnessOptions {
88 readonly thread?: ThreadFixture | null;
89 readonly threadReadError?: "projection" | "dispatch";
90 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
91 readonly currentBranch?: string | null;
92 readonly notARepo?: boolean;
93 readonly newWorktreesStartFromOrigin?: boolean;
94 readonly setupScript?: "started" | "no-script" | "fails" | "dies";
95 readonly dispatchFails?: boolean;
96 readonly dispatchDies?: boolean;
97 readonly dispatchInterrupts?: boolean;
98 readonly dispatchGate?: Effect.Effect<void>;
99 readonly threadAttachedOnRecheck?: boolean;
100 readonly threadArchivedOnRecheck?: boolean;
101 readonly threadReadFailsOnRecheck?: boolean;
102 readonly continuation?: "queued" | "fails" | "dies";
103 readonly projectMissing?: boolean;
104 readonly projectReadFails?: boolean;
105 readonly existingBranchWorktreePath?: string | null;
106 readonly createWorktreeFails?: boolean;
107 readonly fetchRemoteFails?: boolean;
108 readonly resolveRemoteFails?: boolean;
109 readonly removeWorktreeFails?: boolean;
110 readonly deleteLocalBranchFails?: boolean;
111 readonly createWorktreeGate?: Effect.Effect<void>;
112}
113
114const makeHarness = (options: HarnessOptions = {}) => {
115 const thread = options.thread === undefined ? {} : options.thread;
116 const scope = makeScope(options.capabilities ?? new Set(["preview", "worktree"]));
117 const dispatch = vi.fn((_: unknown) =>
118 (options.dispatchGate ?? Effect.void).pipe(
119 Effect.andThen(
120 options.dispatchInterrupts
121 ? (Effect.failCause(Cause.interrupt()) as never)
122 : options.dispatchDies
123 ? Effect.die(new Error("dispatch defect"))
124 : options.dispatchFails
125 ? (Effect.fail("simulated dispatch failure") as never)
126 : Effect.succeed({ sequence: 1, storedEvents: [] }),
127 ),
128 ),
129 );
130 const listLocalBranchNames = vi.fn((_: string) =>
131 Effect.succeed(
132 options.existingBranchWorktreePath === undefined
133 ? ["dev"]
134 : ["dev", "feature/taken", "feature/taken-idle"],
135 ),
136 );
137 const getThreadRecords = vi.fn((id: ThreadId) => {
138 if (options.threadReadError === "dispatch") {
139 return Effect.fail(
140 new OrchestratorDispatchError({
141 commandId: CommandId.make("command:test:read"),
142 commandType: "thread.metadata.update",
143 }),
144 ) as never;
145 }
146 if (options.threadReadFailsOnRecheck === true && getThreadRecords.mock.calls.length > 1) {
147 return Effect.fail(
148 new OrchestratorDispatchError({
149 commandId: CommandId.make("command:test:recheck"),
150 commandType: "thread.metadata.update",
151 }),
152 ) as never;
153 }
154 if (
155 options.threadAttachedOnRecheck === true &&
156 getThreadRecords.mock.calls.length > 1 &&
157 thread !== null
158 ) {
159 return Effect.succeed(
160 makeProjection({ ...thread, worktreePath: "/worktrees/project/raced" }),
161 );
162 }
163 if (
164 options.threadArchivedOnRecheck === true &&
165 getThreadRecords.mock.calls.length > 1 &&
166 thread !== null
167 ) {
168 return Effect.succeed(makeProjection({ ...thread, archivedAt: "2026-01-02T00:00:00.000Z" }));
169 }
170 return id === threadId && thread !== null
171 ? Effect.succeed(makeProjection(thread))
172 : Effect.fail(new OrchestratorProjectionError({ threadId: id }));
173 });
174 const sendToThread = vi.fn((_: unknown) => {
175 switch (options.continuation ?? "queued") {
176 case "fails":
177 return Effect.fail(
178 new ThreadManagementService.ThreadManagementThreadArchivedError({
179 threadId,
180 }),
181 );
182 case "dies":
183 return Effect.die(new Error("send defect"));
184 default:
185 return Effect.succeed({
186 delivery: "queued",
187 } as ThreadManagementService.ThreadManagementSendResult);
188 }
189 });
190 const getById = vi.fn((id: ProjectId) =>
191 options.projectReadFails
192 ? (Effect.fail("simulated project read failure") as never)
193 : Effect.succeed(
194 id === projectId && options.projectMissing !== true
195 ? Option.some(project)
196 : Option.none(),
197 ),
198 );
199 const removeWorktree = vi.fn((_: unknown) =>
200 options.removeWorktreeFails
201 ? (Effect.fail("simulated worktree removal failure") as never)
202 : Effect.void,
203 );
204 const deleteLocalBranch = vi.fn((_: unknown) =>
205 options.deleteLocalBranchFails
206 ? (Effect.fail("simulated local branch deletion failure") as never)
207 : Effect.void,
208 );
209 const fetchRemote = vi.fn((_: unknown) =>
210 options.fetchRemoteFails ? (Effect.fail("simulated fetch failure") as never) : Effect.void,
211 );
212 const resolveRemoteTrackingCommit = vi.fn((_: unknown) =>
213 options.resolveRemoteFails
214 ? (Effect.fail("simulated remote resolve failure") as never)
215 : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }),
216 );
217 const createWorktree = vi.fn(
218 (input: { readonly newRefName?: string | undefined; readonly path: string | null }) =>
219 options.createWorktreeFails
220 ? (Effect.fail("simulated worktree creation failure") as never)
221 : (options.createWorktreeGate ?? Effect.void).pipe(
222 Effect.andThen(
223 Effect.succeed({
224 worktree: {
225 path: input.path ?? `/worktrees/project/${input.newRefName}`,
226 refName: input.newRefName ?? "detached",
227 },
228 }),
229 ),
230 ),
231 );
232 const listRefs = vi.fn((input: { readonly query?: string | undefined }) =>
233 Effect.succeed({
234 refs:
235 options.existingBranchWorktreePath === undefined
236 ? []
237 : [
238 {
239 name: input.query ?? "",
240 current: false,
241 isDefault: false,
242 worktreePath: options.existingBranchWorktreePath,
243 },
244 ],
245 isRepo: true,
246 hasPrimaryRemote: true,
247 nextCursor: null,
248 totalCount: options.existingBranchWorktreePath === undefined ? 0 : 1,
249 }),
250 );
251 const localStatus = vi.fn((_: unknown) =>
252 Effect.succeed({
253 isRepo: options.notARepo !== true,
254 hasPrimaryRemote: true,
255 isDefaultRef: false,
256 refName: options.currentBranch === undefined ? "dev" : options.currentBranch,
257 hasWorkingTreeChanges: false,
258 workingTree: { files: [], insertions: 0, deletions: 0 },
259 }),
260 );
261 const refreshStatus = vi.fn((_: string) => Effect.die("refreshStatus stub"));
262 const runForThread = vi.fn((input: { readonly worktreePath: string }) => {
263 switch (options.setupScript ?? "started") {
264 case "no-script":
265 return Effect.succeed({ status: "no-script" } as const);
266 case "dies":
267 return Effect.die(new Error("setup runner defect"));
268 case "fails":
269 return Effect.fail(
270 new ProjectSetupScriptRunner.ProjectSetupScriptProjectNotFoundError({
271 threadId,
272 worktreePath: input.worktreePath,
273 }),
274 );
275 default:
276 return Effect.succeed({
277 status: "started",
278 async: false,
279 scriptId: "setup",
280 scriptName: "Setup",
281 scriptCommand: "vp install",
282 terminalId: "setup-terminal",
283 cwd: input.worktreePath,
284 } as const);
285 }
286 });
287
288 const layer = WorktreeMcpService.layer.pipe(
289 Layer.provide(
290 Layer.mergeAll(
291 Layer.mock(ThreadManagementService.ThreadManagementService)({
292 dispatch,
293 getThreadRecords,
294 sendToThread,
295 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
296 Layer.mock(ProjectService.ProjectService)({
297 getById,
298 } satisfies Partial<ProjectService.ProjectService["Service"]>),
299 ServerSettings.layerTest({
300 newWorktreesStartFromOrigin: options.newWorktreesStartFromOrigin ?? false,
301 }),
302 Layer.mock(GitWorkflowService.GitWorkflowService)({
303 listRefs,
304 listLocalBranchNames,
305 localStatus,
306 fetchRemote,
307 resolveRemoteTrackingCommit,
308 createWorktree,
309 removeWorktree,
310 deleteLocalBranch,
311 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
312 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
313 runForThread,
314 } satisfies Partial<ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]>),
315 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
316 refreshStatus,
317 } satisfies Partial<VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]>),
318 NodeServices.layer,
319 ),
320 ),
321 );
322
323 return {
324 layer,
325 scope,
326 dispatch,
327 sendToThread,
328 fetchRemote,
329 resolveRemoteTrackingCommit,
330 createWorktree,
331 removeWorktree,
332 deleteLocalBranch,
333 localStatus,
334 runForThread,
335 };
336};
337
338const expectTypedFailure = (exit: Exit.Exit<unknown, unknown>, expected: object): void => {
339 if (!Exit.isFailure(exit)) {
340 expect.fail(`Expected a failure exit, got: ${JSON.stringify(exit)}`);
341 }
342 const reason = exit.cause.reasons[0];
343 if (reason?._tag !== "Fail") {
344 expect.fail(`Expected a typed Fail cause, got: ${reason?._tag ?? "no reason"}`);
345 }
346 expect(reason.error).toMatchObject(expected);
347};
348
349// Resolves the service once from the harness layer; used by tests that must
350// make several calls against the SAME instance (the in-flight guard lives in
351// the layer's closure, so a fresh layer per call would never see it).
352const resolveService = (harness: ReturnType<typeof makeHarness>) =>
353 Effect.gen(function* () {
354 return yield* WorktreeMcpService.WorktreeMcpService;
355 }).pipe(Effect.provide(harness.layer));
356
357const runHandoff = (
358 harness: ReturnType<typeof makeHarness>,
359 input: Parameters<WorktreeMcpService.WorktreeMcpService["Service"]["handoff"]>[1],
360) =>
361 Effect.gen(function* () {
362 const service = yield* WorktreeMcpService.WorktreeMcpService;
363 return yield* service.handoff(harness.scope, input);
364 }).pipe(Effect.provide(harness.layer));
365
366const runStatus = (harness: ReturnType<typeof makeHarness>) =>
367 Effect.gen(function* () {
368 const service = yield* WorktreeMcpService.WorktreeMcpService;
369 return yield* service.status(harness.scope);
370 }).pipe(Effect.provide(harness.layer));
371
372// Decodes tool arguments the way the MCP tool does before calling the service.
373const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
374
375describe("t3_worktree_handoff", () => {
376 it.effect("creates a worktree from the current branch and re-points the thread", () => {
377 const harness = makeHarness();
378 return Effect.gen(function* () {
379 const result = yield* runHandoff(harness, { branch: "feature/handoff" });
380
381 expect(result.branch).toBe("feature/handoff");
382 expect(result.baseRef).toBe("dev");
383 expect(result.startedFromOrigin).toBe(false);
384 expect(result.worktreePath).toBe("/worktrees/project/feature/handoff");
385 expect(result.setupScript).toMatchObject({
386 status: "started",
387 scriptName: "Setup",
388 });
389
390 expect(harness.fetchRemote).not.toHaveBeenCalled();
391 expect(harness.createWorktree).toHaveBeenCalledWith({
392 cwd: workspaceRoot,
393 refName: "dev",
394 newRefName: "feature/handoff",
395 baseRefName: "dev",
396 path: null,
397 });
398 expect(harness.dispatch).toHaveBeenCalledWith(
399 expect.objectContaining({
400 type: "thread.metadata.update",
401 threadId,
402 branch: "feature/handoff",
403 worktreePath: "/worktrees/project/feature/handoff",
404 expectedWorktreePath: null,
405 }),
406 );
407 expect(harness.runForThread).toHaveBeenCalledWith({
408 threadId,
409 projectId,
410 projectCwd: workspaceRoot,
411 worktreePath: "/worktrees/project/feature/handoff",
412 project: { id: projectId, workspaceRoot, scripts: [] },
413 });
414 });
415 });
416
417 it.effect("skips the continuation when no continuationPrompt is given", () => {
418 const harness = makeHarness();
419 return Effect.gen(function* () {
420 const result = yield* runHandoff(harness, { branch: "feature/no-continuation" });
421 expect(result.continuation).toEqual({ status: "skipped" });
422 expect(harness.sendToThread).not.toHaveBeenCalled();
423 });
424 });
425
426 it.effect("queues the continuation prompt as the thread's next message", () => {
427 const harness = makeHarness();
428 return Effect.gen(function* () {
429 const result = yield* runHandoff(harness, {
430 branch: "feature/continue",
431 continuationPrompt: "Keep fixing the login bug in the new worktree.",
432 });
433
434 expect(result.continuation).toEqual({ status: "scheduled", delivery: "queued" });
435 expect(harness.sendToThread).toHaveBeenCalledWith(
436 expect.objectContaining({
437 projectId,
438 threadId,
439 text: "Keep fixing the login bug in the new worktree.",
440 mode: "queue",
441 createdBy: "agent",
442 creationSource: "mcp",
443 }),
444 );
445 expect(harness.sendToThread.mock.invocationCallOrder[0]).toBeLessThan(
446 harness.runForThread.mock.invocationCallOrder[0]!,
447 );
448 });
449 });
450
451 it.effect("reports a continuation failure without failing the handoff", () => {
452 const harness = makeHarness({ continuation: "fails" });
453 return Effect.gen(function* () {
454 const result = yield* runHandoff(harness, {
455 branch: "feature/continue-fails",
456 continuationPrompt: "Keep going.",
457 });
458 expect(result.continuation).toMatchObject({ status: "failed" });
459 expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails");
460 expect(harness.dispatch).toHaveBeenCalled();
461 });
462 });
463
464 it.effect("reports a continuation defect without failing the handoff", () => {
465 const harness = makeHarness({ continuation: "dies" });
466 return Effect.gen(function* () {
467 const result = yield* runHandoff(harness, {
468 branch: "feature/continue-dies",
469 continuationPrompt: "Keep going.",
470 });
471 expect(result.continuation).toEqual({ status: "failed", detail: "send defect" });
472 expect(result.setupScript).toMatchObject({ status: "started" });
473 });
474 });
475
476 it.effect("does not queue a continuation when the thread update fails", () => {
477 const harness = makeHarness({ dispatchFails: true });
478 return Effect.gen(function* () {
479 const exit = yield* Effect.exit(
480 runHandoff(harness, {
481 branch: "feature/dispatch-fails-continue",
482 continuationPrompt: "Keep going.",
483 }),
484 );
485 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
486 expect(harness.sendToThread).not.toHaveBeenCalled();
487 });
488 });
489
490 it.effect("starts from origin and honors an explicit baseRef", () => {
491 const harness = makeHarness();
492 return Effect.gen(function* () {
493 const result = yield* runHandoff(harness, {
494 branch: "feature/from-origin",
495 baseRef: "dev",
496 startFromOrigin: true,
497 runSetupScript: false,
498 });
499
500 expect(harness.fetchRemote).toHaveBeenCalledWith({
501 cwd: workspaceRoot,
502 remoteName: "origin",
503 });
504 expect(harness.resolveRemoteTrackingCommit).toHaveBeenCalledWith({
505 cwd: workspaceRoot,
506 refName: "dev",
507 fallbackRemoteName: "origin",
508 });
509 expect(harness.createWorktree).toHaveBeenCalledWith({
510 cwd: workspaceRoot,
511 refName: "abc123",
512 newRefName: "feature/from-origin",
513 baseRefName: "dev",
514 path: null,
515 });
516 expect(harness.localStatus).toHaveBeenCalled();
517 expect(harness.runForThread).not.toHaveBeenCalled();
518 expect(result.worktreePath).toBe("/worktrees/project/feature/from-origin");
519 expect(result.startedFromOrigin).toBe(true);
520 expect(result.setupScript).toEqual({ status: "skipped" });
521 });
522 });
523
524 it.effect("uses the server setting for startFromOrigin when unspecified", () => {
525 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
526 return Effect.gen(function* () {
527 const result = yield* runHandoff(harness, { branch: "feature/settings-origin" });
528 expect(result.startedFromOrigin).toBe(true);
529 expect(harness.fetchRemote).toHaveBeenCalled();
530 });
531 });
532
533 it.effect("fails when the thread is already attached to a worktree", () => {
534 const harness = makeHarness({
535 thread: { branch: "feature/existing", worktreePath: "/worktrees/project/existing" },
536 });
537 return Effect.gen(function* () {
538 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/second" }));
539 expectTypedFailure(exit, {
540 _tag: "WorktreeMcpFailure",
541 code: "already_in_worktree",
542 });
543 expect(harness.createWorktree).not.toHaveBeenCalled();
544 });
545 });
546
547 it.effect("fails when the thread does not exist", () => {
548 const harness = makeHarness({ thread: null });
549 return Effect.gen(function* () {
550 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/missing" }));
551 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
552 expect(harness.createWorktree).not.toHaveBeenCalled();
553 });
554 });
555
556 it.effect("treats a soft-deleted thread as not found", () => {
557 const harness = makeHarness({ thread: { deletedAt: "2026-01-02T00:00:00.000Z" } });
558 return Effect.gen(function* () {
559 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/deleted" }));
560 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
561 expect(harness.createWorktree).not.toHaveBeenCalled();
562 });
563 });
564
565 it.effect("maps a non-projection orchestrator error to operation_failed", () => {
566 const harness = makeHarness({ threadReadError: "dispatch" });
567 return Effect.gen(function* () {
568 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/read-error" }));
569 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
570 expect(harness.createWorktree).not.toHaveBeenCalled();
571 });
572 });
573
574 it.effect("fails when the project does not exist", () => {
575 const harness = makeHarness({ projectMissing: true });
576 return Effect.gen(function* () {
577 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-project" }));
578 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
579 expect(harness.createWorktree).not.toHaveBeenCalled();
580 });
581 });
582
583 it.effect("maps a project read error to operation_failed", () => {
584 const harness = makeHarness({ projectReadFails: true });
585 return Effect.gen(function* () {
586 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/project-error" }));
587 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
588 expect(harness.createWorktree).not.toHaveBeenCalled();
589 });
590 });
591
592 it.effect("fails when the project workspace is not a git repository", () => {
593 const harness = makeHarness({ notARepo: true });
594 return Effect.gen(function* () {
595 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-repo" }));
596 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
597 expect(harness.createWorktree).not.toHaveBeenCalled();
598 });
599 });
600
601 it.effect("rejects an existing branch with an actionable error naming its checkout", () => {
602 const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" });
603 return Effect.gen(function* () {
604 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken" }));
605 if (!Exit.isFailure(exit)) {
606 return expect.fail("expected a failure exit");
607 }
608 const reason = exit.cause.reasons[0];
609 expect(reason?._tag).toBe("Fail");
610 const error = (reason as { readonly error: { code: string; message: string } }).error;
611 expect(error.code).toBe("invalid_request");
612 expect(error.message).toContain("feature/taken");
613 expect(error.message).toContain("already exists");
614 expect(error.message).toContain("/elsewhere/checkout");
615 expect(harness.createWorktree).not.toHaveBeenCalled();
616 expect(harness.fetchRemote).not.toHaveBeenCalled();
617 });
618 });
619
620 it.effect("rejects an existing branch that is not checked out anywhere", () => {
621 const harness = makeHarness({ existingBranchWorktreePath: null });
622 return Effect.gen(function* () {
623 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken-idle" }));
624 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
625 expect(harness.createWorktree).not.toHaveBeenCalled();
626 });
627 });
628
629 it.effect("does not trip the pre-flight on similarly named branches", () => {
630 const harness = makeHarness({ existingBranchWorktreePath: null });
631 return Effect.gen(function* () {
632 const result = yield* runHandoff(harness, { branch: "feature/take" });
633 expect(result.branch).toBe("feature/take");
634 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
635 });
636 });
637
638 it.effect("rejects a non-repository workspace even when baseRef is explicit", () => {
639 const harness = makeHarness({ notARepo: true });
640 return Effect.gen(function* () {
641 const exit = yield* Effect.exit(
642 runHandoff(harness, { branch: "feature/no-repo-baseref", baseRef: "dev" }),
643 );
644 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
645 expect(harness.createWorktree).not.toHaveBeenCalled();
646 });
647 });
648
649 it.effect("propagates an interrupted dispatch without rolling back the worktree", () => {
650 const harness = makeHarness({ dispatchInterrupts: true });
651 return Effect.gen(function* () {
652 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-int" }));
653 if (!Exit.isFailure(exit)) {
654 return expect.fail("expected a failure exit");
655 }
656 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
657 expect(harness.removeWorktree).not.toHaveBeenCalled();
658 });
659 });
660
661 it.effect("maps a worktree creation failure to operation_failed", () => {
662 const harness = makeHarness({ createWorktreeFails: true });
663 return Effect.gen(function* () {
664 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/create-fails" }));
665 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
666 expect(harness.dispatch).not.toHaveBeenCalled();
667 expect(harness.removeWorktree).not.toHaveBeenCalled();
668 });
669 });
670
671 it.effect("maps an origin fetch failure to operation_failed", () => {
672 const harness = makeHarness({ fetchRemoteFails: true });
673 return Effect.gen(function* () {
674 const exit = yield* Effect.exit(
675 runHandoff(harness, { branch: "feature/fetch-fails", startFromOrigin: true }),
676 );
677 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
678 expect(harness.createWorktree).not.toHaveBeenCalled();
679 });
680 });
681
682 it.effect("maps a remote-tracking resolve failure to operation_failed", () => {
683 const harness = makeHarness({ resolveRemoteFails: true });
684 return Effect.gen(function* () {
685 const exit = yield* Effect.exit(
686 runHandoff(harness, { branch: "feature/resolve-fails", startFromOrigin: true }),
687 );
688 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
689 expect(harness.createWorktree).not.toHaveBeenCalled();
690 });
691 });
692
693 it.effect("removes the created worktree when the thread update dies with a defect", () => {
694 const harness = makeHarness({ dispatchDies: true });
695 return Effect.gen(function* () {
696 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-defect" }));
697 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
698 expect(harness.removeWorktree).toHaveBeenCalledWith({
699 cwd: workspaceRoot,
700 path: "/worktrees/project/feature/dispatch-defect",
701 force: true,
702 });
703 });
704 });
705
706 it.effect("re-checks attachment after creating the worktree and backs out on a race", () => {
707 const harness = makeHarness({ threadAttachedOnRecheck: true });
708 return Effect.gen(function* () {
709 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/raced" }));
710 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
711 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
712 expect(harness.removeWorktree).toHaveBeenCalledWith({
713 cwd: workspaceRoot,
714 path: "/worktrees/project/feature/raced",
715 force: true,
716 });
717 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
718 cwd: workspaceRoot,
719 refName: "feature/raced",
720 force: true,
721 });
722 expect(harness.dispatch).not.toHaveBeenCalled();
723 });
724 });
725
726 it.effect("removes the created worktree when the recheck read fails", () => {
727 const harness = makeHarness({ threadReadFailsOnRecheck: true });
728 return Effect.gen(function* () {
729 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/recheck-fails" }));
730 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
731 expect(harness.removeWorktree).toHaveBeenCalledWith({
732 cwd: workspaceRoot,
733 path: "/worktrees/project/feature/recheck-fails",
734 force: true,
735 });
736 expect(harness.dispatch).not.toHaveBeenCalled();
737 });
738 });
739
740 it.effect("backs out when the thread is archived during worktree creation", () => {
741 const harness = makeHarness({ threadArchivedOnRecheck: true });
742 return Effect.gen(function* () {
743 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived-race" }));
744 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
745 expect(harness.dispatch).not.toHaveBeenCalled();
746 expect(harness.removeWorktree).toHaveBeenCalledWith({
747 cwd: workspaceRoot,
748 path: "/worktrees/project/feature/archived-race",
749 force: true,
750 });
751 });
752 });
753
754 it.effect("rejects a handoff for an archived thread", () => {
755 const harness = makeHarness({ thread: { archivedAt: "2026-01-02T00:00:00.000Z" } });
756 return Effect.gen(function* () {
757 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived" }));
758 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
759 expect(harness.createWorktree).not.toHaveBeenCalled();
760 });
761 });
762
763 it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
764 Effect.gen(function* () {
765 const gate = yield* Deferred.make<void>();
766 const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
767
768 const fiber = yield* Effect.forkChild(
769 runHandoff(harness, {
770 branch: "feature/interrupted",
771 continuationPrompt: "Keep going in the worktree.",
772 }),
773 );
774 yield* Effect.yieldNow;
775 const interruption = yield* Effect.forkChild(Fiber.interrupt(fiber));
776 yield* Effect.yieldNow;
777 yield* Deferred.succeed(gate, undefined);
778 yield* Fiber.await(fiber);
779 yield* Fiber.join(interruption);
780
781 expect(harness.dispatch).toHaveBeenCalledTimes(1);
782 expect(harness.sendToThread).toHaveBeenCalledTimes(1);
783 expect(harness.runForThread).toHaveBeenCalledTimes(1);
784 }),
785 );
786
787 it.effect("still fails with a typed error when the rollback removal also fails", () => {
788 const harness = makeHarness({ dispatchFails: true, removeWorktreeFails: true });
789 return Effect.gen(function* () {
790 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/rollback-fails" }));
791 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
792 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
793 expect(harness.deleteLocalBranch).not.toHaveBeenCalled();
794 });
795 });
796
797 it.effect("preserves the typed failure when rollback branch deletion also fails", () => {
798 const harness = makeHarness({ dispatchFails: true, deleteLocalBranchFails: true });
799 return Effect.gen(function* () {
800 const exit = yield* Effect.exit(
801 runHandoff(harness, { branch: "feature/rollback-branch-fails" }),
802 );
803 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
804 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
805 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
806 cwd: workspaceRoot,
807 refName: "feature/rollback-branch-fails",
808 force: true,
809 });
810 });
811 });
812
813 it.effect("creates the worktree in the managed directory even when a call names a path", () => {
814 const harness = makeHarness();
815 return Effect.gen(function* () {
816 const input = yield* decodeHandoffInput({
817 branch: "feature/elsewhere",
818 path: "/home/user/.ssh/checkout",
819 });
820 const result = yield* runHandoff(harness, input);
821 expect(harness.createWorktree).toHaveBeenCalledWith(expect.objectContaining({ path: null }));
822 expect(result.worktreePath).toBe("/worktrees/project/feature/elsewhere");
823 });
824 });
825
826 it.effect("releases the per-thread guard after a failed handoff", () => {
827 const harness = makeHarness({
828 thread: { worktreePath: "/worktrees/project/existing" },
829 });
830 return Effect.gen(function* () {
831 const service = yield* resolveService(harness);
832
833 const first = yield* Effect.exit(
834 service.handoff(harness.scope, { branch: "feature/guard-1" }),
835 );
836 expectTypedFailure(first, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
837 const second = yield* Effect.exit(
838 service.handoff(harness.scope, { branch: "feature/guard-2" }),
839 );
840 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
841 });
842 });
843
844 it.effect("fails when the worktree capability is missing", () => {
845 const harness = makeHarness({ capabilities: new Set(["preview"]) });
846 return Effect.gen(function* () {
847 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-capability" }));
848 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
849 });
850 });
851
852 it.effect("serializes concurrent handoffs for the same thread", () =>
853 Effect.gen(function* () {
854 const gate = yield* Deferred.make<void>();
855 const harness = makeHarness({ createWorktreeGate: Deferred.await(gate) });
856
857 const service = yield* resolveService(harness);
858
859 const first = yield* Effect.forkChild(
860 Effect.exit(service.handoff(harness.scope, { branch: "feature/race-1" })),
861 );
862 yield* Effect.yieldNow;
863
864 const second = yield* Effect.exit(
865 service.handoff(harness.scope, { branch: "feature/race-2" }),
866 );
867 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "handoff_in_progress" });
868
869 yield* Deferred.succeed(gate, undefined);
870 const firstExit = yield* Fiber.join(first);
871 expect(Exit.isSuccess(firstExit)).toBe(true);
872 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
873 }),
874 );
875
876 it.effect("removes the created worktree when the thread update fails", () => {
877 const harness = makeHarness({ dispatchFails: true });
878 return Effect.gen(function* () {
879 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-fails" }));
880 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
881 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
882 expect(harness.removeWorktree).toHaveBeenCalledWith({
883 cwd: workspaceRoot,
884 path: "/worktrees/project/feature/dispatch-fails",
885 force: true,
886 });
887 });
888 });
889
890 it.effect("fails when baseRef is omitted and HEAD is detached", () => {
891 const harness = makeHarness({ currentBranch: null });
892 return Effect.gen(function* () {
893 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/detached" }));
894 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
895 });
896 });
897
898 it.effect("reports setup script failure without failing the handoff", () => {
899 const harness = makeHarness({ setupScript: "fails" });
900 return Effect.gen(function* () {
901 const result = yield* runHandoff(harness, { branch: "feature/setup-fails" });
902 expect(result.setupScript.status).toBe("failed");
903 expect(harness.dispatch).toHaveBeenCalled();
904 });
905 });
906
907 it.effect("reports a setup script defect without failing the handoff", () => {
908 const harness = makeHarness({ setupScript: "dies" });
909 return Effect.gen(function* () {
910 const result = yield* runHandoff(harness, { branch: "feature/setup-dies" });
911 expect(result.setupScript).toEqual({ status: "failed", detail: "setup runner defect" });
912 expect(harness.dispatch).toHaveBeenCalled();
913 });
914 });
915});
916
917describe("t3_worktree_status", () => {
918 it.effect("reports an unattached thread", () => {
919 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
920 return Effect.gen(function* () {
921 const result = yield* runStatus(harness);
922 expect(result).toEqual({
923 attached: false,
924 worktreePath: null,
925 branch: null,
926 projectWorkspaceRoot: workspaceRoot,
927 defaultStartFromOrigin: true,
928 });
929 });
930 });
931
932 it.effect("reports an attached thread's worktree and branch", () => {
933 const harness = makeHarness({
934 thread: {
935 worktreePath: "/worktrees/project/existing",
936 branch: "feature/existing",
937 },
938 });
939 return Effect.gen(function* () {
940 const result = yield* runStatus(harness);
941 expect(result).toMatchObject({
942 attached: true,
943 worktreePath: "/worktrees/project/existing",
944 branch: "feature/existing",
945 defaultStartFromOrigin: false,
946 });
947 });
948 });
949
950 it.effect("fails when the worktree capability is missing", () => {
951 const harness = makeHarness({ capabilities: new Set(["preview"]) });
952 return Effect.gen(function* () {
953 const exit = yield* Effect.exit(runStatus(harness));
954 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
955 });
956 });
957
958 it.effect("fails when the thread does not exist", () => {
959 const harness = makeHarness({ thread: null });
960 return Effect.gen(function* () {
961 const exit = yield* Effect.exit(runStatus(harness));
962 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
963 });
964 });
965
966 it.effect("fails when the project does not exist", () => {
967 const harness = makeHarness({ projectMissing: true });
968 return Effect.gen(function* () {
969 const exit = yield* Effect.exit(runStatus(harness));
970 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
971 });
972 });
973});
974
975describe("WorktreeMcpHandoffInput schema", () => {
976 const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
977
978 it.effect("rejects a missing or blank branch", () =>
979 Effect.gen(function* () {
980 expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true);
981 expect(Exit.isFailure(yield* Effect.exit(decode({ branch: " " })))).toBe(true);
982 }),
983 );
984
985 it.effect("rejects a blank continuationPrompt", () =>
986 Effect.gen(function* () {
987 const exit = yield* Effect.exit(decode({ branch: "feature/x", continuationPrompt: " " }));
988 expect(Exit.isFailure(exit)).toBe(true);
989 }),
990 );
991});