Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorktreeMcpService.test.ts

740 lines28.0 KB

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