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 {
29 ThreadManagementService,
30 ThreadManagementThreadArchivedError,
31 type ThreadManagementSendResult,
32} from "../orchestration-v2/ThreadManagementService.ts";
33import * as ProjectService from "../project/ProjectService.ts";
34import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
35import * as ServerSettings from "../serverSettings.ts";
36import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
37import type * as McpInvocationContext from "./McpInvocationContext.ts";
38import { layer as worktreeMcpServiceLayer, WorktreeMcpService } from "./WorktreeMcpService.ts";
39
40const environmentId = EnvironmentId.make("environment-worktree-test");
41const threadId = ThreadId.make("thread-worktree-test");
42const projectId = ProjectId.make("project-worktree-test");
43const workspaceRoot = "/repo/project";
44
45const makeScope = (
46 capabilities: ReadonlySet<McpInvocationContext.McpCapability>,
47): McpInvocationContext.McpInvocationScope => ({
48 environmentId,
49 threadId,
50 providerSessionId: "provider-session-worktree-test",
51 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
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 getThreadProjection = 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 && getThreadProjection.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 getThreadProjection.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 getThreadProjection.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 ThreadManagementThreadArchivedError({
181 threadId,
182 }),
183 );
184 case "dies":
185 return Effect.die(new Error("send defect"));
186 default:
187 return Effect.succeed({ delivery: "queued" } as 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 // Optional deterministic Path semantics: providing this BEFORE the general
289 // mocks means the service resolves Path here rather than from NodeServices,
290 // so absolute-path validation is testable independently of the host OS. The
291 // service only calls isAbsolute; the minimal per-platform semantics are
292 // inlined so the test does not depend on the host's path module.
293 const win32IsAbsolute = (value: string) => /^(?:[a-zA-Z]:[\\/]|[\\/])/.test(value);
294 const posixIsAbsolute = (value: string) => value.startsWith("/");
295 const serviceLayer =
296 options.pathSemantics === undefined
297 ? worktreeMcpServiceLayer
298 : worktreeMcpServiceLayer.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 = serviceLayer.pipe(
306 Layer.provide(
307 Layer.mergeAll(
308 Layer.mock(ThreadManagementService)({
309 dispatch,
310 getThreadProjection,
311 sendToThread,
312 } satisfies Partial<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)({
333 refreshStatus,
334 } satisfies Partial<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;
372 }).pipe(Effect.provide(harness.layer));
373
374const runHandoff = (
375 harness: ReturnType<typeof makeHarness>,
376 input: Parameters<WorktreeMcpService["Service"]["handoff"]>[1],
377) =>
378 Effect.gen(function* () {
379 const service = yield* 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;
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 // The continuation must be durably queued before anything slower runs.
460 expect(harness.sendToThread.mock.invocationCallOrder[0]).toBeLessThan(
461 harness.runForThread.mock.invocationCallOrder[0]!,
462 );
463 });
464 });
465
466 it.effect("reports a continuation failure without failing the handoff", () => {
467 const harness = makeHarness({ continuation: "fails" });
468 return Effect.gen(function* () {
469 const result = yield* runHandoff(harness, {
470 branch: "feature/continue-fails",
471 continuationPrompt: "Keep going.",
472 });
473 expect(result.continuation).toMatchObject({ status: "failed" });
474 expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails");
475 expect(harness.dispatch).toHaveBeenCalled();
476 });
477 });
478
479 it.effect("reports a continuation defect without failing the handoff", () => {
480 const harness = makeHarness({ continuation: "dies" });
481 return Effect.gen(function* () {
482 const result = yield* runHandoff(harness, {
483 branch: "feature/continue-dies",
484 continuationPrompt: "Keep going.",
485 });
486 expect(result.continuation).toEqual({ status: "failed", detail: "send defect" });
487 expect(result.setupScript).toMatchObject({ status: "started" });
488 });
489 });
490
491 it.effect("does not queue a continuation when the thread update fails", () => {
492 const harness = makeHarness({ dispatchFails: true });
493 return Effect.gen(function* () {
494 const exit = yield* Effect.exit(
495 runHandoff(harness, {
496 branch: "feature/dispatch-fails-continue",
497 continuationPrompt: "Keep going.",
498 }),
499 );
500 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
501 expect(harness.sendToThread).not.toHaveBeenCalled();
502 });
503 });
504
505 it.effect("starts from origin and honors explicit baseRef and path", () => {
506 const harness = makeHarness();
507 return Effect.gen(function* () {
508 const result = yield* runHandoff(harness, {
509 branch: "feature/from-origin",
510 baseRef: "dev",
511 startFromOrigin: true,
512 path: "/custom/worktree/location",
513 runSetupScript: false,
514 });
515
516 expect(harness.fetchRemote).toHaveBeenCalledWith({
517 cwd: workspaceRoot,
518 remoteName: "origin",
519 });
520 expect(harness.resolveRemoteTrackingCommit).toHaveBeenCalledWith({
521 cwd: workspaceRoot,
522 refName: "dev",
523 fallbackRemoteName: "origin",
524 });
525 expect(harness.createWorktree).toHaveBeenCalledWith({
526 cwd: workspaceRoot,
527 refName: "abc123",
528 newRefName: "feature/from-origin",
529 baseRefName: "dev",
530 path: "/custom/worktree/location",
531 });
532 // localStatus is always consulted now (repo pre-check), but its branch
533 // must not override the explicit baseRef.
534 expect(harness.localStatus).toHaveBeenCalled();
535 expect(harness.runForThread).not.toHaveBeenCalled();
536 expect(result.worktreePath).toBe("/custom/worktree/location");
537 expect(result.startedFromOrigin).toBe(true);
538 expect(result.setupScript).toEqual({ status: "skipped" });
539 });
540 });
541
542 it.effect("uses the server setting for startFromOrigin when unspecified", () => {
543 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
544 return Effect.gen(function* () {
545 const result = yield* runHandoff(harness, { branch: "feature/settings-origin" });
546 expect(result.startedFromOrigin).toBe(true);
547 expect(harness.fetchRemote).toHaveBeenCalled();
548 });
549 });
550
551 it.effect("fails when the thread is already attached to a worktree", () => {
552 const harness = makeHarness({
553 thread: { branch: "feature/existing", worktreePath: "/worktrees/project/existing" },
554 });
555 return Effect.gen(function* () {
556 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/second" }));
557 expectTypedFailure(exit, {
558 _tag: "WorktreeMcpFailure",
559 code: "already_in_worktree",
560 });
561 expect(harness.createWorktree).not.toHaveBeenCalled();
562 });
563 });
564
565 it.effect("fails when the thread does not exist", () => {
566 const harness = makeHarness({ thread: null });
567 return Effect.gen(function* () {
568 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/missing" }));
569 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
570 expect(harness.createWorktree).not.toHaveBeenCalled();
571 });
572 });
573
574 it.effect("treats a soft-deleted thread as not found", () => {
575 const harness = makeHarness({ thread: { deletedAt: "2026-01-02T00:00:00.000Z" } });
576 return Effect.gen(function* () {
577 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/deleted" }));
578 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
579 expect(harness.createWorktree).not.toHaveBeenCalled();
580 });
581 });
582
583 it.effect("maps a non-projection orchestrator error to operation_failed", () => {
584 const harness = makeHarness({ threadReadError: "dispatch" });
585 return Effect.gen(function* () {
586 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/read-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 does not exist", () => {
593 const harness = makeHarness({ projectMissing: true });
594 return Effect.gen(function* () {
595 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-project" }));
596 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
597 expect(harness.createWorktree).not.toHaveBeenCalled();
598 });
599 });
600
601 it.effect("maps a project read error to operation_failed", () => {
602 const harness = makeHarness({ projectReadFails: true });
603 return Effect.gen(function* () {
604 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/project-error" }));
605 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
606 expect(harness.createWorktree).not.toHaveBeenCalled();
607 });
608 });
609
610 it.effect("fails when the project workspace is not a git repository", () => {
611 const harness = makeHarness({ notARepo: true });
612 return Effect.gen(function* () {
613 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-repo" }));
614 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
615 expect(harness.createWorktree).not.toHaveBeenCalled();
616 });
617 });
618
619 it.effect("rejects an existing branch with an actionable error naming its checkout", () => {
620 const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" });
621 return Effect.gen(function* () {
622 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken" }));
623 if (!Exit.isFailure(exit)) {
624 return expect.fail("expected a failure exit");
625 }
626 const reason = exit.cause.reasons[0];
627 expect(reason?._tag).toBe("Fail");
628 const error = (reason as { readonly error: { code: string; message: string } }).error;
629 expect(error.code).toBe("invalid_request");
630 expect(error.message).toContain("feature/taken");
631 expect(error.message).toContain("already exists");
632 expect(error.message).toContain("/elsewhere/checkout");
633 expect(harness.createWorktree).not.toHaveBeenCalled();
634 expect(harness.fetchRemote).not.toHaveBeenCalled();
635 });
636 });
637
638 it.effect("rejects an existing branch that is not checked out anywhere", () => {
639 const harness = makeHarness({ existingBranchWorktreePath: null });
640 return Effect.gen(function* () {
641 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken-idle" }));
642 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
643 expect(harness.createWorktree).not.toHaveBeenCalled();
644 });
645 });
646
647 it.effect("does not trip the pre-flight on similarly named branches", () => {
648 const harness = makeHarness({ existingBranchWorktreePath: null });
649 return Effect.gen(function* () {
650 // "feature/taken" exists in the mock branch list; "feature/take" does
651 // not, and a substring-based check would wrongly match it.
652 const result = yield* runHandoff(harness, { branch: "feature/take" });
653 expect(result.branch).toBe("feature/take");
654 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
655 });
656 });
657
658 it.effect("rejects a non-repository workspace even when baseRef is explicit", () => {
659 const harness = makeHarness({ notARepo: true });
660 return Effect.gen(function* () {
661 const exit = yield* Effect.exit(
662 runHandoff(harness, { branch: "feature/no-repo-baseref", baseRef: "dev" }),
663 );
664 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
665 expect(harness.createWorktree).not.toHaveBeenCalled();
666 });
667 });
668
669 it.effect("propagates an interrupted dispatch without rolling back the worktree", () => {
670 const harness = makeHarness({ dispatchInterrupts: true });
671 return Effect.gen(function* () {
672 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-int" }));
673 if (!Exit.isFailure(exit)) {
674 return expect.fail("expected a failure exit");
675 }
676 // Whether the binding committed is unknown on interruption, so the
677 // worktree must not be force-deleted and no typed failure is invented.
678 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
679 expect(harness.removeWorktree).not.toHaveBeenCalled();
680 });
681 });
682
683 it.effect("maps a worktree creation failure to operation_failed", () => {
684 const harness = makeHarness({ createWorktreeFails: true });
685 return Effect.gen(function* () {
686 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/create-fails" }));
687 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
688 expect(harness.dispatch).not.toHaveBeenCalled();
689 expect(harness.removeWorktree).not.toHaveBeenCalled();
690 });
691 });
692
693 it.effect("maps an origin fetch failure to operation_failed", () => {
694 const harness = makeHarness({ fetchRemoteFails: true });
695 return Effect.gen(function* () {
696 const exit = yield* Effect.exit(
697 runHandoff(harness, { branch: "feature/fetch-fails", startFromOrigin: true }),
698 );
699 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
700 expect(harness.createWorktree).not.toHaveBeenCalled();
701 });
702 });
703
704 it.effect("maps a remote-tracking resolve failure to operation_failed", () => {
705 const harness = makeHarness({ resolveRemoteFails: true });
706 return Effect.gen(function* () {
707 const exit = yield* Effect.exit(
708 runHandoff(harness, { branch: "feature/resolve-fails", startFromOrigin: true }),
709 );
710 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
711 expect(harness.createWorktree).not.toHaveBeenCalled();
712 });
713 });
714
715 it.effect("removes the created worktree when the thread update dies with a defect", () => {
716 const harness = makeHarness({ dispatchDies: true });
717 return Effect.gen(function* () {
718 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-defect" }));
719 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
720 expect(harness.removeWorktree).toHaveBeenCalledWith({
721 cwd: workspaceRoot,
722 path: "/worktrees/project/feature/dispatch-defect",
723 force: true,
724 });
725 });
726 });
727
728 it.effect("re-checks attachment after creating the worktree and backs out on a race", () => {
729 const harness = makeHarness({ threadAttachedOnRecheck: true });
730 return Effect.gen(function* () {
731 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/raced" }));
732 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
733 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
734 // The freshly created worktree must not be left orphaned.
735 expect(harness.removeWorktree).toHaveBeenCalledWith({
736 cwd: workspaceRoot,
737 path: "/worktrees/project/feature/raced",
738 force: true,
739 });
740 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
741 cwd: workspaceRoot,
742 refName: "feature/raced",
743 force: true,
744 });
745 expect(harness.dispatch).not.toHaveBeenCalled();
746 });
747 });
748
749 it.effect("removes the created worktree when the recheck read fails", () => {
750 const harness = makeHarness({ threadReadFailsOnRecheck: true });
751 return Effect.gen(function* () {
752 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/recheck-fails" }));
753 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
754 expect(harness.removeWorktree).toHaveBeenCalledWith({
755 cwd: workspaceRoot,
756 path: "/worktrees/project/feature/recheck-fails",
757 force: true,
758 });
759 expect(harness.dispatch).not.toHaveBeenCalled();
760 });
761 });
762
763 it.effect("backs out when the thread is archived during worktree creation", () => {
764 const harness = makeHarness({ threadArchivedOnRecheck: true });
765 return Effect.gen(function* () {
766 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived-race" }));
767 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
768 expect(harness.dispatch).not.toHaveBeenCalled();
769 // The created worktree must not be left orphaned.
770 expect(harness.removeWorktree).toHaveBeenCalledWith({
771 cwd: workspaceRoot,
772 path: "/worktrees/project/feature/archived-race",
773 force: true,
774 });
775 });
776 });
777
778 it.effect("rejects a handoff for an archived thread", () => {
779 const harness = makeHarness({ thread: { archivedAt: "2026-01-02T00:00:00.000Z" } });
780 return Effect.gen(function* () {
781 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived" }));
782 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
783 expect(harness.createWorktree).not.toHaveBeenCalled();
784 });
785 });
786
787 it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
788 Effect.gen(function* () {
789 const gate = yield* Deferred.make<void>();
790 const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
791
792 // Interrupt arrives while the metadata dispatch is in flight; the
793 // binding-plus-continuation section must run to completion anyway so the
794 // continuation is never lost between the commit and the queue.
795 const fiber = yield* Effect.forkChild(
796 runHandoff(harness, {
797 branch: "feature/interrupted",
798 continuationPrompt: "Keep going in the worktree.",
799 }),
800 );
801 yield* Effect.yieldNow;
802 const interruption = yield* Effect.forkChild(Fiber.interrupt(fiber));
803 yield* Effect.yieldNow;
804 yield* Deferred.succeed(gate, undefined);
805 yield* Fiber.await(fiber);
806 yield* Fiber.join(interruption);
807
808 expect(harness.dispatch).toHaveBeenCalledTimes(1);
809 expect(harness.sendToThread).toHaveBeenCalledTimes(1);
810 // The setup script must also survive the pending interrupt; otherwise
811 // the continuation run starts in a worktree that was never set up.
812 expect(harness.runForThread).toHaveBeenCalledTimes(1);
813 }),
814 );
815
816 it.effect("still fails with a typed error when the rollback removal also fails", () => {
817 const harness = makeHarness({ dispatchFails: true, removeWorktreeFails: true });
818 return Effect.gen(function* () {
819 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/rollback-fails" }));
820 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
821 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
822 expect(harness.deleteLocalBranch).not.toHaveBeenCalled();
823 });
824 });
825
826 it.effect("preserves the typed failure when rollback branch deletion also fails", () => {
827 const harness = makeHarness({ dispatchFails: true, deleteLocalBranchFails: true });
828 return Effect.gen(function* () {
829 const exit = yield* Effect.exit(
830 runHandoff(harness, { branch: "feature/rollback-branch-fails" }),
831 );
832 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
833 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
834 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
835 cwd: workspaceRoot,
836 refName: "feature/rollback-branch-fails",
837 force: true,
838 });
839 });
840 });
841
842 it.effect("accepts a Windows drive path under win32 path semantics", () => {
843 const harness = makeHarness({ pathSemantics: "win32" });
844 return Effect.gen(function* () {
845 const result = yield* runHandoff(harness, {
846 branch: "feature/windows-path",
847 path: "C:\\worktrees\\custom",
848 });
849 expect(result.worktreePath).toBe("C:\\worktrees\\custom");
850 expect(harness.createWorktree).toHaveBeenCalledWith(
851 expect.objectContaining({ path: "C:\\worktrees\\custom" }),
852 );
853 });
854 });
855
856 it.effect("rejects a Windows drive path under posix path semantics", () => {
857 const harness = makeHarness({ pathSemantics: "posix" });
858 return Effect.gen(function* () {
859 // The schema-level pattern admits drive paths cross-platform; the
860 // runtime check reflects the host the worktree would be created on.
861 const exit = yield* Effect.exit(
862 runHandoff(harness, { branch: "feature/windows-path", path: "C:\\worktrees\\custom" }),
863 );
864 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
865 expect(harness.createWorktree).not.toHaveBeenCalled();
866 });
867 });
868
869 it.effect("releases the per-thread guard after a failed handoff", () => {
870 const harness = makeHarness({
871 thread: { worktreePath: "/worktrees/project/existing" },
872 });
873 return Effect.gen(function* () {
874 const service = yield* resolveService(harness);
875
876 const first = yield* Effect.exit(
877 service.handoff(harness.scope, { branch: "feature/guard-1" }),
878 );
879 expectTypedFailure(first, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
880 // A leaked guard would surface as handoff_in_progress here.
881 const second = yield* Effect.exit(
882 service.handoff(harness.scope, { branch: "feature/guard-2" }),
883 );
884 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
885 });
886 });
887
888 it.effect("fails when the worktree capability is missing", () => {
889 const harness = makeHarness({ capabilities: new Set(["preview"]) });
890 return Effect.gen(function* () {
891 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-capability" }));
892 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
893 });
894 });
895
896 it.effect("serializes concurrent handoffs for the same thread", () =>
897 Effect.gen(function* () {
898 const gate = yield* Deferred.make<void>();
899 const harness = makeHarness({ createWorktreeGate: Deferred.await(gate) });
900
901 const service = yield* resolveService(harness);
902
903 // First handoff acquires the per-thread guard and blocks on the gate.
904 const first = yield* Effect.forkChild(
905 Effect.exit(service.handoff(harness.scope, { branch: "feature/race-1" })),
906 );
907 yield* Effect.yieldNow;
908
909 // Second handoff for the same thread must be refused while the first
910 // is still in flight.
911 const second = yield* Effect.exit(
912 service.handoff(harness.scope, { branch: "feature/race-2" }),
913 );
914 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "handoff_in_progress" });
915
916 yield* Deferred.succeed(gate, undefined);
917 const firstExit = yield* Fiber.join(first);
918 expect(Exit.isSuccess(firstExit)).toBe(true);
919 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
920 }),
921 );
922
923 it.effect("removes the created worktree when the thread update fails", () => {
924 const harness = makeHarness({ dispatchFails: true });
925 return Effect.gen(function* () {
926 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-fails" }));
927 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
928 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
929 expect(harness.removeWorktree).toHaveBeenCalledWith({
930 cwd: workspaceRoot,
931 path: "/worktrees/project/feature/dispatch-fails",
932 force: true,
933 });
934 });
935 });
936
937 it.effect("rejects a relative path", () => {
938 const harness = makeHarness();
939 return Effect.gen(function* () {
940 const exit = yield* Effect.exit(
941 runHandoff(harness, { branch: "feature/relative-path", path: "worktrees/nested" }),
942 );
943 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
944 expect(harness.createWorktree).not.toHaveBeenCalled();
945 });
946 });
947
948 it.effect("fails when baseRef is omitted and HEAD is detached", () => {
949 const harness = makeHarness({ currentBranch: null });
950 return Effect.gen(function* () {
951 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/detached" }));
952 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
953 });
954 });
955
956 it.effect("reports setup script failure without failing the handoff", () => {
957 const harness = makeHarness({ setupScript: "fails" });
958 return Effect.gen(function* () {
959 const result = yield* runHandoff(harness, { branch: "feature/setup-fails" });
960 expect(result.setupScript.status).toBe("failed");
961 expect(harness.dispatch).toHaveBeenCalled();
962 });
963 });
964
965 it.effect("reports a setup script defect without failing the handoff", () => {
966 const harness = makeHarness({ setupScript: "dies" });
967 return Effect.gen(function* () {
968 const result = yield* runHandoff(harness, { branch: "feature/setup-dies" });
969 expect(result.setupScript).toEqual({ status: "failed", detail: "setup runner defect" });
970 expect(harness.dispatch).toHaveBeenCalled();
971 });
972 });
973});
974
975describe("t3_worktree_status", () => {
976 it.effect("reports an unattached thread", () => {
977 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
978 return Effect.gen(function* () {
979 const result = yield* runStatus(harness);
980 expect(result).toEqual({
981 attached: false,
982 worktreePath: null,
983 branch: null,
984 projectWorkspaceRoot: workspaceRoot,
985 defaultStartFromOrigin: true,
986 });
987 });
988 });
989
990 it.effect("reports an attached thread's worktree and branch", () => {
991 const harness = makeHarness({
992 thread: {
993 worktreePath: "/worktrees/project/existing",
994 branch: "feature/existing",
995 },
996 });
997 return Effect.gen(function* () {
998 const result = yield* runStatus(harness);
999 expect(result).toMatchObject({
1000 attached: true,
1001 worktreePath: "/worktrees/project/existing",
1002 branch: "feature/existing",
1003 defaultStartFromOrigin: false,
1004 });
1005 });
1006 });
1007
1008 it.effect("fails when the worktree capability is missing", () => {
1009 const harness = makeHarness({ capabilities: new Set(["preview"]) });
1010 return Effect.gen(function* () {
1011 const exit = yield* Effect.exit(runStatus(harness));
1012 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
1013 });
1014 });
1015
1016 it.effect("fails when the thread does not exist", () => {
1017 const harness = makeHarness({ thread: null });
1018 return Effect.gen(function* () {
1019 const exit = yield* Effect.exit(runStatus(harness));
1020 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
1021 });
1022 });
1023
1024 it.effect("fails when the project does not exist", () => {
1025 const harness = makeHarness({ projectMissing: true });
1026 return Effect.gen(function* () {
1027 const exit = yield* Effect.exit(runStatus(harness));
1028 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
1029 });
1030 });
1031});
1032
1033describe("WorktreeMcpHandoffInput schema", () => {
1034 const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
1035
1036 it.effect("accepts POSIX, Windows drive, and UNC absolute paths", () =>
1037 Effect.gen(function* () {
1038 for (const path of ["/abs/posix", "C:\\abs\\drive", "C:/abs/drive", "\\\\host\\share"]) {
1039 const decoded = yield* decode({ branch: "feature/x", path });
1040 expect(decoded.path).toBe(path);
1041 }
1042 }),
1043 );
1044
1045 it.effect("rejects relative paths", () =>
1046 Effect.gen(function* () {
1047 for (const path of ["worktrees/nested", "./nested", "../sibling"]) {
1048 const exit = yield* Effect.exit(decode({ branch: "feature/x", path }));
1049 expect(Exit.isFailure(exit), `path '${path}' should be rejected`).toBe(true);
1050 }
1051 }),
1052 );
1053
1054 it.effect("rejects a missing or blank branch", () =>
1055 Effect.gen(function* () {
1056 expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true);
1057 expect(Exit.isFailure(yield* Effect.exit(decode({ branch: " " })))).toBe(true);
1058 }),
1059 );
1060
1061 it.effect("rejects a blank continuationPrompt", () =>
1062 Effect.gen(function* () {
1063 const exit = yield* Effect.exit(decode({ branch: "feature/x", continuationPrompt: " " }));
1064 expect(Exit.isFailure(exit)).toBe(true);
1065 }),
1066 );
1067});