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 scriptId: "setup",
279 scriptName: "Setup",
280 terminalId: "setup-terminal",
281 cwd: input.worktreePath,
282 } as const);
283 }
284 });
285
286 // Optional deterministic Path semantics: providing this BEFORE the general
287 // mocks means the service resolves Path here rather than from NodeServices,
288 // so absolute-path validation is testable independently of the host OS. The
289 // service only calls isAbsolute; the minimal per-platform semantics are
290 // inlined so the test does not depend on the host's path module.
291 const win32IsAbsolute = (value: string) => /^(?:[a-zA-Z]:[\\/]|[\\/])/.test(value);
292 const posixIsAbsolute = (value: string) => value.startsWith("/");
293 const serviceLayer =
294 options.pathSemantics === undefined
295 ? worktreeMcpServiceLayer
296 : worktreeMcpServiceLayer.pipe(
297 Layer.provide(
298 Layer.succeed(Path.Path, {
299 isAbsolute: options.pathSemantics === "win32" ? win32IsAbsolute : posixIsAbsolute,
300 } as unknown as Path.Path),
301 ),
302 );
303 const layer = serviceLayer.pipe(
304 Layer.provide(
305 Layer.mergeAll(
306 Layer.mock(ThreadManagementService)({
307 dispatch,
308 getThreadProjection,
309 sendToThread,
310 } satisfies Partial<ThreadManagementService["Service"]>),
311 Layer.mock(ProjectService.ProjectService)({
312 getById,
313 } satisfies Partial<ProjectService.ProjectService["Service"]>),
314 ServerSettings.layerTest({
315 newWorktreesStartFromOrigin: options.newWorktreesStartFromOrigin ?? false,
316 }),
317 Layer.mock(GitWorkflowService.GitWorkflowService)({
318 listRefs,
319 listLocalBranchNames,
320 localStatus,
321 fetchRemote,
322 resolveRemoteTrackingCommit,
323 createWorktree,
324 removeWorktree,
325 deleteLocalBranch,
326 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
327 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
328 runForThread,
329 } satisfies Partial<ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]>),
330 Layer.mock(VcsStatusBroadcaster)({
331 refreshStatus,
332 } satisfies Partial<VcsStatusBroadcaster["Service"]>),
333 NodeServices.layer,
334 ),
335 ),
336 );
337
338 return {
339 layer,
340 scope,
341 dispatch,
342 sendToThread,
343 fetchRemote,
344 resolveRemoteTrackingCommit,
345 createWorktree,
346 removeWorktree,
347 deleteLocalBranch,
348 localStatus,
349 runForThread,
350 };
351};
352
353const expectTypedFailure = (exit: Exit.Exit<unknown, unknown>, expected: object): void => {
354 if (!Exit.isFailure(exit)) {
355 expect.fail(`Expected a failure exit, got: ${JSON.stringify(exit)}`);
356 }
357 const reason = exit.cause.reasons[0];
358 if (reason?._tag !== "Fail") {
359 expect.fail(`Expected a typed Fail cause, got: ${reason?._tag ?? "no reason"}`);
360 }
361 expect(reason.error).toMatchObject(expected);
362};
363
364// Resolves the service once from the harness layer; used by tests that must
365// make several calls against the SAME instance (the in-flight guard lives in
366// the layer's closure, so a fresh layer per call would never see it).
367const resolveService = (harness: ReturnType<typeof makeHarness>) =>
368 Effect.gen(function* () {
369 return yield* WorktreeMcpService;
370 }).pipe(Effect.provide(harness.layer));
371
372const runHandoff = (
373 harness: ReturnType<typeof makeHarness>,
374 input: Parameters<WorktreeMcpService["Service"]["handoff"]>[1],
375) =>
376 Effect.gen(function* () {
377 const service = yield* WorktreeMcpService;
378 return yield* service.handoff(harness.scope, input);
379 }).pipe(Effect.provide(harness.layer));
380
381const runStatus = (harness: ReturnType<typeof makeHarness>) =>
382 Effect.gen(function* () {
383 const service = yield* WorktreeMcpService;
384 return yield* service.status(harness.scope);
385 }).pipe(Effect.provide(harness.layer));
386
387describe("t3_worktree_handoff", () => {
388 it.effect("creates a worktree from the current branch and re-points the thread", () => {
389 const harness = makeHarness();
390 return Effect.gen(function* () {
391 const result = yield* runHandoff(harness, { branch: "feature/handoff" });
392
393 expect(result.branch).toBe("feature/handoff");
394 expect(result.baseRef).toBe("dev");
395 expect(result.startedFromOrigin).toBe(false);
396 expect(result.worktreePath).toBe("/worktrees/project/feature/handoff");
397 expect(result.setupScript).toMatchObject({ status: "started", scriptName: "Setup" });
398
399 expect(harness.fetchRemote).not.toHaveBeenCalled();
400 expect(harness.createWorktree).toHaveBeenCalledWith({
401 cwd: workspaceRoot,
402 refName: "dev",
403 newRefName: "feature/handoff",
404 baseRefName: "dev",
405 path: null,
406 });
407 expect(harness.dispatch).toHaveBeenCalledWith(
408 expect.objectContaining({
409 type: "thread.metadata.update",
410 threadId,
411 branch: "feature/handoff",
412 worktreePath: "/worktrees/project/feature/handoff",
413 expectedWorktreePath: null,
414 }),
415 );
416 expect(harness.runForThread).toHaveBeenCalledWith({
417 threadId,
418 projectId,
419 projectCwd: workspaceRoot,
420 worktreePath: "/worktrees/project/feature/handoff",
421 project: { id: projectId, workspaceRoot, scripts: [] },
422 });
423 });
424 });
425
426 it.effect("skips the continuation when no continuationPrompt is given", () => {
427 const harness = makeHarness();
428 return Effect.gen(function* () {
429 const result = yield* runHandoff(harness, { branch: "feature/no-continuation" });
430 expect(result.continuation).toEqual({ status: "skipped" });
431 expect(harness.sendToThread).not.toHaveBeenCalled();
432 });
433 });
434
435 it.effect("queues the continuation prompt as the thread's next message", () => {
436 const harness = makeHarness();
437 return Effect.gen(function* () {
438 const result = yield* runHandoff(harness, {
439 branch: "feature/continue",
440 continuationPrompt: "Keep fixing the login bug in the new worktree.",
441 });
442
443 expect(result.continuation).toEqual({ status: "scheduled", delivery: "queued" });
444 expect(harness.sendToThread).toHaveBeenCalledWith(
445 expect.objectContaining({
446 projectId,
447 threadId,
448 text: "Keep fixing the login bug in the new worktree.",
449 mode: "queue",
450 createdBy: "agent",
451 creationSource: "mcp",
452 }),
453 );
454 // The continuation must be durably queued before anything slower runs.
455 expect(harness.sendToThread.mock.invocationCallOrder[0]).toBeLessThan(
456 harness.runForThread.mock.invocationCallOrder[0]!,
457 );
458 });
459 });
460
461 it.effect("reports a continuation failure without failing the handoff", () => {
462 const harness = makeHarness({ continuation: "fails" });
463 return Effect.gen(function* () {
464 const result = yield* runHandoff(harness, {
465 branch: "feature/continue-fails",
466 continuationPrompt: "Keep going.",
467 });
468 expect(result.continuation).toMatchObject({ status: "failed" });
469 expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails");
470 expect(harness.dispatch).toHaveBeenCalled();
471 });
472 });
473
474 it.effect("reports a continuation defect without failing the handoff", () => {
475 const harness = makeHarness({ continuation: "dies" });
476 return Effect.gen(function* () {
477 const result = yield* runHandoff(harness, {
478 branch: "feature/continue-dies",
479 continuationPrompt: "Keep going.",
480 });
481 expect(result.continuation).toEqual({ status: "failed", detail: "send defect" });
482 expect(result.setupScript).toMatchObject({ status: "started" });
483 });
484 });
485
486 it.effect("does not queue a continuation when the thread update fails", () => {
487 const harness = makeHarness({ dispatchFails: true });
488 return Effect.gen(function* () {
489 const exit = yield* Effect.exit(
490 runHandoff(harness, {
491 branch: "feature/dispatch-fails-continue",
492 continuationPrompt: "Keep going.",
493 }),
494 );
495 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
496 expect(harness.sendToThread).not.toHaveBeenCalled();
497 });
498 });
499
500 it.effect("starts from origin and honors explicit baseRef and path", () => {
501 const harness = makeHarness();
502 return Effect.gen(function* () {
503 const result = yield* runHandoff(harness, {
504 branch: "feature/from-origin",
505 baseRef: "dev",
506 startFromOrigin: true,
507 path: "/custom/worktree/location",
508 runSetupScript: false,
509 });
510
511 expect(harness.fetchRemote).toHaveBeenCalledWith({
512 cwd: workspaceRoot,
513 remoteName: "origin",
514 });
515 expect(harness.resolveRemoteTrackingCommit).toHaveBeenCalledWith({
516 cwd: workspaceRoot,
517 refName: "dev",
518 fallbackRemoteName: "origin",
519 });
520 expect(harness.createWorktree).toHaveBeenCalledWith({
521 cwd: workspaceRoot,
522 refName: "abc123",
523 newRefName: "feature/from-origin",
524 baseRefName: "dev",
525 path: "/custom/worktree/location",
526 });
527 // localStatus is always consulted now (repo pre-check), but its branch
528 // must not override the explicit baseRef.
529 expect(harness.localStatus).toHaveBeenCalled();
530 expect(harness.runForThread).not.toHaveBeenCalled();
531 expect(result.worktreePath).toBe("/custom/worktree/location");
532 expect(result.startedFromOrigin).toBe(true);
533 expect(result.setupScript).toEqual({ status: "skipped" });
534 });
535 });
536
537 it.effect("uses the server setting for startFromOrigin when unspecified", () => {
538 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
539 return Effect.gen(function* () {
540 const result = yield* runHandoff(harness, { branch: "feature/settings-origin" });
541 expect(result.startedFromOrigin).toBe(true);
542 expect(harness.fetchRemote).toHaveBeenCalled();
543 });
544 });
545
546 it.effect("fails when the thread is already attached to a worktree", () => {
547 const harness = makeHarness({
548 thread: { branch: "feature/existing", worktreePath: "/worktrees/project/existing" },
549 });
550 return Effect.gen(function* () {
551 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/second" }));
552 expectTypedFailure(exit, {
553 _tag: "WorktreeMcpFailure",
554 code: "already_in_worktree",
555 });
556 expect(harness.createWorktree).not.toHaveBeenCalled();
557 });
558 });
559
560 it.effect("fails when the thread does not exist", () => {
561 const harness = makeHarness({ thread: null });
562 return Effect.gen(function* () {
563 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/missing" }));
564 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
565 expect(harness.createWorktree).not.toHaveBeenCalled();
566 });
567 });
568
569 it.effect("treats a soft-deleted thread as not found", () => {
570 const harness = makeHarness({ thread: { deletedAt: "2026-01-02T00:00:00.000Z" } });
571 return Effect.gen(function* () {
572 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/deleted" }));
573 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
574 expect(harness.createWorktree).not.toHaveBeenCalled();
575 });
576 });
577
578 it.effect("maps a non-projection orchestrator error to operation_failed", () => {
579 const harness = makeHarness({ threadReadError: "dispatch" });
580 return Effect.gen(function* () {
581 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/read-error" }));
582 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
583 expect(harness.createWorktree).not.toHaveBeenCalled();
584 });
585 });
586
587 it.effect("fails when the project does not exist", () => {
588 const harness = makeHarness({ projectMissing: true });
589 return Effect.gen(function* () {
590 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-project" }));
591 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
592 expect(harness.createWorktree).not.toHaveBeenCalled();
593 });
594 });
595
596 it.effect("maps a project read error to operation_failed", () => {
597 const harness = makeHarness({ projectReadFails: true });
598 return Effect.gen(function* () {
599 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/project-error" }));
600 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
601 expect(harness.createWorktree).not.toHaveBeenCalled();
602 });
603 });
604
605 it.effect("fails when the project workspace is not a git repository", () => {
606 const harness = makeHarness({ notARepo: true });
607 return Effect.gen(function* () {
608 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-repo" }));
609 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
610 expect(harness.createWorktree).not.toHaveBeenCalled();
611 });
612 });
613
614 it.effect("rejects an existing branch with an actionable error naming its checkout", () => {
615 const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" });
616 return Effect.gen(function* () {
617 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken" }));
618 if (!Exit.isFailure(exit)) {
619 return expect.fail("expected a failure exit");
620 }
621 const reason = exit.cause.reasons[0];
622 expect(reason?._tag).toBe("Fail");
623 const error = (reason as { readonly error: { code: string; message: string } }).error;
624 expect(error.code).toBe("invalid_request");
625 expect(error.message).toContain("feature/taken");
626 expect(error.message).toContain("already exists");
627 expect(error.message).toContain("/elsewhere/checkout");
628 expect(harness.createWorktree).not.toHaveBeenCalled();
629 expect(harness.fetchRemote).not.toHaveBeenCalled();
630 });
631 });
632
633 it.effect("rejects an existing branch that is not checked out anywhere", () => {
634 const harness = makeHarness({ existingBranchWorktreePath: null });
635 return Effect.gen(function* () {
636 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken-idle" }));
637 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
638 expect(harness.createWorktree).not.toHaveBeenCalled();
639 });
640 });
641
642 it.effect("does not trip the pre-flight on similarly named branches", () => {
643 const harness = makeHarness({ existingBranchWorktreePath: null });
644 return Effect.gen(function* () {
645 // "feature/taken" exists in the mock branch list; "feature/take" does
646 // not, and a substring-based check would wrongly match it.
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 // Whether the binding committed is unknown on interruption, so the
672 // worktree must not be force-deleted and no typed failure is invented.
673 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
674 expect(harness.removeWorktree).not.toHaveBeenCalled();
675 });
676 });
677
678 it.effect("maps a worktree creation failure to operation_failed", () => {
679 const harness = makeHarness({ createWorktreeFails: true });
680 return Effect.gen(function* () {
681 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/create-fails" }));
682 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
683 expect(harness.dispatch).not.toHaveBeenCalled();
684 expect(harness.removeWorktree).not.toHaveBeenCalled();
685 });
686 });
687
688 it.effect("maps an origin fetch failure to operation_failed", () => {
689 const harness = makeHarness({ fetchRemoteFails: true });
690 return Effect.gen(function* () {
691 const exit = yield* Effect.exit(
692 runHandoff(harness, { branch: "feature/fetch-fails", startFromOrigin: true }),
693 );
694 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
695 expect(harness.createWorktree).not.toHaveBeenCalled();
696 });
697 });
698
699 it.effect("maps a remote-tracking resolve failure to operation_failed", () => {
700 const harness = makeHarness({ resolveRemoteFails: true });
701 return Effect.gen(function* () {
702 const exit = yield* Effect.exit(
703 runHandoff(harness, { branch: "feature/resolve-fails", startFromOrigin: true }),
704 );
705 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
706 expect(harness.createWorktree).not.toHaveBeenCalled();
707 });
708 });
709
710 it.effect("removes the created worktree when the thread update dies with a defect", () => {
711 const harness = makeHarness({ dispatchDies: true });
712 return Effect.gen(function* () {
713 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-defect" }));
714 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
715 expect(harness.removeWorktree).toHaveBeenCalledWith({
716 cwd: workspaceRoot,
717 path: "/worktrees/project/feature/dispatch-defect",
718 force: true,
719 });
720 });
721 });
722
723 it.effect("re-checks attachment after creating the worktree and backs out on a race", () => {
724 const harness = makeHarness({ threadAttachedOnRecheck: true });
725 return Effect.gen(function* () {
726 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/raced" }));
727 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
728 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
729 // The freshly created worktree must not be left orphaned.
730 expect(harness.removeWorktree).toHaveBeenCalledWith({
731 cwd: workspaceRoot,
732 path: "/worktrees/project/feature/raced",
733 force: true,
734 });
735 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
736 cwd: workspaceRoot,
737 refName: "feature/raced",
738 force: true,
739 });
740 expect(harness.dispatch).not.toHaveBeenCalled();
741 });
742 });
743
744 it.effect("removes the created worktree when the recheck read fails", () => {
745 const harness = makeHarness({ threadReadFailsOnRecheck: true });
746 return Effect.gen(function* () {
747 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/recheck-fails" }));
748 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
749 expect(harness.removeWorktree).toHaveBeenCalledWith({
750 cwd: workspaceRoot,
751 path: "/worktrees/project/feature/recheck-fails",
752 force: true,
753 });
754 expect(harness.dispatch).not.toHaveBeenCalled();
755 });
756 });
757
758 it.effect("backs out when the thread is archived during worktree creation", () => {
759 const harness = makeHarness({ threadArchivedOnRecheck: true });
760 return Effect.gen(function* () {
761 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived-race" }));
762 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
763 expect(harness.dispatch).not.toHaveBeenCalled();
764 // The created worktree must not be left orphaned.
765 expect(harness.removeWorktree).toHaveBeenCalledWith({
766 cwd: workspaceRoot,
767 path: "/worktrees/project/feature/archived-race",
768 force: true,
769 });
770 });
771 });
772
773 it.effect("rejects a handoff for an archived thread", () => {
774 const harness = makeHarness({ thread: { archivedAt: "2026-01-02T00:00:00.000Z" } });
775 return Effect.gen(function* () {
776 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived" }));
777 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
778 expect(harness.createWorktree).not.toHaveBeenCalled();
779 });
780 });
781
782 it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
783 Effect.gen(function* () {
784 const gate = yield* Deferred.make<void>();
785 const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
786
787 // Interrupt arrives while the metadata dispatch is in flight; the
788 // binding-plus-continuation section must run to completion anyway so the
789 // continuation is never lost between the commit and the queue.
790 const fiber = yield* Effect.forkChild(
791 runHandoff(harness, {
792 branch: "feature/interrupted",
793 continuationPrompt: "Keep going in the worktree.",
794 }),
795 );
796 yield* Effect.yieldNow;
797 const interruption = yield* Effect.forkChild(Fiber.interrupt(fiber));
798 yield* Effect.yieldNow;
799 yield* Deferred.succeed(gate, undefined);
800 yield* Fiber.await(fiber);
801 yield* Fiber.join(interruption);
802
803 expect(harness.dispatch).toHaveBeenCalledTimes(1);
804 expect(harness.sendToThread).toHaveBeenCalledTimes(1);
805 // The setup script must also survive the pending interrupt; otherwise
806 // the continuation run starts in a worktree that was never set up.
807 expect(harness.runForThread).toHaveBeenCalledTimes(1);
808 }),
809 );
810
811 it.effect("still fails with a typed error when the rollback removal also fails", () => {
812 const harness = makeHarness({ dispatchFails: true, removeWorktreeFails: true });
813 return Effect.gen(function* () {
814 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/rollback-fails" }));
815 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
816 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
817 expect(harness.deleteLocalBranch).not.toHaveBeenCalled();
818 });
819 });
820
821 it.effect("preserves the typed failure when rollback branch deletion also fails", () => {
822 const harness = makeHarness({ dispatchFails: true, deleteLocalBranchFails: true });
823 return Effect.gen(function* () {
824 const exit = yield* Effect.exit(
825 runHandoff(harness, { branch: "feature/rollback-branch-fails" }),
826 );
827 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
828 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
829 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
830 cwd: workspaceRoot,
831 refName: "feature/rollback-branch-fails",
832 force: true,
833 });
834 });
835 });
836
837 it.effect("accepts a Windows drive path under win32 path semantics", () => {
838 const harness = makeHarness({ pathSemantics: "win32" });
839 return Effect.gen(function* () {
840 const result = yield* runHandoff(harness, {
841 branch: "feature/windows-path",
842 path: "C:\\worktrees\\custom",
843 });
844 expect(result.worktreePath).toBe("C:\\worktrees\\custom");
845 expect(harness.createWorktree).toHaveBeenCalledWith(
846 expect.objectContaining({ path: "C:\\worktrees\\custom" }),
847 );
848 });
849 });
850
851 it.effect("rejects a Windows drive path under posix path semantics", () => {
852 const harness = makeHarness({ pathSemantics: "posix" });
853 return Effect.gen(function* () {
854 // The schema-level pattern admits drive paths cross-platform; the
855 // runtime check reflects the host the worktree would be created on.
856 const exit = yield* Effect.exit(
857 runHandoff(harness, { branch: "feature/windows-path", path: "C:\\worktrees\\custom" }),
858 );
859 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
860 expect(harness.createWorktree).not.toHaveBeenCalled();
861 });
862 });
863
864 it.effect("releases the per-thread guard after a failed handoff", () => {
865 const harness = makeHarness({
866 thread: { worktreePath: "/worktrees/project/existing" },
867 });
868 return Effect.gen(function* () {
869 const service = yield* resolveService(harness);
870
871 const first = yield* Effect.exit(
872 service.handoff(harness.scope, { branch: "feature/guard-1" }),
873 );
874 expectTypedFailure(first, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
875 // A leaked guard would surface as handoff_in_progress here.
876 const second = yield* Effect.exit(
877 service.handoff(harness.scope, { branch: "feature/guard-2" }),
878 );
879 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
880 });
881 });
882
883 it.effect("fails when the worktree capability is missing", () => {
884 const harness = makeHarness({ capabilities: new Set(["preview"]) });
885 return Effect.gen(function* () {
886 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-capability" }));
887 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
888 });
889 });
890
891 it.effect("serializes concurrent handoffs for the same thread", () =>
892 Effect.gen(function* () {
893 const gate = yield* Deferred.make<void>();
894 const harness = makeHarness({ createWorktreeGate: Deferred.await(gate) });
895
896 const service = yield* resolveService(harness);
897
898 // First handoff acquires the per-thread guard and blocks on the gate.
899 const first = yield* Effect.forkChild(
900 Effect.exit(service.handoff(harness.scope, { branch: "feature/race-1" })),
901 );
902 yield* Effect.yieldNow;
903
904 // Second handoff for the same thread must be refused while the first
905 // is still in flight.
906 const second = yield* Effect.exit(
907 service.handoff(harness.scope, { branch: "feature/race-2" }),
908 );
909 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "handoff_in_progress" });
910
911 yield* Deferred.succeed(gate, undefined);
912 const firstExit = yield* Fiber.join(first);
913 expect(Exit.isSuccess(firstExit)).toBe(true);
914 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
915 }),
916 );
917
918 it.effect("removes the created worktree when the thread update fails", () => {
919 const harness = makeHarness({ dispatchFails: true });
920 return Effect.gen(function* () {
921 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-fails" }));
922 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
923 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
924 expect(harness.removeWorktree).toHaveBeenCalledWith({
925 cwd: workspaceRoot,
926 path: "/worktrees/project/feature/dispatch-fails",
927 force: true,
928 });
929 });
930 });
931
932 it.effect("rejects a relative path", () => {
933 const harness = makeHarness();
934 return Effect.gen(function* () {
935 const exit = yield* Effect.exit(
936 runHandoff(harness, { branch: "feature/relative-path", path: "worktrees/nested" }),
937 );
938 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
939 expect(harness.createWorktree).not.toHaveBeenCalled();
940 });
941 });
942
943 it.effect("fails when baseRef is omitted and HEAD is detached", () => {
944 const harness = makeHarness({ currentBranch: null });
945 return Effect.gen(function* () {
946 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/detached" }));
947 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
948 });
949 });
950
951 it.effect("reports setup script failure without failing the handoff", () => {
952 const harness = makeHarness({ setupScript: "fails" });
953 return Effect.gen(function* () {
954 const result = yield* runHandoff(harness, { branch: "feature/setup-fails" });
955 expect(result.setupScript.status).toBe("failed");
956 expect(harness.dispatch).toHaveBeenCalled();
957 });
958 });
959
960 it.effect("reports a setup script defect without failing the handoff", () => {
961 const harness = makeHarness({ setupScript: "dies" });
962 return Effect.gen(function* () {
963 const result = yield* runHandoff(harness, { branch: "feature/setup-dies" });
964 expect(result.setupScript).toEqual({ status: "failed", detail: "setup runner defect" });
965 expect(harness.dispatch).toHaveBeenCalled();
966 });
967 });
968});
969
970describe("t3_worktree_status", () => {
971 it.effect("reports an unattached thread", () => {
972 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
973 return Effect.gen(function* () {
974 const result = yield* runStatus(harness);
975 expect(result).toEqual({
976 attached: false,
977 worktreePath: null,
978 branch: null,
979 projectWorkspaceRoot: workspaceRoot,
980 defaultStartFromOrigin: true,
981 });
982 });
983 });
984
985 it.effect("reports an attached thread's worktree and branch", () => {
986 const harness = makeHarness({
987 thread: {
988 worktreePath: "/worktrees/project/existing",
989 branch: "feature/existing",
990 },
991 });
992 return Effect.gen(function* () {
993 const result = yield* runStatus(harness);
994 expect(result).toMatchObject({
995 attached: true,
996 worktreePath: "/worktrees/project/existing",
997 branch: "feature/existing",
998 defaultStartFromOrigin: false,
999 });
1000 });
1001 });
1002
1003 it.effect("fails when the worktree capability is missing", () => {
1004 const harness = makeHarness({ capabilities: new Set(["preview"]) });
1005 return Effect.gen(function* () {
1006 const exit = yield* Effect.exit(runStatus(harness));
1007 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
1008 });
1009 });
1010
1011 it.effect("fails when the thread does not exist", () => {
1012 const harness = makeHarness({ thread: null });
1013 return Effect.gen(function* () {
1014 const exit = yield* Effect.exit(runStatus(harness));
1015 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
1016 });
1017 });
1018
1019 it.effect("fails when the project does not exist", () => {
1020 const harness = makeHarness({ projectMissing: true });
1021 return Effect.gen(function* () {
1022 const exit = yield* Effect.exit(runStatus(harness));
1023 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
1024 });
1025 });
1026});
1027
1028describe("WorktreeMcpHandoffInput schema", () => {
1029 const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
1030
1031 it.effect("accepts POSIX, Windows drive, and UNC absolute paths", () =>
1032 Effect.gen(function* () {
1033 for (const path of ["/abs/posix", "C:\\abs\\drive", "C:/abs/drive", "\\\\host\\share"]) {
1034 const decoded = yield* decode({ branch: "feature/x", path });
1035 expect(decoded.path).toBe(path);
1036 }
1037 }),
1038 );
1039
1040 it.effect("rejects relative paths", () =>
1041 Effect.gen(function* () {
1042 for (const path of ["worktrees/nested", "./nested", "../sibling"]) {
1043 const exit = yield* Effect.exit(decode({ branch: "feature/x", path }));
1044 expect(Exit.isFailure(exit), `path '${path}' should be rejected`).toBe(true);
1045 }
1046 }),
1047 );
1048
1049 it.effect("rejects a missing or blank branch", () =>
1050 Effect.gen(function* () {
1051 expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true);
1052 expect(Exit.isFailure(yield* Effect.exit(decode({ branch: " " })))).toBe(true);
1053 }),
1054 );
1055
1056 it.effect("rejects a blank continuationPrompt", () =>
1057 Effect.gen(function* () {
1058 const exit = yield* Effect.exit(decode({ branch: "feature/x", continuationPrompt: " " }));
1059 expect(Exit.isFailure(exit)).toBe(true);
1060 }),
1061 );
1062});