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