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