Open History to see the last commit
1import { describe, expect, it, vi } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import {
5 CommandId,
6 EnvironmentId,
7 type OrchestrationV2ThreadProjection,
8 type Project,
9 ProjectId,
10 ProviderInstanceId,
11 ThreadId,
12 WorktreeMcpHandoffInput,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Fiber from "effect/Fiber";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Schema from "effect/Schema";
23
24import * as GitWorkflowService from "../git/GitWorkflowService.ts";
25import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
26import * as ServerConfig from "../config.ts";
27import {
28 OrchestratorDispatchError,
29 OrchestratorProjectionError,
30} from "../orchestration-v2/Orchestrator.ts";
31import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
32import * as ProjectService from "../project/ProjectService.ts";
33import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
36import type * as McpInvocationContext from "./McpInvocationContext.ts";
37import * as WorktreeMcpService from "./WorktreeMcpService.ts";
38
39const environmentId = EnvironmentId.make("environment-worktree-test");
40const threadId = ThreadId.make("thread-worktree-test");
41const projectId = ProjectId.make("project-worktree-test");
42const workspaceRoot = "/repo/project";
43
44const makeScope = (
45 capabilities: ReadonlySet<McpInvocationContext.McpCapability>,
46): McpInvocationContext.McpInvocationScope => ({
47 environmentId,
48 requestNamespace: "provider-session-worktree-test",
49 thread: {
50 threadId,
51 providerSessionId: "provider-session-worktree-test",
52 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
53 },
54 client: undefined,
55 capabilities,
56 issuedAt: 1,
57});
58
59interface ThreadFixture {
60 readonly branch?: string | null;
61 readonly worktreePath?: string | null;
62 readonly archivedAt?: string | null;
63 readonly deletedAt?: string | null;
64}
65
66const makeProjection = (overrides: ThreadFixture = {}): OrchestrationV2ThreadProjection =>
67 ({
68 thread: {
69 id: threadId,
70 projectId,
71 title: "Worktree test thread",
72 branch: null,
73 worktreePath: null,
74 archivedAt: null,
75 deletedAt: null,
76 ...overrides,
77 },
78 }) as OrchestrationV2ThreadProjection;
79
80const project: Project = {
81 id: projectId,
82 title: "Worktree test project",
83 workspaceRoot,
84 defaultModelSelection: null,
85 scripts: [],
86 createdAt: "2026-01-01T00:00:00.000Z",
87 updatedAt: "2026-01-01T00:00:00.000Z",
88 deletedAt: null,
89} as Project;
90
91interface HarnessOptions {
92 readonly git?: Partial<GitWorkflowService.GitWorkflowService["Service"]>;
93 readonly thread?: ThreadFixture | null;
94 readonly threadReadError?: "projection" | "dispatch";
95 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
96 readonly currentBranch?: string | null;
97 readonly notARepo?: boolean;
98 readonly newWorktreesStartFromOrigin?: boolean;
99 readonly setupScript?: "started" | "no-script" | "fails" | "dies";
100 readonly dispatchFails?: boolean;
101 readonly dispatchDies?: boolean;
102 readonly dispatchInterrupts?: boolean;
103 readonly dispatchGate?: Effect.Effect<void>;
104 readonly threadAttachedOnRecheck?: boolean;
105 readonly threadArchivedOnRecheck?: boolean;
106 readonly threadReadFailsOnRecheck?: boolean;
107 readonly continuation?: "queued" | "fails" | "dies";
108 readonly projectMissing?: boolean;
109 readonly projectReadFails?: boolean;
110 readonly existingBranchWorktreePath?: string | null;
111 readonly createWorktreeFails?: boolean;
112 readonly fetchWorktreeBaseFails?: boolean;
113 readonly worktreeBaseMissing?: boolean;
114 readonly removeWorktreeFails?: boolean;
115 readonly deleteLocalBranchFails?: boolean;
116 readonly createWorktreeGate?: Effect.Effect<void>;
117}
118
119const makeHarness = (options: HarnessOptions = {}) => {
120 const thread = options.thread === undefined ? {} : options.thread;
121 const scope = makeScope(options.capabilities ?? new Set(["preview", "worktree"]));
122 const dispatch = vi.fn((_: unknown) =>
123 (options.dispatchGate ?? Effect.void).pipe(
124 Effect.andThen(
125 options.dispatchInterrupts
126 ? (Effect.failCause(Cause.interrupt()) as never)
127 : options.dispatchDies
128 ? Effect.die(new Error("dispatch defect"))
129 : options.dispatchFails
130 ? (Effect.fail("simulated dispatch failure") as never)
131 : Effect.succeed({ sequence: 1, storedEvents: [] }),
132 ),
133 ),
134 );
135 const listLocalBranchNames = vi.fn((_: string) =>
136 Effect.succeed(
137 options.existingBranchWorktreePath === undefined
138 ? ["dev"]
139 : ["dev", "feature/taken", "feature/taken-idle"],
140 ),
141 );
142 const getThreadRecords = vi.fn((id: ThreadId) => {
143 if (options.threadReadError === "dispatch") {
144 return Effect.fail(
145 new OrchestratorDispatchError({
146 commandId: CommandId.make("command:test:read"),
147 commandType: "thread.metadata.update",
148 }),
149 ) as never;
150 }
151 if (options.threadReadFailsOnRecheck === true && getThreadRecords.mock.calls.length > 1) {
152 return Effect.fail(
153 new OrchestratorDispatchError({
154 commandId: CommandId.make("command:test:recheck"),
155 commandType: "thread.metadata.update",
156 }),
157 ) as never;
158 }
159 if (
160 options.threadAttachedOnRecheck === true &&
161 getThreadRecords.mock.calls.length > 1 &&
162 thread !== null
163 ) {
164 return Effect.succeed(
165 makeProjection({ ...thread, worktreePath: "/worktrees/project/raced" }),
166 );
167 }
168 if (
169 options.threadArchivedOnRecheck === true &&
170 getThreadRecords.mock.calls.length > 1 &&
171 thread !== null
172 ) {
173 return Effect.succeed(makeProjection({ ...thread, archivedAt: "2026-01-02T00:00:00.000Z" }));
174 }
175 return id === threadId && thread !== null
176 ? Effect.succeed(makeProjection(thread))
177 : Effect.fail(new OrchestratorProjectionError({ threadId: id }));
178 });
179 const sendToThread = vi.fn((_: unknown) => {
180 switch (options.continuation ?? "queued") {
181 case "fails":
182 return Effect.fail(
183 new ThreadManagementService.ThreadManagementThreadArchivedError({
184 threadId,
185 }),
186 );
187 case "dies":
188 return Effect.die(new Error("send defect"));
189 default:
190 return Effect.succeed({
191 delivery: "queued",
192 } as ThreadManagementService.ThreadManagementSendResult);
193 }
194 });
195 const getById = vi.fn((id: ProjectId) =>
196 options.projectReadFails
197 ? (Effect.fail("simulated project read failure") as never)
198 : Effect.succeed(
199 id === projectId && options.projectMissing !== true
200 ? Option.some(project)
201 : Option.none(),
202 ),
203 );
204 const removeWorktree = vi.fn((_: unknown) =>
205 options.removeWorktreeFails
206 ? (Effect.fail("simulated worktree removal failure") as never)
207 : Effect.void,
208 );
209 const deleteLocalBranch = vi.fn((_: unknown) =>
210 options.deleteLocalBranchFails
211 ? (Effect.fail("simulated local branch deletion failure") as never)
212 : Effect.void,
213 );
214 const fetchWorktreeBaseCommit = vi.fn((_: unknown) =>
215 options.fetchWorktreeBaseFails
216 ? (Effect.fail("simulated fetch failure") as never)
217 : options.worktreeBaseMissing
218 ? Effect.succeed(null)
219 : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }),
220 );
221 const createWorktree = vi.fn(
222 (input: { readonly newRefName?: string | undefined; readonly path: string | null }) =>
223 options.createWorktreeFails
224 ? (Effect.fail("simulated worktree creation failure") as never)
225 : (options.createWorktreeGate ?? Effect.void).pipe(
226 Effect.andThen(
227 Effect.succeed({
228 worktree: {
229 path: input.path ?? `/worktrees/project/${input.newRefName}`,
230 refName: input.newRefName ?? "detached",
231 },
232 }),
233 ),
234 ),
235 );
236 const listRefs = vi.fn((input: { readonly query?: string | undefined }) =>
237 Effect.succeed({
238 refs:
239 options.existingBranchWorktreePath === undefined
240 ? []
241 : [
242 {
243 name: input.query ?? "",
244 current: false,
245 isDefault: false,
246 worktreePath: options.existingBranchWorktreePath,
247 },
248 ],
249 isRepo: true,
250 hasPrimaryRemote: true,
251 nextCursor: null,
252 totalCount: options.existingBranchWorktreePath === undefined ? 0 : 1,
253 }),
254 );
255 const localStatus = vi.fn((_: unknown) =>
256 Effect.succeed({
257 isRepo: options.notARepo !== true,
258 hasPrimaryRemote: true,
259 isDefaultRef: false,
260 refName: options.currentBranch === undefined ? "dev" : options.currentBranch,
261 hasWorkingTreeChanges: false,
262 workingTree: { files: [], insertions: 0, deletions: 0 },
263 }),
264 );
265 const refreshStatus = vi.fn((_: string) => Effect.die("refreshStatus stub"));
266 const runForThread = vi.fn((input: { readonly worktreePath: string }) => {
267 switch (options.setupScript ?? "started") {
268 case "no-script":
269 return Effect.succeed({ status: "no-script" } as const);
270 case "dies":
271 return Effect.die(new Error("setup runner defect"));
272 case "fails":
273 return Effect.fail(
274 new ProjectSetupScriptRunner.ProjectSetupScriptProjectNotFoundError({
275 threadId,
276 worktreePath: input.worktreePath,
277 }),
278 );
279 default:
280 return Effect.succeed({
281 status: "started",
282 async: false,
283 scriptId: "setup",
284 scriptName: "Setup",
285 scriptCommand: "vp install",
286 terminalId: "setup-terminal",
287 cwd: input.worktreePath,
288 } as const);
289 }
290 });
291
292 const layer = WorktreeMcpService.layer.pipe(
293 Layer.provide(
294 Layer.mergeAll(
295 Layer.mock(ThreadManagementService.ThreadManagementService)({
296 dispatch,
297 getThreadRecords,
298 sendToThread,
299 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
300 Layer.mock(ProjectService.ProjectService)({
301 getById,
302 } satisfies Partial<ProjectService.ProjectService["Service"]>),
303 ServerSettings.layerTest({
304 newWorktreesStartFromOrigin: options.newWorktreesStartFromOrigin ?? false,
305 }),
306 Layer.mock(GitWorkflowService.GitWorkflowService)({
307 listRefs,
308 listLocalBranchNames,
309 localStatus,
310 fetchWorktreeBaseCommit,
311 createWorktree,
312 removeWorktree,
313 deleteLocalBranch,
314 ...options.git,
315 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
316 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
317 runForThread,
318 } satisfies Partial<ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]>),
319 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
320 refreshStatus,
321 } satisfies Partial<VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]>),
322 NodeServices.layer,
323 NodeCrypto.layer,
324 ),
325 ),
326 );
327
328 return {
329 layer,
330 scope,
331 dispatch,
332 sendToThread,
333 fetchWorktreeBaseCommit,
334 createWorktree,
335 removeWorktree,
336 deleteLocalBranch,
337 localStatus,
338 runForThread,
339 };
340};
341
342const expectTypedFailure = (exit: Exit.Exit<unknown, unknown>, expected: object): void => {
343 if (!Exit.isFailure(exit)) {
344 expect.fail(`Expected a failure exit, got: ${JSON.stringify(exit)}`);
345 }
346 const reason = exit.cause.reasons[0];
347 if (reason?._tag !== "Fail") {
348 expect.fail(`Expected a typed Fail cause, got: ${reason?._tag ?? "no reason"}`);
349 }
350 expect(reason.error).toMatchObject(expected);
351};
352
353// Resolve once so calls share the in-flight guard.
354const resolveService = (harness: ReturnType<typeof makeHarness>) =>
355 WorktreeMcpService.WorktreeMcpService.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(Layer.mergeAll(NodeServices.layer, NodeCrypto.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});