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 WorktreeMcpService.WorktreeMcpService.pipe(Effect.provide(harness.layer));
354
355const runHandoff = (
356 harness: ReturnType<typeof makeHarness>,
357 input: Parameters<WorktreeMcpService.WorktreeMcpService["Service"]["handoff"]>[1],
358) =>
359 Effect.gen(function* () {
360 const service = yield* WorktreeMcpService.WorktreeMcpService;
361 return yield* service.handoff(harness.scope, input);
362 }).pipe(Effect.provide(harness.layer));
363
364const runStatus = (harness: ReturnType<typeof makeHarness>) =>
365 Effect.gen(function* () {
366 const service = yield* WorktreeMcpService.WorktreeMcpService;
367 return yield* service.status(harness.scope);
368 }).pipe(Effect.provide(harness.layer));
369
370const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
371
372describe("t3_worktree_handoff", () => {
373 it.effect("reports a continuation failure without failing the handoff", () => {
374 const harness = makeHarness({ continuation: "fails" });
375 return Effect.gen(function* () {
376 const result = yield* runHandoff(harness, {
377 branch: "feature/continue-fails",
378 continuationPrompt: "Keep going.",
379 });
380 expect(result.continuation).toMatchObject({ status: "failed" });
381 expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails");
382 expect(harness.dispatch).toHaveBeenCalled();
383 });
384 });
385
386 it.effect("does not queue a continuation when the thread update fails", () => {
387 const harness = makeHarness({ dispatchFails: true });
388 return Effect.gen(function* () {
389 const exit = yield* Effect.exit(
390 runHandoff(harness, {
391 branch: "feature/dispatch-fails-continue",
392 continuationPrompt: "Keep going.",
393 }),
394 );
395 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
396 expect(harness.sendToThread).not.toHaveBeenCalled();
397 });
398 });
399
400 it.effect("uses the fetched commit and remote PR base for an explicit local alias", () =>
401 Effect.gen(function* () {
402 const fs = yield* FileSystem.FileSystem;
403 const git = yield* GitVcsDriver.GitVcsDriver;
404 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "handoff-remote-base-" });
405 const cwd = `${directory}/repo`;
406 const remote = `${directory}/remote.git`;
407 const worktreePath = `${directory}/worktree`;
408 yield* fs.makeDirectory(cwd);
409 const command = (at: string, args: string[]) =>
410 git.execute({ operation: "handoff-test", cwd: at, args });
411 yield* command(cwd, ["init", "-b", "stable"]);
412 yield* command(cwd, ["config", "user.name", "Test"]);
413 yield* command(cwd, ["config", "user.email", "test@example.test"]);
414 yield* command(cwd, ["commit", "--allow-empty", "-m", "remote base"]);
415 const remoteHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
416 yield* command(cwd, ["init", "--bare", remote]);
417 yield* command(cwd, ["remote", "add", "upstream", remote]);
418 yield* command(cwd, ["push", "-u", "upstream", "stable:release"]);
419 yield* command(cwd, ["commit", "--allow-empty", "-m", "local only"]);
420 const harness = makeHarness({
421 git: {
422 fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }),
423 createWorktree: (input) => git.createWorktree({ ...input, cwd, path: worktreePath }),
424 },
425 });
426 const result = yield* runHandoff(harness, {
427 branch: "feature/from-remote",
428 baseRef: "stable",
429 startFromOrigin: true,
430 runSetupScript: false,
431 });
432
433 expect(result.worktreePath).toBe(worktreePath);
434 expect(result.startedFromOrigin).toBe(true);
435 expect(result.setupScript).toEqual({ status: "skipped" });
436 expect((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(remoteHead);
437 const preview = yield* git.getReviewDiffPreview({ cwd: worktreePath });
438 const comparisonBase = preview.sources.find(
439 (source) => source.kind === "branch-range",
440 )!.baseRef;
441 expect(
442 (yield* command(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`])).stdout.trim(),
443 ).toBe(remoteHead);
444 }).pipe(
445 Effect.provide(
446 GitVcsDriver.layer.pipe(
447 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "handoff-remote-git-" })),
448 Layer.provideMerge(NodeServices.layer),
449 ),
450 ),
451 ),
452 );
453
454 it.effect("fails when the thread is already attached to a worktree", () => {
455 const harness = makeHarness({
456 thread: { branch: "feature/existing", worktreePath: "/worktrees/project/existing" },
457 });
458 return Effect.gen(function* () {
459 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/second" }));
460 expectTypedFailure(exit, {
461 _tag: "WorktreeMcpFailure",
462 code: "already_in_worktree",
463 });
464 expect(harness.createWorktree).not.toHaveBeenCalled();
465 });
466 });
467
468 it.effect("rejects an existing branch with an actionable error naming its checkout", () => {
469 const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" });
470 return Effect.gen(function* () {
471 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken" }));
472 if (!Exit.isFailure(exit)) {
473 return expect.fail("expected a failure exit");
474 }
475 const reason = exit.cause.reasons[0];
476 expect(reason?._tag).toBe("Fail");
477 const error = (reason as { readonly error: { code: string; message: string } }).error;
478 expect(error.code).toBe("invalid_request");
479 expect(error.message).toContain("feature/taken");
480 expect(error.message).toContain("already exists");
481 expect(error.message).toContain("/elsewhere/checkout");
482 expect(harness.createWorktree).not.toHaveBeenCalled();
483 expect(harness.fetchWorktreeBaseCommit).not.toHaveBeenCalled();
484 });
485 });
486
487 it.effect("does not trip the pre-flight on similarly named branches", () => {
488 const harness = makeHarness({ existingBranchWorktreePath: null });
489 return Effect.gen(function* () {
490 const result = yield* runHandoff(harness, { branch: "feature/take" });
491 expect(result.branch).toBe("feature/take");
492 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
493 });
494 });
495
496 it.effect("propagates an interrupted dispatch without rolling back the worktree", () => {
497 const harness = makeHarness({ dispatchInterrupts: true });
498 return Effect.gen(function* () {
499 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-int" }));
500 if (!Exit.isFailure(exit)) {
501 return expect.fail("expected a failure exit");
502 }
503 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
504 expect(harness.removeWorktree).not.toHaveBeenCalled();
505 });
506 });
507
508 it.effect("falls back to the local base when no remote holds it", () => {
509 const harness = makeHarness({ worktreeBaseMissing: true });
510 return Effect.gen(function* () {
511 const result = yield* runHandoff(harness, {
512 branch: "feature/local-fallback",
513 baseRef: "dev",
514 startFromOrigin: true,
515 });
516 expect(harness.createWorktree).toHaveBeenCalledWith(
517 expect.objectContaining({ refName: "dev", baseRefName: "dev" }),
518 );
519 expect(result.startedFromOrigin).toBe(false);
520 });
521 });
522
523 it.effect("removes the created worktree when the thread update dies with a defect", () => {
524 const harness = makeHarness({ dispatchDies: true });
525 return Effect.gen(function* () {
526 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-defect" }));
527 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
528 expect(harness.removeWorktree).toHaveBeenCalledWith({
529 cwd: workspaceRoot,
530 path: "/worktrees/project/feature/dispatch-defect",
531 force: true,
532 });
533 });
534 });
535
536 it.effect("re-checks attachment after creating the worktree and backs out on a race", () => {
537 const harness = makeHarness({ threadAttachedOnRecheck: true });
538 return Effect.gen(function* () {
539 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/raced" }));
540 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
541 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
542 expect(harness.removeWorktree).toHaveBeenCalledWith({
543 cwd: workspaceRoot,
544 path: "/worktrees/project/feature/raced",
545 force: true,
546 });
547 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
548 cwd: workspaceRoot,
549 refName: "feature/raced",
550 force: true,
551 });
552 expect(harness.dispatch).not.toHaveBeenCalled();
553 });
554 });
555
556 it.effect("removes the created worktree when the recheck read fails", () => {
557 const harness = makeHarness({ threadReadFailsOnRecheck: true });
558 return Effect.gen(function* () {
559 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/recheck-fails" }));
560 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
561 expect(harness.removeWorktree).toHaveBeenCalledWith({
562 cwd: workspaceRoot,
563 path: "/worktrees/project/feature/recheck-fails",
564 force: true,
565 });
566 expect(harness.dispatch).not.toHaveBeenCalled();
567 });
568 });
569
570 it.effect("backs out when the thread is archived during worktree creation", () => {
571 const harness = makeHarness({ threadArchivedOnRecheck: true });
572 return Effect.gen(function* () {
573 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived-race" }));
574 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
575 expect(harness.dispatch).not.toHaveBeenCalled();
576 expect(harness.removeWorktree).toHaveBeenCalledWith({
577 cwd: workspaceRoot,
578 path: "/worktrees/project/feature/archived-race",
579 force: true,
580 });
581 });
582 });
583
584 it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
585 Effect.gen(function* () {
586 const gate = yield* Deferred.make<void>();
587 const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
588
589 const fiber = yield* Effect.forkChild(
590 runHandoff(harness, {
591 branch: "feature/interrupted",
592 continuationPrompt: "Keep going in the worktree.",
593 }),
594 );
595 yield* Effect.yieldNow;
596 const interruption = yield* Effect.forkChild(Fiber.interrupt(fiber));
597 yield* Effect.yieldNow;
598 yield* Deferred.succeed(gate, undefined);
599 yield* Fiber.await(fiber);
600 yield* Fiber.join(interruption);
601
602 expect(harness.dispatch).toHaveBeenCalledTimes(1);
603 expect(harness.sendToThread).toHaveBeenCalledTimes(1);
604 expect(harness.runForThread).toHaveBeenCalledTimes(1);
605 }),
606 );
607
608 it.effect("creates the worktree in the managed directory even when a call names a path", () => {
609 const harness = makeHarness();
610 return Effect.gen(function* () {
611 const input = yield* decodeHandoffInput({
612 branch: "feature/elsewhere",
613 path: "/home/user/.ssh/checkout",
614 });
615 const result = yield* runHandoff(harness, input);
616 expect(harness.createWorktree).toHaveBeenCalledWith(expect.objectContaining({ path: null }));
617 expect(result.worktreePath).toBe("/worktrees/project/feature/elsewhere");
618 });
619 });
620
621 it.effect("releases the per-thread guard after a failed handoff", () => {
622 const harness = makeHarness({
623 thread: { worktreePath: "/worktrees/project/existing" },
624 });
625 return Effect.gen(function* () {
626 const service = yield* resolveService(harness);
627
628 const first = yield* Effect.exit(
629 service.handoff(harness.scope, { branch: "feature/guard-1" }),
630 );
631 expectTypedFailure(first, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
632 const second = yield* Effect.exit(
633 service.handoff(harness.scope, { branch: "feature/guard-2" }),
634 );
635 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
636 });
637 });
638
639 it.effect("serializes concurrent handoffs for the same thread", () =>
640 Effect.gen(function* () {
641 const gate = yield* Deferred.make<void>();
642 const harness = makeHarness({ createWorktreeGate: Deferred.await(gate) });
643
644 const service = yield* resolveService(harness);
645
646 const first = yield* Effect.forkChild(
647 Effect.exit(service.handoff(harness.scope, { branch: "feature/race-1" })),
648 );
649 yield* Effect.yieldNow;
650
651 const second = yield* Effect.exit(
652 service.handoff(harness.scope, { branch: "feature/race-2" }),
653 );
654 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "handoff_in_progress" });
655
656 yield* Deferred.succeed(gate, undefined);
657 const firstExit = yield* Fiber.join(first);
658 expect(Exit.isSuccess(firstExit)).toBe(true);
659 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
660 }),
661 );
662
663 it.effect("reports a setup script defect without failing the handoff", () => {
664 const harness = makeHarness({ setupScript: "dies" });
665 return Effect.gen(function* () {
666 const result = yield* runHandoff(harness, { branch: "feature/setup-dies" });
667 expect(result.setupScript).toEqual({ status: "failed", detail: "setup runner defect" });
668 expect(harness.dispatch).toHaveBeenCalled();
669 });
670 });
671});
672
673describe("t3_worktree_status", () => {
674 it.effect("reports an attached thread's worktree and branch", () => {
675 const harness = makeHarness({
676 thread: {
677 worktreePath: "/worktrees/project/existing",
678 branch: "feature/existing",
679 },
680 });
681 return Effect.gen(function* () {
682 const result = yield* runStatus(harness);
683 expect(result).toMatchObject({
684 attached: true,
685 worktreePath: "/worktrees/project/existing",
686 branch: "feature/existing",
687 defaultStartFromOrigin: false,
688 });
689 });
690 });
691});