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 FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Schema from "effect/Schema";
22
23import * as GitWorkflowService from "../git/GitWorkflowService.ts";
24import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
25import * as ServerConfig from "../config.ts";
26import {
27 OrchestratorDispatchError,
28 OrchestratorProjectionError,
29} from "../orchestration-v2/Orchestrator.ts";
30import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
31import * as ProjectService from "../project/ProjectService.ts";
32import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
35import type * as McpInvocationContext from "./McpInvocationContext.ts";
36import * as WorktreeMcpService from "./WorktreeMcpService.ts";
37
38const environmentId = EnvironmentId.make("environment-worktree-test");
39const threadId = ThreadId.make("thread-worktree-test");
40const projectId = ProjectId.make("project-worktree-test");
41const workspaceRoot = "/repo/project";
42
43const makeScope = (
44 capabilities: ReadonlySet<McpInvocationContext.McpCapability>,
45): McpInvocationContext.McpInvocationScope => ({
46 environmentId,
47 requestNamespace: "provider-session-worktree-test",
48 thread: {
49 threadId,
50 providerSessionId: "provider-session-worktree-test",
51 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
52 },
53 client: undefined,
54 capabilities,
55 issuedAt: 1,
56});
57
58interface ThreadFixture {
59 readonly branch?: string | null;
60 readonly worktreePath?: string | null;
61 readonly archivedAt?: string | null;
62 readonly deletedAt?: string | null;
63}
64
65const makeProjection = (overrides: ThreadFixture = {}): OrchestrationV2ThreadProjection =>
66 ({
67 thread: {
68 id: threadId,
69 projectId,
70 title: "Worktree test thread",
71 branch: null,
72 worktreePath: null,
73 archivedAt: null,
74 deletedAt: null,
75 ...overrides,
76 },
77 }) as OrchestrationV2ThreadProjection;
78
79const project: Project = {
80 id: projectId,
81 title: "Worktree test project",
82 workspaceRoot,
83 defaultModelSelection: null,
84 scripts: [],
85 createdAt: "2026-01-01T00:00:00.000Z",
86 updatedAt: "2026-01-01T00:00:00.000Z",
87 deletedAt: null,
88} as Project;
89
90interface HarnessOptions {
91 readonly git?: Partial<GitWorkflowService.GitWorkflowService["Service"]>;
92 readonly thread?: ThreadFixture | null;
93 readonly threadReadError?: "projection" | "dispatch";
94 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
95 readonly currentBranch?: string | null;
96 readonly notARepo?: boolean;
97 readonly newWorktreesStartFromOrigin?: boolean;
98 readonly setupScript?: "started" | "no-script" | "fails" | "dies";
99 readonly dispatchFails?: boolean;
100 readonly dispatchDies?: boolean;
101 readonly dispatchInterrupts?: boolean;
102 readonly dispatchGate?: Effect.Effect<void>;
103 readonly threadAttachedOnRecheck?: boolean;
104 readonly threadArchivedOnRecheck?: boolean;
105 readonly threadReadFailsOnRecheck?: boolean;
106 readonly continuation?: "queued" | "fails" | "dies";
107 readonly projectMissing?: boolean;
108 readonly projectReadFails?: boolean;
109 readonly existingBranchWorktreePath?: string | null;
110 readonly createWorktreeFails?: boolean;
111 readonly fetchWorktreeBaseFails?: boolean;
112 readonly worktreeBaseMissing?: boolean;
113 readonly removeWorktreeFails?: boolean;
114 readonly deleteLocalBranchFails?: boolean;
115 readonly createWorktreeGate?: Effect.Effect<void>;
116}
117
118const makeHarness = (options: HarnessOptions = {}) => {
119 const thread = options.thread === undefined ? {} : options.thread;
120 const scope = makeScope(options.capabilities ?? new Set(["preview", "worktree"]));
121 const dispatch = vi.fn((_: unknown) =>
122 (options.dispatchGate ?? Effect.void).pipe(
123 Effect.andThen(
124 options.dispatchInterrupts
125 ? (Effect.failCause(Cause.interrupt()) as never)
126 : options.dispatchDies
127 ? Effect.die(new Error("dispatch defect"))
128 : options.dispatchFails
129 ? (Effect.fail("simulated dispatch failure") as never)
130 : Effect.succeed({ sequence: 1, storedEvents: [] }),
131 ),
132 ),
133 );
134 const listLocalBranchNames = vi.fn((_: string) =>
135 Effect.succeed(
136 options.existingBranchWorktreePath === undefined
137 ? ["dev"]
138 : ["dev", "feature/taken", "feature/taken-idle"],
139 ),
140 );
141 const getThreadRecords = vi.fn((id: ThreadId) => {
142 if (options.threadReadError === "dispatch") {
143 return Effect.fail(
144 new OrchestratorDispatchError({
145 commandId: CommandId.make("command:test:read"),
146 commandType: "thread.metadata.update",
147 }),
148 ) as never;
149 }
150 if (options.threadReadFailsOnRecheck === true && getThreadRecords.mock.calls.length > 1) {
151 return Effect.fail(
152 new OrchestratorDispatchError({
153 commandId: CommandId.make("command:test:recheck"),
154 commandType: "thread.metadata.update",
155 }),
156 ) as never;
157 }
158 if (
159 options.threadAttachedOnRecheck === true &&
160 getThreadRecords.mock.calls.length > 1 &&
161 thread !== null
162 ) {
163 return Effect.succeed(
164 makeProjection({ ...thread, worktreePath: "/worktrees/project/raced" }),
165 );
166 }
167 if (
168 options.threadArchivedOnRecheck === true &&
169 getThreadRecords.mock.calls.length > 1 &&
170 thread !== null
171 ) {
172 return Effect.succeed(makeProjection({ ...thread, archivedAt: "2026-01-02T00:00:00.000Z" }));
173 }
174 return id === threadId && thread !== null
175 ? Effect.succeed(makeProjection(thread))
176 : Effect.fail(new OrchestratorProjectionError({ threadId: id }));
177 });
178 const sendToThread = vi.fn((_: unknown) => {
179 switch (options.continuation ?? "queued") {
180 case "fails":
181 return Effect.fail(
182 new ThreadManagementService.ThreadManagementThreadArchivedError({
183 threadId,
184 }),
185 );
186 case "dies":
187 return Effect.die(new Error("send defect"));
188 default:
189 return Effect.succeed({
190 delivery: "queued",
191 } as ThreadManagementService.ThreadManagementSendResult);
192 }
193 });
194 const getById = vi.fn((id: ProjectId) =>
195 options.projectReadFails
196 ? (Effect.fail("simulated project read failure") as never)
197 : Effect.succeed(
198 id === projectId && options.projectMissing !== true
199 ? Option.some(project)
200 : Option.none(),
201 ),
202 );
203 const removeWorktree = vi.fn((_: unknown) =>
204 options.removeWorktreeFails
205 ? (Effect.fail("simulated worktree removal failure") as never)
206 : Effect.void,
207 );
208 const deleteLocalBranch = vi.fn((_: unknown) =>
209 options.deleteLocalBranchFails
210 ? (Effect.fail("simulated local branch deletion failure") as never)
211 : Effect.void,
212 );
213 const fetchWorktreeBaseCommit = vi.fn((_: unknown) =>
214 options.fetchWorktreeBaseFails
215 ? (Effect.fail("simulated fetch failure") as never)
216 : options.worktreeBaseMissing
217 ? Effect.succeed(null)
218 : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }),
219 );
220 const createWorktree = vi.fn(
221 (input: { readonly newRefName?: string | undefined; readonly path: string | null }) =>
222 options.createWorktreeFails
223 ? (Effect.fail("simulated worktree creation failure") as never)
224 : (options.createWorktreeGate ?? Effect.void).pipe(
225 Effect.andThen(
226 Effect.succeed({
227 worktree: {
228 path: input.path ?? `/worktrees/project/${input.newRefName}`,
229 refName: input.newRefName ?? "detached",
230 },
231 }),
232 ),
233 ),
234 );
235 const listRefs = vi.fn((input: { readonly query?: string | undefined }) =>
236 Effect.succeed({
237 refs:
238 options.existingBranchWorktreePath === undefined
239 ? []
240 : [
241 {
242 name: input.query ?? "",
243 current: false,
244 isDefault: false,
245 worktreePath: options.existingBranchWorktreePath,
246 },
247 ],
248 isRepo: true,
249 hasPrimaryRemote: true,
250 nextCursor: null,
251 totalCount: options.existingBranchWorktreePath === undefined ? 0 : 1,
252 }),
253 );
254 const localStatus = vi.fn((_: unknown) =>
255 Effect.succeed({
256 isRepo: options.notARepo !== true,
257 hasPrimaryRemote: true,
258 isDefaultRef: false,
259 refName: options.currentBranch === undefined ? "dev" : options.currentBranch,
260 hasWorkingTreeChanges: false,
261 workingTree: { files: [], insertions: 0, deletions: 0 },
262 }),
263 );
264 const refreshStatus = vi.fn((_: string) => Effect.die("refreshStatus stub"));
265 const runForThread = vi.fn((input: { readonly worktreePath: string }) => {
266 switch (options.setupScript ?? "started") {
267 case "no-script":
268 return Effect.succeed({ status: "no-script" } as const);
269 case "dies":
270 return Effect.die(new Error("setup runner defect"));
271 case "fails":
272 return Effect.fail(
273 new ProjectSetupScriptRunner.ProjectSetupScriptProjectNotFoundError({
274 threadId,
275 worktreePath: input.worktreePath,
276 }),
277 );
278 default:
279 return Effect.succeed({
280 status: "started",
281 async: false,
282 scriptId: "setup",
283 scriptName: "Setup",
284 scriptCommand: "vp install",
285 terminalId: "setup-terminal",
286 cwd: input.worktreePath,
287 } as const);
288 }
289 });
290
291 const layer = WorktreeMcpService.layer.pipe(
292 Layer.provide(
293 Layer.mergeAll(
294 Layer.mock(ThreadManagementService.ThreadManagementService)({
295 dispatch,
296 getThreadRecords,
297 sendToThread,
298 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
299 Layer.mock(ProjectService.ProjectService)({
300 getById,
301 } satisfies Partial<ProjectService.ProjectService["Service"]>),
302 ServerSettings.layerTest({
303 newWorktreesStartFromOrigin: options.newWorktreesStartFromOrigin ?? false,
304 }),
305 Layer.mock(GitWorkflowService.GitWorkflowService)({
306 listRefs,
307 listLocalBranchNames,
308 localStatus,
309 fetchWorktreeBaseCommit,
310 createWorktree,
311 removeWorktree,
312 deleteLocalBranch,
313 ...options.git,
314 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
315 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
316 runForThread,
317 } satisfies Partial<ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]>),
318 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
319 refreshStatus,
320 } satisfies Partial<VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]>),
321 NodeServices.layer,
322 ),
323 ),
324 );
325
326 return {
327 layer,
328 scope,
329 dispatch,
330 sendToThread,
331 fetchWorktreeBaseCommit,
332 createWorktree,
333 removeWorktree,
334 deleteLocalBranch,
335 localStatus,
336 runForThread,
337 };
338};
339
340const expectTypedFailure = (exit: Exit.Exit<unknown, unknown>, expected: object): void => {
341 if (!Exit.isFailure(exit)) {
342 expect.fail(`Expected a failure exit, got: ${JSON.stringify(exit)}`);
343 }
344 const reason = exit.cause.reasons[0];
345 if (reason?._tag !== "Fail") {
346 expect.fail(`Expected a typed Fail cause, got: ${reason?._tag ?? "no reason"}`);
347 }
348 expect(reason.error).toMatchObject(expected);
349};
350
351// Resolve once so calls share the in-flight guard.
352const resolveService = (harness: ReturnType<typeof makeHarness>) =>
353 Effect.gen(function* () {
354 return yield* WorktreeMcpService.WorktreeMcpService;
355 }).pipe(Effect.provide(harness.layer));
356
357const runHandoff = (
358 harness: ReturnType<typeof makeHarness>,
359 input: Parameters<WorktreeMcpService.WorktreeMcpService["Service"]["handoff"]>[1],
360) =>
361 Effect.gen(function* () {
362 const service = yield* WorktreeMcpService.WorktreeMcpService;
363 return yield* service.handoff(harness.scope, input);
364 }).pipe(Effect.provide(harness.layer));
365
366const runStatus = (harness: ReturnType<typeof makeHarness>) =>
367 Effect.gen(function* () {
368 const service = yield* WorktreeMcpService.WorktreeMcpService;
369 return yield* service.status(harness.scope);
370 }).pipe(Effect.provide(harness.layer));
371
372const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
373
374describe("t3_worktree_handoff", () => {
375 it.effect("reports a continuation failure without failing the handoff", () => {
376 const harness = makeHarness({ continuation: "fails" });
377 return Effect.gen(function* () {
378 const result = yield* runHandoff(harness, {
379 branch: "feature/continue-fails",
380 continuationPrompt: "Keep going.",
381 });
382 expect(result.continuation).toMatchObject({ status: "failed" });
383 expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails");
384 expect(harness.dispatch).toHaveBeenCalled();
385 });
386 });
387
388 it.effect("does not queue a continuation when the thread update fails", () => {
389 const harness = makeHarness({ dispatchFails: true });
390 return Effect.gen(function* () {
391 const exit = yield* Effect.exit(
392 runHandoff(harness, {
393 branch: "feature/dispatch-fails-continue",
394 continuationPrompt: "Keep going.",
395 }),
396 );
397 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
398 expect(harness.sendToThread).not.toHaveBeenCalled();
399 });
400 });
401
402 it.effect("uses the fetched commit and remote PR base for an explicit local alias", () =>
403 Effect.gen(function* () {
404 const fs = yield* FileSystem.FileSystem;
405 const git = yield* GitVcsDriver.GitVcsDriver;
406 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "handoff-remote-base-" });
407 const cwd = `${directory}/repo`;
408 const remote = `${directory}/remote.git`;
409 const worktreePath = `${directory}/worktree`;
410 yield* fs.makeDirectory(cwd);
411 const command = (at: string, args: string[]) =>
412 git.execute({ operation: "handoff-test", cwd: at, args });
413 yield* command(cwd, ["init", "-b", "stable"]);
414 yield* command(cwd, ["config", "user.name", "Test"]);
415 yield* command(cwd, ["config", "user.email", "test@example.test"]);
416 yield* command(cwd, ["commit", "--allow-empty", "-m", "remote base"]);
417 const remoteHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
418 yield* command(cwd, ["init", "--bare", remote]);
419 yield* command(cwd, ["remote", "add", "upstream", remote]);
420 yield* command(cwd, ["push", "-u", "upstream", "stable:release"]);
421 yield* command(cwd, ["commit", "--allow-empty", "-m", "local only"]);
422 const harness = makeHarness({
423 git: {
424 fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }),
425 createWorktree: (input) => git.createWorktree({ ...input, cwd, path: worktreePath }),
426 },
427 });
428 const result = yield* runHandoff(harness, {
429 branch: "feature/from-remote",
430 baseRef: "stable",
431 startFromOrigin: true,
432 runSetupScript: false,
433 });
434
435 expect(result.worktreePath).toBe(worktreePath);
436 expect(result.startedFromOrigin).toBe(true);
437 expect(result.setupScript).toEqual({ status: "skipped" });
438 expect((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(remoteHead);
439 const preview = yield* git.getReviewDiffPreview({ cwd: worktreePath });
440 const comparisonBase = preview.sources.find(
441 (source) => source.kind === "branch-range",
442 )!.baseRef;
443 expect(
444 (yield* command(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`])).stdout.trim(),
445 ).toBe(remoteHead);
446 }).pipe(
447 Effect.provide(
448 GitVcsDriver.layer.pipe(
449 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "handoff-remote-git-" })),
450 Layer.provideMerge(NodeServices.layer),
451 ),
452 ),
453 ),
454 );
455
456 it.effect("fails when the thread is already attached to a worktree", () => {
457 const harness = makeHarness({
458 thread: { branch: "feature/existing", worktreePath: "/worktrees/project/existing" },
459 });
460 return Effect.gen(function* () {
461 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/second" }));
462 expectTypedFailure(exit, {
463 _tag: "WorktreeMcpFailure",
464 code: "already_in_worktree",
465 });
466 expect(harness.createWorktree).not.toHaveBeenCalled();
467 });
468 });
469
470 it.effect("rejects an existing branch with an actionable error naming its checkout", () => {
471 const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" });
472 return Effect.gen(function* () {
473 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken" }));
474 if (!Exit.isFailure(exit)) {
475 return expect.fail("expected a failure exit");
476 }
477 const reason = exit.cause.reasons[0];
478 expect(reason?._tag).toBe("Fail");
479 const error = (reason as { readonly error: { code: string; message: string } }).error;
480 expect(error.code).toBe("invalid_request");
481 expect(error.message).toContain("feature/taken");
482 expect(error.message).toContain("already exists");
483 expect(error.message).toContain("/elsewhere/checkout");
484 expect(harness.createWorktree).not.toHaveBeenCalled();
485 expect(harness.fetchWorktreeBaseCommit).not.toHaveBeenCalled();
486 });
487 });
488
489 it.effect("does not trip the pre-flight on similarly named branches", () => {
490 const harness = makeHarness({ existingBranchWorktreePath: null });
491 return Effect.gen(function* () {
492 const result = yield* runHandoff(harness, { branch: "feature/take" });
493 expect(result.branch).toBe("feature/take");
494 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
495 });
496 });
497
498 it.effect("propagates an interrupted dispatch without rolling back the worktree", () => {
499 const harness = makeHarness({ dispatchInterrupts: true });
500 return Effect.gen(function* () {
501 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-int" }));
502 if (!Exit.isFailure(exit)) {
503 return expect.fail("expected a failure exit");
504 }
505 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
506 expect(harness.removeWorktree).not.toHaveBeenCalled();
507 });
508 });
509
510 it.effect("falls back to the local base when no remote holds it", () => {
511 const harness = makeHarness({ worktreeBaseMissing: true });
512 return Effect.gen(function* () {
513 const result = yield* runHandoff(harness, {
514 branch: "feature/local-fallback",
515 baseRef: "dev",
516 startFromOrigin: true,
517 });
518 expect(harness.createWorktree).toHaveBeenCalledWith(
519 expect.objectContaining({ refName: "dev", baseRefName: "dev" }),
520 );
521 expect(result.startedFromOrigin).toBe(false);
522 });
523 });
524
525 it.effect("removes the created worktree when the thread update dies with a defect", () => {
526 const harness = makeHarness({ dispatchDies: true });
527 return Effect.gen(function* () {
528 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-defect" }));
529 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
530 expect(harness.removeWorktree).toHaveBeenCalledWith({
531 cwd: workspaceRoot,
532 path: "/worktrees/project/feature/dispatch-defect",
533 force: true,
534 });
535 });
536 });
537
538 it.effect("re-checks attachment after creating the worktree and backs out on a race", () => {
539 const harness = makeHarness({ threadAttachedOnRecheck: true });
540 return Effect.gen(function* () {
541 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/raced" }));
542 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
543 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
544 expect(harness.removeWorktree).toHaveBeenCalledWith({
545 cwd: workspaceRoot,
546 path: "/worktrees/project/feature/raced",
547 force: true,
548 });
549 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
550 cwd: workspaceRoot,
551 refName: "feature/raced",
552 force: true,
553 });
554 expect(harness.dispatch).not.toHaveBeenCalled();
555 });
556 });
557
558 it.effect("removes the created worktree when the recheck read fails", () => {
559 const harness = makeHarness({ threadReadFailsOnRecheck: true });
560 return Effect.gen(function* () {
561 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/recheck-fails" }));
562 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
563 expect(harness.removeWorktree).toHaveBeenCalledWith({
564 cwd: workspaceRoot,
565 path: "/worktrees/project/feature/recheck-fails",
566 force: true,
567 });
568 expect(harness.dispatch).not.toHaveBeenCalled();
569 });
570 });
571
572 it.effect("backs out when the thread is archived during worktree creation", () => {
573 const harness = makeHarness({ threadArchivedOnRecheck: true });
574 return Effect.gen(function* () {
575 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived-race" }));
576 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
577 expect(harness.dispatch).not.toHaveBeenCalled();
578 expect(harness.removeWorktree).toHaveBeenCalledWith({
579 cwd: workspaceRoot,
580 path: "/worktrees/project/feature/archived-race",
581 force: true,
582 });
583 });
584 });
585
586 it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
587 Effect.gen(function* () {
588 const gate = yield* Deferred.make<void>();
589 const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
590
591 const fiber = yield* Effect.forkChild(
592 runHandoff(harness, {
593 branch: "feature/interrupted",
594 continuationPrompt: "Keep going in the worktree.",
595 }),
596 );
597 yield* Effect.yieldNow;
598 const interruption = yield* Effect.forkChild(Fiber.interrupt(fiber));
599 yield* Effect.yieldNow;
600 yield* Deferred.succeed(gate, undefined);
601 yield* Fiber.await(fiber);
602 yield* Fiber.join(interruption);
603
604 expect(harness.dispatch).toHaveBeenCalledTimes(1);
605 expect(harness.sendToThread).toHaveBeenCalledTimes(1);
606 expect(harness.runForThread).toHaveBeenCalledTimes(1);
607 }),
608 );
609
610 it.effect("creates the worktree in the managed directory even when a call names a path", () => {
611 const harness = makeHarness();
612 return Effect.gen(function* () {
613 const input = yield* decodeHandoffInput({
614 branch: "feature/elsewhere",
615 path: "/home/user/.ssh/checkout",
616 });
617 const result = yield* runHandoff(harness, input);
618 expect(harness.createWorktree).toHaveBeenCalledWith(expect.objectContaining({ path: null }));
619 expect(result.worktreePath).toBe("/worktrees/project/feature/elsewhere");
620 });
621 });
622
623 it.effect("releases the per-thread guard after a failed handoff", () => {
624 const harness = makeHarness({
625 thread: { worktreePath: "/worktrees/project/existing" },
626 });
627 return Effect.gen(function* () {
628 const service = yield* resolveService(harness);
629
630 const first = yield* Effect.exit(
631 service.handoff(harness.scope, { branch: "feature/guard-1" }),
632 );
633 expectTypedFailure(first, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
634 const second = yield* Effect.exit(
635 service.handoff(harness.scope, { branch: "feature/guard-2" }),
636 );
637 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
638 });
639 });
640
641 it.effect("serializes concurrent handoffs for the same thread", () =>
642 Effect.gen(function* () {
643 const gate = yield* Deferred.make<void>();
644 const harness = makeHarness({ createWorktreeGate: Deferred.await(gate) });
645
646 const service = yield* resolveService(harness);
647
648 const first = yield* Effect.forkChild(
649 Effect.exit(service.handoff(harness.scope, { branch: "feature/race-1" })),
650 );
651 yield* Effect.yieldNow;
652
653 const second = yield* Effect.exit(
654 service.handoff(harness.scope, { branch: "feature/race-2" }),
655 );
656 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "handoff_in_progress" });
657
658 yield* Deferred.succeed(gate, undefined);
659 const firstExit = yield* Fiber.join(first);
660 expect(Exit.isSuccess(firstExit)).toBe(true);
661 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
662 }),
663 );
664
665 it.effect("reports a setup script defect without failing the handoff", () => {
666 const harness = makeHarness({ setupScript: "dies" });
667 return Effect.gen(function* () {
668 const result = yield* runHandoff(harness, { branch: "feature/setup-dies" });
669 expect(result.setupScript).toEqual({ status: "failed", detail: "setup runner defect" });
670 expect(harness.dispatch).toHaveBeenCalled();
671 });
672 });
673});
674
675describe("t3_worktree_status", () => {
676 it.effect("reports an attached thread's worktree and branch", () => {
677 const harness = makeHarness({
678 thread: {
679 worktreePath: "/worktrees/project/existing",
680 branch: "feature/existing",
681 },
682 });
683 return Effect.gen(function* () {
684 const result = yield* runStatus(harness);
685 expect(result).toMatchObject({
686 attached: true,
687 worktreePath: "/worktrees/project/existing",
688 branch: "feature/existing",
689 defaultStartFromOrigin: false,
690 });
691 });
692 });
693});