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