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

WorktreeMcpService.test.ts

1,065 lines41.4 KB

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 Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22​
23import * as GitWorkflowService from "../git/GitWorkflowService.ts";
24import {
25 OrchestratorDispatchError,
26 OrchestratorProjectionError,
27} from "../orchestration-v2/Orchestrator.ts";
28import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
29import * as ProjectService from "../project/ProjectService.ts";
30import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
31import * as ServerSettings from "../serverSettings.ts";
32import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
33import type * as McpInvocationContext from "./McpInvocationContext.ts";
34import * as WorktreeMcpService from "./WorktreeMcpService.ts";
35​
36const environmentId = EnvironmentId.make("environment-worktree-test");
37const threadId = ThreadId.make("thread-worktree-test");
38const projectId = ProjectId.make("project-worktree-test");
39const workspaceRoot = "/repo/project";
40​
41const makeScope = (
42 capabilities: ReadonlySet<McpInvocationContext.McpCapability>,
43): McpInvocationContext.McpInvocationScope => ({
44 environmentId,
45 threadId,
46 providerSessionId: "provider-session-worktree-test",
47 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
48 capabilities,
49 issuedAt: 1,
50});
51​
52interface ThreadFixture {
53 readonly branch?: string | null;
54 readonly worktreePath?: string | null;
55 readonly archivedAt?: string | null;
56 readonly deletedAt?: string | null;
58​
59const makeProjection = (overrides: ThreadFixture = {}): OrchestrationV2ThreadProjection =>
60 ({
61 thread: {
62 id: threadId,
63 projectId,
64 title: "Worktree test thread",
65 branch: null,
66 worktreePath: null,
67 archivedAt: null,
68 deletedAt: null,
69 ...overrides,
70 },
71 }) as OrchestrationV2ThreadProjection;
72​
73const project: Project = {
74 id: projectId,
75 title: "Worktree test project",
76 workspaceRoot,
77 defaultModelSelection: null,
78 scripts: [],
79 createdAt: "2026-01-01T00:00:00.000Z",
80 updatedAt: "2026-01-01T00:00:00.000Z",
81 deletedAt: null,
82} as Project;
83​
84interface HarnessOptions {
85 readonly thread?: ThreadFixture | null;
86 readonly threadReadError?: "projection" | "dispatch";
87 readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
88 readonly currentBranch?: string | null;
89 readonly notARepo?: boolean;
90 readonly newWorktreesStartFromOrigin?: boolean;
91 readonly setupScript?: "started" | "no-script" | "fails" | "dies";
92 readonly dispatchFails?: boolean;
93 readonly dispatchDies?: boolean;
94 readonly dispatchInterrupts?: boolean;
95 readonly dispatchGate?: Effect.Effect<void>;
96 readonly threadAttachedOnRecheck?: boolean;
97 readonly threadArchivedOnRecheck?: boolean;
98 readonly threadReadFailsOnRecheck?: boolean;
99 readonly continuation?: "queued" | "fails" | "dies";
100 readonly projectMissing?: boolean;
101 readonly projectReadFails?: boolean;
102 readonly existingBranchWorktreePath?: string | null;
103 readonly pathSemantics?: "win32" | "posix";
104 readonly createWorktreeFails?: boolean;
105 readonly fetchRemoteFails?: boolean;
106 readonly resolveRemoteFails?: boolean;
107 readonly removeWorktreeFails?: boolean;
108 readonly deleteLocalBranchFails?: boolean;
109 readonly createWorktreeGate?: Effect.Effect<void>;
111​
112const makeHarness = (options: HarnessOptions = {}) => {
113 const thread = options.thread === undefined ? {} : options.thread;
114 const scope = makeScope(options.capabilities ?? new Set(["preview", "worktree"]));
115 const dispatch = vi.fn((_: unknown) =>
116 (options.dispatchGate ?? Effect.void).pipe(
117 Effect.andThen(
118 options.dispatchInterrupts
119 ? (Effect.failCause(Cause.interrupt()) as never)
120 : options.dispatchDies
121 ? Effect.die(new Error("dispatch defect"))
122 : options.dispatchFails
123 ? (Effect.fail("simulated dispatch failure") as never)
124 : Effect.succeed({ sequence: 1, storedEvents: [] }),
125 ),
126 ),
127 );
128 const listLocalBranchNames = vi.fn((_: string) =>
129 Effect.succeed(
130 options.existingBranchWorktreePath === undefined
131 ? ["dev"]
132 : ["dev", "feature/taken", "feature/taken-idle"],
133 ),
134 );
135 const getThreadRecords = vi.fn((id: ThreadId) => {
136 if (options.threadReadError === "dispatch") {
137 return Effect.fail(
138 new OrchestratorDispatchError({
139 commandId: CommandId.make("command:test:read"),
140 commandType: "thread.metadata.update",
141 }),
142 ) as never;
143 }
144 if (options.threadReadFailsOnRecheck === true && getThreadRecords.mock.calls.length > 1) {
145 return Effect.fail(
146 new OrchestratorDispatchError({
147 commandId: CommandId.make("command:test:recheck"),
148 commandType: "thread.metadata.update",
149 }),
150 ) as never;
151 }
152 if (
153 options.threadAttachedOnRecheck === true &&
154 getThreadRecords.mock.calls.length > 1 &&
155 thread !== null
156 ) {
157 return Effect.succeed(
158 makeProjection({ ...thread, worktreePath: "/worktrees/project/raced" }),
159 );
160 }
161 if (
162 options.threadArchivedOnRecheck === true &&
163 getThreadRecords.mock.calls.length > 1 &&
164 thread !== null
165 ) {
166 return Effect.succeed(makeProjection({ ...thread, archivedAt: "2026-01-02T00:00:00.000Z" }));
167 }
168 return id === threadId && thread !== null
169 ? Effect.succeed(makeProjection(thread))
170 : Effect.fail(new OrchestratorProjectionError({ threadId: id }));
171 });
172 const sendToThread = vi.fn((_: unknown) => {
173 switch (options.continuation ?? "queued") {
174 case "fails":
175 return Effect.fail(
176 new ThreadManagementService.ThreadManagementThreadArchivedError({
177 threadId,
178 }),
179 );
180 case "dies":
181 return Effect.die(new Error("send defect"));
182 default:
183 return Effect.succeed({
184 delivery: "queued",
185 } as ThreadManagementService.ThreadManagementSendResult);
186 }
187 });
188 const getById = vi.fn((id: ProjectId) =>
189 options.projectReadFails
190 ? (Effect.fail("simulated project read failure") as never)
191 : Effect.succeed(
192 id === projectId && options.projectMissing !== true
193 ? Option.some(project)
194 : Option.none(),
195 ),
196 );
197 const removeWorktree = vi.fn((_: unknown) =>
198 options.removeWorktreeFails
199 ? (Effect.fail("simulated worktree removal failure") as never)
200 : Effect.void,
201 );
202 const deleteLocalBranch = vi.fn((_: unknown) =>
203 options.deleteLocalBranchFails
204 ? (Effect.fail("simulated local branch deletion failure") as never)
205 : Effect.void,
206 );
207 const fetchRemote = vi.fn((_: unknown) =>
208 options.fetchRemoteFails ? (Effect.fail("simulated fetch failure") as never) : Effect.void,
209 );
210 const resolveRemoteTrackingCommit = vi.fn((_: unknown) =>
211 options.resolveRemoteFails
212 ? (Effect.fail("simulated remote resolve failure") as never)
213 : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }),
214 );
215 const createWorktree = vi.fn(
216 (input: { readonly newRefName?: string | undefined; readonly path: string | null }) =>
217 options.createWorktreeFails
218 ? (Effect.fail("simulated worktree creation failure") as never)
219 : (options.createWorktreeGate ?? Effect.void).pipe(
220 Effect.andThen(
221 Effect.succeed({
222 worktree: {
223 path: input.path ?? `/worktrees/project/${input.newRefName}`,
224 refName: input.newRefName ?? "detached",
225 },
226 }),
227 ),
228 ),
229 );
230 const listRefs = vi.fn((input: { readonly query?: string | undefined }) =>
231 Effect.succeed({
232 refs:
233 options.existingBranchWorktreePath === undefined
234 ? []
235 : [
236 {
237 name: input.query ?? "",
238 current: false,
239 isDefault: false,
240 worktreePath: options.existingBranchWorktreePath,
241 },
242 ],
243 isRepo: true,
244 hasPrimaryRemote: true,
245 nextCursor: null,
246 totalCount: options.existingBranchWorktreePath === undefined ? 0 : 1,
247 }),
248 );
249 const localStatus = vi.fn((_: unknown) =>
250 Effect.succeed({
251 isRepo: options.notARepo !== true,
252 hasPrimaryRemote: true,
253 isDefaultRef: false,
254 refName: options.currentBranch === undefined ? "dev" : options.currentBranch,
255 hasWorkingTreeChanges: false,
256 workingTree: { files: [], insertions: 0, deletions: 0 },
257 }),
258 );
259 const refreshStatus = vi.fn((_: string) => Effect.die("refreshStatus stub"));
260 const runForThread = vi.fn((input: { readonly worktreePath: string }) => {
261 switch (options.setupScript ?? "started") {
262 case "no-script":
263 return Effect.succeed({ status: "no-script" } as const);
264 case "dies":
265 return Effect.die(new Error("setup runner defect"));
266 case "fails":
267 return Effect.fail(
268 new ProjectSetupScriptRunner.ProjectSetupScriptProjectNotFoundError({
269 threadId,
270 worktreePath: input.worktreePath,
271 }),
272 );
273 default:
274 return Effect.succeed({
275 status: "started",
276 async: false,
277 scriptId: "setup",
278 scriptName: "Setup",
279 scriptCommand: "vp install",
280 terminalId: "setup-terminal",
281 cwd: input.worktreePath,
282 } as const);
283 }
284 });
285​
286 // Optional deterministic Path semantics: providing this BEFORE the general
287 // mocks means the service resolves Path here rather than from NodeServices,
288 // so absolute-path validation is testable independently of the host OS. The
289 // service only calls isAbsolute; the minimal per-platform semantics are
290 // inlined so the test does not depend on the host's path module.
291 const win32IsAbsolute = (value: string) => /^(?:[a-zA-Z]:[\\/]|[\\/])/.test(value);
292 const posixIsAbsolute = (value: string) => value.startsWith("/");
293 const serviceLayer =
294 options.pathSemantics === undefined
295 ? WorktreeMcpService.layer
296 : WorktreeMcpService.layer.pipe(
297 Layer.provide(
298 Layer.succeed(Path.Path, {
299 isAbsolute: options.pathSemantics === "win32" ? win32IsAbsolute : posixIsAbsolute,
300 } as unknown as Path.Path),
301 ),
302 );
303 const layer = serviceLayer.pipe(
304 Layer.provide(
305 Layer.mergeAll(
306 Layer.mock(ThreadManagementService.ThreadManagementService)({
307 dispatch,
308 getThreadRecords,
309 sendToThread,
310 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
311 Layer.mock(ProjectService.ProjectService)({
312 getById,
313 } satisfies Partial<ProjectService.ProjectService["Service"]>),
314 ServerSettings.layerTest({
315 newWorktreesStartFromOrigin: options.newWorktreesStartFromOrigin ?? false,
316 }),
317 Layer.mock(GitWorkflowService.GitWorkflowService)({
318 listRefs,
319 listLocalBranchNames,
320 localStatus,
321 fetchRemote,
322 resolveRemoteTrackingCommit,
323 createWorktree,
324 removeWorktree,
325 deleteLocalBranch,
326 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
327 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
328 runForThread,
329 } satisfies Partial<ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]>),
330 Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
331 refreshStatus,
332 } satisfies Partial<VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]>),
333 NodeServices.layer,
334 ),
335 ),
336 );
337​
338 return {
339 layer,
340 scope,
341 dispatch,
342 sendToThread,
343 fetchRemote,
344 resolveRemoteTrackingCommit,
345 createWorktree,
346 removeWorktree,
347 deleteLocalBranch,
348 localStatus,
349 runForThread,
350 };
351};
352​
353const expectTypedFailure = (exit: Exit.Exit<unknown, unknown>, expected: object): void => {
354 if (!Exit.isFailure(exit)) {
355 expect.fail(`Expected a failure exit, got: ${JSON.stringify(exit)}`);
356 }
357 const reason = exit.cause.reasons[0];
358 if (reason?._tag !== "Fail") {
359 expect.fail(`Expected a typed Fail cause, got: ${reason?._tag ?? "no reason"}`);
360 }
361 expect(reason.error).toMatchObject(expected);
362};
363​
364// Resolves the service once from the harness layer; used by tests that must
365// make several calls against the SAME instance (the in-flight guard lives in
366// the layer's closure, so a fresh layer per call would never see it).
367const resolveService = (harness: ReturnType<typeof makeHarness>) =>
368 Effect.gen(function* () {
369 return yield* WorktreeMcpService.WorktreeMcpService;
370 }).pipe(Effect.provide(harness.layer));
371​
372const runHandoff = (
373 harness: ReturnType<typeof makeHarness>,
374 input: Parameters<WorktreeMcpService.WorktreeMcpService["Service"]["handoff"]>[1],
375) =>
376 Effect.gen(function* () {
377 const service = yield* WorktreeMcpService.WorktreeMcpService;
378 return yield* service.handoff(harness.scope, input);
379 }).pipe(Effect.provide(harness.layer));
380​
381const runStatus = (harness: ReturnType<typeof makeHarness>) =>
382 Effect.gen(function* () {
383 const service = yield* WorktreeMcpService.WorktreeMcpService;
384 return yield* service.status(harness.scope);
385 }).pipe(Effect.provide(harness.layer));
386​
387describe("t3_worktree_handoff", () => {
388 it.effect("creates a worktree from the current branch and re-points the thread", () => {
389 const harness = makeHarness();
390 return Effect.gen(function* () {
391 const result = yield* runHandoff(harness, { branch: "feature/handoff" });
392​
393 expect(result.branch).toBe("feature/handoff");
394 expect(result.baseRef).toBe("dev");
395 expect(result.startedFromOrigin).toBe(false);
396 expect(result.worktreePath).toBe("/worktrees/project/feature/handoff");
397 expect(result.setupScript).toMatchObject({
398 status: "started",
399 scriptName: "Setup",
400 });
401​
402 expect(harness.fetchRemote).not.toHaveBeenCalled();
403 expect(harness.createWorktree).toHaveBeenCalledWith({
404 cwd: workspaceRoot,
405 refName: "dev",
406 newRefName: "feature/handoff",
407 baseRefName: "dev",
408 path: null,
409 });
410 expect(harness.dispatch).toHaveBeenCalledWith(
411 expect.objectContaining({
412 type: "thread.metadata.update",
413 threadId,
414 branch: "feature/handoff",
415 worktreePath: "/worktrees/project/feature/handoff",
416 expectedWorktreePath: null,
417 }),
418 );
419 expect(harness.runForThread).toHaveBeenCalledWith({
420 threadId,
421 projectId,
422 projectCwd: workspaceRoot,
423 worktreePath: "/worktrees/project/feature/handoff",
424 project: { id: projectId, workspaceRoot, scripts: [] },
425 });
426 });
427 });
428​
429 it.effect("skips the continuation when no continuationPrompt is given", () => {
430 const harness = makeHarness();
431 return Effect.gen(function* () {
432 const result = yield* runHandoff(harness, { branch: "feature/no-continuation" });
433 expect(result.continuation).toEqual({ status: "skipped" });
434 expect(harness.sendToThread).not.toHaveBeenCalled();
435 });
436 });
437​
438 it.effect("queues the continuation prompt as the thread's next message", () => {
439 const harness = makeHarness();
440 return Effect.gen(function* () {
441 const result = yield* runHandoff(harness, {
442 branch: "feature/continue",
443 continuationPrompt: "Keep fixing the login bug in the new worktree.",
444 });
445​
446 expect(result.continuation).toEqual({ status: "scheduled", delivery: "queued" });
447 expect(harness.sendToThread).toHaveBeenCalledWith(
448 expect.objectContaining({
449 projectId,
450 threadId,
451 text: "Keep fixing the login bug in the new worktree.",
452 mode: "queue",
453 createdBy: "agent",
454 creationSource: "mcp",
455 }),
456 );
457 // The continuation must be durably queued before anything slower runs.
458 expect(harness.sendToThread.mock.invocationCallOrder[0]).toBeLessThan(
459 harness.runForThread.mock.invocationCallOrder[0]!,
460 );
461 });
462 });
463​
464 it.effect("reports a continuation failure without failing the handoff", () => {
465 const harness = makeHarness({ continuation: "fails" });
466 return Effect.gen(function* () {
467 const result = yield* runHandoff(harness, {
468 branch: "feature/continue-fails",
469 continuationPrompt: "Keep going.",
470 });
471 expect(result.continuation).toMatchObject({ status: "failed" });
472 expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails");
473 expect(harness.dispatch).toHaveBeenCalled();
474 });
475 });
476​
477 it.effect("reports a continuation defect without failing the handoff", () => {
478 const harness = makeHarness({ continuation: "dies" });
479 return Effect.gen(function* () {
480 const result = yield* runHandoff(harness, {
481 branch: "feature/continue-dies",
482 continuationPrompt: "Keep going.",
483 });
484 expect(result.continuation).toEqual({ status: "failed", detail: "send defect" });
485 expect(result.setupScript).toMatchObject({ status: "started" });
486 });
487 });
488​
489 it.effect("does not queue a continuation when the thread update fails", () => {
490 const harness = makeHarness({ dispatchFails: true });
491 return Effect.gen(function* () {
492 const exit = yield* Effect.exit(
493 runHandoff(harness, {
494 branch: "feature/dispatch-fails-continue",
495 continuationPrompt: "Keep going.",
496 }),
497 );
498 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
499 expect(harness.sendToThread).not.toHaveBeenCalled();
500 });
501 });
502​
503 it.effect("starts from origin and honors explicit baseRef and path", () => {
504 const harness = makeHarness();
505 return Effect.gen(function* () {
506 const result = yield* runHandoff(harness, {
507 branch: "feature/from-origin",
508 baseRef: "dev",
509 startFromOrigin: true,
510 path: "/custom/worktree/location",
511 runSetupScript: false,
512 });
513​
514 expect(harness.fetchRemote).toHaveBeenCalledWith({
515 cwd: workspaceRoot,
516 remoteName: "origin",
517 });
518 expect(harness.resolveRemoteTrackingCommit).toHaveBeenCalledWith({
519 cwd: workspaceRoot,
520 refName: "dev",
521 fallbackRemoteName: "origin",
522 });
523 expect(harness.createWorktree).toHaveBeenCalledWith({
524 cwd: workspaceRoot,
525 refName: "abc123",
526 newRefName: "feature/from-origin",
527 baseRefName: "dev",
528 path: "/custom/worktree/location",
529 });
530 // localStatus is always consulted now (repo pre-check), but its branch
531 // must not override the explicit baseRef.
532 expect(harness.localStatus).toHaveBeenCalled();
533 expect(harness.runForThread).not.toHaveBeenCalled();
534 expect(result.worktreePath).toBe("/custom/worktree/location");
535 expect(result.startedFromOrigin).toBe(true);
536 expect(result.setupScript).toEqual({ status: "skipped" });
537 });
538 });
539​
540 it.effect("uses the server setting for startFromOrigin when unspecified", () => {
541 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
542 return Effect.gen(function* () {
543 const result = yield* runHandoff(harness, { branch: "feature/settings-origin" });
544 expect(result.startedFromOrigin).toBe(true);
545 expect(harness.fetchRemote).toHaveBeenCalled();
546 });
547 });
548​
549 it.effect("fails when the thread is already attached to a worktree", () => {
550 const harness = makeHarness({
551 thread: { branch: "feature/existing", worktreePath: "/worktrees/project/existing" },
552 });
553 return Effect.gen(function* () {
554 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/second" }));
555 expectTypedFailure(exit, {
556 _tag: "WorktreeMcpFailure",
557 code: "already_in_worktree",
558 });
559 expect(harness.createWorktree).not.toHaveBeenCalled();
560 });
561 });
562​
563 it.effect("fails when the thread does not exist", () => {
564 const harness = makeHarness({ thread: null });
565 return Effect.gen(function* () {
566 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/missing" }));
567 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
568 expect(harness.createWorktree).not.toHaveBeenCalled();
569 });
570 });
571​
572 it.effect("treats a soft-deleted thread as not found", () => {
573 const harness = makeHarness({ thread: { deletedAt: "2026-01-02T00:00:00.000Z" } });
574 return Effect.gen(function* () {
575 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/deleted" }));
576 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
577 expect(harness.createWorktree).not.toHaveBeenCalled();
578 });
579 });
580​
581 it.effect("maps a non-projection orchestrator error to operation_failed", () => {
582 const harness = makeHarness({ threadReadError: "dispatch" });
583 return Effect.gen(function* () {
584 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/read-error" }));
585 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
586 expect(harness.createWorktree).not.toHaveBeenCalled();
587 });
588 });
589​
590 it.effect("fails when the project does not exist", () => {
591 const harness = makeHarness({ projectMissing: true });
592 return Effect.gen(function* () {
593 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-project" }));
594 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
595 expect(harness.createWorktree).not.toHaveBeenCalled();
596 });
597 });
598​
599 it.effect("maps a project read error to operation_failed", () => {
600 const harness = makeHarness({ projectReadFails: true });
601 return Effect.gen(function* () {
602 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/project-error" }));
603 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
604 expect(harness.createWorktree).not.toHaveBeenCalled();
605 });
606 });
607​
608 it.effect("fails when the project workspace is not a git repository", () => {
609 const harness = makeHarness({ notARepo: true });
610 return Effect.gen(function* () {
611 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-repo" }));
612 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
613 expect(harness.createWorktree).not.toHaveBeenCalled();
614 });
615 });
616​
617 it.effect("rejects an existing branch with an actionable error naming its checkout", () => {
618 const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" });
619 return Effect.gen(function* () {
620 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken" }));
621 if (!Exit.isFailure(exit)) {
622 return expect.fail("expected a failure exit");
623 }
624 const reason = exit.cause.reasons[0];
625 expect(reason?._tag).toBe("Fail");
626 const error = (reason as { readonly error: { code: string; message: string } }).error;
627 expect(error.code).toBe("invalid_request");
628 expect(error.message).toContain("feature/taken");
629 expect(error.message).toContain("already exists");
630 expect(error.message).toContain("/elsewhere/checkout");
631 expect(harness.createWorktree).not.toHaveBeenCalled();
632 expect(harness.fetchRemote).not.toHaveBeenCalled();
633 });
634 });
635​
636 it.effect("rejects an existing branch that is not checked out anywhere", () => {
637 const harness = makeHarness({ existingBranchWorktreePath: null });
638 return Effect.gen(function* () {
639 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken-idle" }));
640 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
641 expect(harness.createWorktree).not.toHaveBeenCalled();
642 });
643 });
644​
645 it.effect("does not trip the pre-flight on similarly named branches", () => {
646 const harness = makeHarness({ existingBranchWorktreePath: null });
647 return Effect.gen(function* () {
648 // "feature/taken" exists in the mock branch list; "feature/take" does
649 // not, and a substring-based check would wrongly match it.
650 const result = yield* runHandoff(harness, { branch: "feature/take" });
651 expect(result.branch).toBe("feature/take");
652 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
653 });
654 });
655​
656 it.effect("rejects a non-repository workspace even when baseRef is explicit", () => {
657 const harness = makeHarness({ notARepo: true });
658 return Effect.gen(function* () {
659 const exit = yield* Effect.exit(
660 runHandoff(harness, { branch: "feature/no-repo-baseref", baseRef: "dev" }),
661 );
662 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
663 expect(harness.createWorktree).not.toHaveBeenCalled();
664 });
665 });
666​
667 it.effect("propagates an interrupted dispatch without rolling back the worktree", () => {
668 const harness = makeHarness({ dispatchInterrupts: true });
669 return Effect.gen(function* () {
670 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-int" }));
671 if (!Exit.isFailure(exit)) {
672 return expect.fail("expected a failure exit");
673 }
674 // Whether the binding committed is unknown on interruption, so the
675 // worktree must not be force-deleted and no typed failure is invented.
676 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
677 expect(harness.removeWorktree).not.toHaveBeenCalled();
678 });
679 });
680​
681 it.effect("maps a worktree creation failure to operation_failed", () => {
682 const harness = makeHarness({ createWorktreeFails: true });
683 return Effect.gen(function* () {
684 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/create-fails" }));
685 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
686 expect(harness.dispatch).not.toHaveBeenCalled();
687 expect(harness.removeWorktree).not.toHaveBeenCalled();
688 });
689 });
690​
691 it.effect("maps an origin fetch failure to operation_failed", () => {
692 const harness = makeHarness({ fetchRemoteFails: true });
693 return Effect.gen(function* () {
694 const exit = yield* Effect.exit(
695 runHandoff(harness, { branch: "feature/fetch-fails", startFromOrigin: true }),
696 );
697 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
698 expect(harness.createWorktree).not.toHaveBeenCalled();
699 });
700 });
701​
702 it.effect("maps a remote-tracking resolve failure to operation_failed", () => {
703 const harness = makeHarness({ resolveRemoteFails: true });
704 return Effect.gen(function* () {
705 const exit = yield* Effect.exit(
706 runHandoff(harness, { branch: "feature/resolve-fails", startFromOrigin: true }),
707 );
708 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
709 expect(harness.createWorktree).not.toHaveBeenCalled();
710 });
711 });
712​
713 it.effect("removes the created worktree when the thread update dies with a defect", () => {
714 const harness = makeHarness({ dispatchDies: true });
715 return Effect.gen(function* () {
716 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-defect" }));
717 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
718 expect(harness.removeWorktree).toHaveBeenCalledWith({
719 cwd: workspaceRoot,
720 path: "/worktrees/project/feature/dispatch-defect",
721 force: true,
722 });
723 });
724 });
725​
726 it.effect("re-checks attachment after creating the worktree and backs out on a race", () => {
727 const harness = makeHarness({ threadAttachedOnRecheck: true });
728 return Effect.gen(function* () {
729 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/raced" }));
730 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
731 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
732 // The freshly created worktree must not be left orphaned.
733 expect(harness.removeWorktree).toHaveBeenCalledWith({
734 cwd: workspaceRoot,
735 path: "/worktrees/project/feature/raced",
736 force: true,
737 });
738 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
739 cwd: workspaceRoot,
740 refName: "feature/raced",
741 force: true,
742 });
743 expect(harness.dispatch).not.toHaveBeenCalled();
744 });
745 });
746​
747 it.effect("removes the created worktree when the recheck read fails", () => {
748 const harness = makeHarness({ threadReadFailsOnRecheck: true });
749 return Effect.gen(function* () {
750 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/recheck-fails" }));
751 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
752 expect(harness.removeWorktree).toHaveBeenCalledWith({
753 cwd: workspaceRoot,
754 path: "/worktrees/project/feature/recheck-fails",
755 force: true,
756 });
757 expect(harness.dispatch).not.toHaveBeenCalled();
758 });
759 });
760​
761 it.effect("backs out when the thread is archived during worktree creation", () => {
762 const harness = makeHarness({ threadArchivedOnRecheck: true });
763 return Effect.gen(function* () {
764 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived-race" }));
765 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
766 expect(harness.dispatch).not.toHaveBeenCalled();
767 // The created worktree must not be left orphaned.
768 expect(harness.removeWorktree).toHaveBeenCalledWith({
769 cwd: workspaceRoot,
770 path: "/worktrees/project/feature/archived-race",
771 force: true,
772 });
773 });
774 });
775​
776 it.effect("rejects a handoff for an archived thread", () => {
777 const harness = makeHarness({ thread: { archivedAt: "2026-01-02T00:00:00.000Z" } });
778 return Effect.gen(function* () {
779 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived" }));
780 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
781 expect(harness.createWorktree).not.toHaveBeenCalled();
782 });
783 });
784​
785 it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
786 Effect.gen(function* () {
787 const gate = yield* Deferred.make<void>();
788 const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
789​
790 // Interrupt arrives while the metadata dispatch is in flight; the
791 // binding-plus-continuation section must run to completion anyway so the
792 // continuation is never lost between the commit and the queue.
793 const fiber = yield* Effect.forkChild(
794 runHandoff(harness, {
795 branch: "feature/interrupted",
796 continuationPrompt: "Keep going in the worktree.",
797 }),
798 );
799 yield* Effect.yieldNow;
800 const interruption = yield* Effect.forkChild(Fiber.interrupt(fiber));
801 yield* Effect.yieldNow;
802 yield* Deferred.succeed(gate, undefined);
803 yield* Fiber.await(fiber);
804 yield* Fiber.join(interruption);
805​
806 expect(harness.dispatch).toHaveBeenCalledTimes(1);
807 expect(harness.sendToThread).toHaveBeenCalledTimes(1);
808 // The setup script must also survive the pending interrupt; otherwise
809 // the continuation run starts in a worktree that was never set up.
810 expect(harness.runForThread).toHaveBeenCalledTimes(1);
811 }),
812 );
813​
814 it.effect("still fails with a typed error when the rollback removal also fails", () => {
815 const harness = makeHarness({ dispatchFails: true, removeWorktreeFails: true });
816 return Effect.gen(function* () {
817 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/rollback-fails" }));
818 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
819 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
820 expect(harness.deleteLocalBranch).not.toHaveBeenCalled();
821 });
822 });
823​
824 it.effect("preserves the typed failure when rollback branch deletion also fails", () => {
825 const harness = makeHarness({ dispatchFails: true, deleteLocalBranchFails: true });
826 return Effect.gen(function* () {
827 const exit = yield* Effect.exit(
828 runHandoff(harness, { branch: "feature/rollback-branch-fails" }),
829 );
830 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
831 expect(harness.removeWorktree).toHaveBeenCalledTimes(1);
832 expect(harness.deleteLocalBranch).toHaveBeenCalledWith({
833 cwd: workspaceRoot,
834 refName: "feature/rollback-branch-fails",
835 force: true,
836 });
837 });
838 });
839​
840 it.effect("accepts a Windows drive path under win32 path semantics", () => {
841 const harness = makeHarness({ pathSemantics: "win32" });
842 return Effect.gen(function* () {
843 const result = yield* runHandoff(harness, {
844 branch: "feature/windows-path",
845 path: "C:\\worktrees\\custom",
846 });
847 expect(result.worktreePath).toBe("C:\\worktrees\\custom");
848 expect(harness.createWorktree).toHaveBeenCalledWith(
849 expect.objectContaining({ path: "C:\\worktrees\\custom" }),
850 );
851 });
852 });
853​
854 it.effect("rejects a Windows drive path under posix path semantics", () => {
855 const harness = makeHarness({ pathSemantics: "posix" });
856 return Effect.gen(function* () {
857 // The schema-level pattern admits drive paths cross-platform; the
858 // runtime check reflects the host the worktree would be created on.
859 const exit = yield* Effect.exit(
860 runHandoff(harness, { branch: "feature/windows-path", path: "C:\\worktrees\\custom" }),
861 );
862 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
863 expect(harness.createWorktree).not.toHaveBeenCalled();
864 });
865 });
866​
867 it.effect("releases the per-thread guard after a failed handoff", () => {
868 const harness = makeHarness({
869 thread: { worktreePath: "/worktrees/project/existing" },
870 });
871 return Effect.gen(function* () {
872 const service = yield* resolveService(harness);
873​
874 const first = yield* Effect.exit(
875 service.handoff(harness.scope, { branch: "feature/guard-1" }),
876 );
877 expectTypedFailure(first, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
878 // A leaked guard would surface as handoff_in_progress here.
879 const second = yield* Effect.exit(
880 service.handoff(harness.scope, { branch: "feature/guard-2" }),
881 );
882 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "already_in_worktree" });
883 });
884 });
885​
886 it.effect("fails when the worktree capability is missing", () => {
887 const harness = makeHarness({ capabilities: new Set(["preview"]) });
888 return Effect.gen(function* () {
889 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-capability" }));
890 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
891 });
892 });
893​
894 it.effect("serializes concurrent handoffs for the same thread", () =>
895 Effect.gen(function* () {
896 const gate = yield* Deferred.make<void>();
897 const harness = makeHarness({ createWorktreeGate: Deferred.await(gate) });
898​
899 const service = yield* resolveService(harness);
900​
901 // First handoff acquires the per-thread guard and blocks on the gate.
902 const first = yield* Effect.forkChild(
903 Effect.exit(service.handoff(harness.scope, { branch: "feature/race-1" })),
904 );
905 yield* Effect.yieldNow;
906​
907 // Second handoff for the same thread must be refused while the first
908 // is still in flight.
909 const second = yield* Effect.exit(
910 service.handoff(harness.scope, { branch: "feature/race-2" }),
911 );
912 expectTypedFailure(second, { _tag: "WorktreeMcpFailure", code: "handoff_in_progress" });
913​
914 yield* Deferred.succeed(gate, undefined);
915 const firstExit = yield* Fiber.join(first);
916 expect(Exit.isSuccess(firstExit)).toBe(true);
917 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
918 }),
919 );
920​
921 it.effect("removes the created worktree when the thread update fails", () => {
922 const harness = makeHarness({ dispatchFails: true });
923 return Effect.gen(function* () {
924 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-fails" }));
925 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
926 expect(harness.createWorktree).toHaveBeenCalledTimes(1);
927 expect(harness.removeWorktree).toHaveBeenCalledWith({
928 cwd: workspaceRoot,
929 path: "/worktrees/project/feature/dispatch-fails",
930 force: true,
931 });
932 });
933 });
934​
935 it.effect("rejects a relative path", () => {
936 const harness = makeHarness();
937 return Effect.gen(function* () {
938 const exit = yield* Effect.exit(
939 runHandoff(harness, { branch: "feature/relative-path", path: "worktrees/nested" }),
940 );
941 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
942 expect(harness.createWorktree).not.toHaveBeenCalled();
943 });
944 });
945​
946 it.effect("fails when baseRef is omitted and HEAD is detached", () => {
947 const harness = makeHarness({ currentBranch: null });
948 return Effect.gen(function* () {
949 const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/detached" }));
950 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" });
951 });
952 });
953​
954 it.effect("reports setup script failure without failing the handoff", () => {
955 const harness = makeHarness({ setupScript: "fails" });
956 return Effect.gen(function* () {
957 const result = yield* runHandoff(harness, { branch: "feature/setup-fails" });
958 expect(result.setupScript.status).toBe("failed");
959 expect(harness.dispatch).toHaveBeenCalled();
960 });
961 });
962​
963 it.effect("reports a setup script defect without failing the handoff", () => {
964 const harness = makeHarness({ setupScript: "dies" });
965 return Effect.gen(function* () {
966 const result = yield* runHandoff(harness, { branch: "feature/setup-dies" });
967 expect(result.setupScript).toEqual({ status: "failed", detail: "setup runner defect" });
968 expect(harness.dispatch).toHaveBeenCalled();
969 });
970 });
971});
972​
973describe("t3_worktree_status", () => {
974 it.effect("reports an unattached thread", () => {
975 const harness = makeHarness({ newWorktreesStartFromOrigin: true });
976 return Effect.gen(function* () {
977 const result = yield* runStatus(harness);
978 expect(result).toEqual({
979 attached: false,
980 worktreePath: null,
981 branch: null,
982 projectWorkspaceRoot: workspaceRoot,
983 defaultStartFromOrigin: true,
984 });
985 });
986 });
987​
988 it.effect("reports an attached thread's worktree and branch", () => {
989 const harness = makeHarness({
990 thread: {
991 worktreePath: "/worktrees/project/existing",
992 branch: "feature/existing",
993 },
994 });
995 return Effect.gen(function* () {
996 const result = yield* runStatus(harness);
997 expect(result).toMatchObject({
998 attached: true,
999 worktreePath: "/worktrees/project/existing",
1000 branch: "feature/existing",
1001 defaultStartFromOrigin: false,
1002 });
1003 });
1004 });
1005​
1006 it.effect("fails when the worktree capability is missing", () => {
1007 const harness = makeHarness({ capabilities: new Set(["preview"]) });
1008 return Effect.gen(function* () {
1009 const exit = yield* Effect.exit(runStatus(harness));
1010 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" });
1011 });
1012 });
1013​
1014 it.effect("fails when the thread does not exist", () => {
1015 const harness = makeHarness({ thread: null });
1016 return Effect.gen(function* () {
1017 const exit = yield* Effect.exit(runStatus(harness));
1018 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" });
1019 });
1020 });
1021​
1022 it.effect("fails when the project does not exist", () => {
1023 const harness = makeHarness({ projectMissing: true });
1024 return Effect.gen(function* () {
1025 const exit = yield* Effect.exit(runStatus(harness));
1026 expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" });
1027 });
1028 });
1029});
1030​
1031describe("WorktreeMcpHandoffInput schema", () => {
1032 const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
1033​
1034 it.effect("accepts POSIX, Windows drive, and UNC absolute paths", () =>
1035 Effect.gen(function* () {
1036 for (const path of ["/abs/posix", "C:\\abs\\drive", "C:/abs/drive", "\\\\host\\share"]) {
1037 const decoded = yield* decode({ branch: "feature/x", path });
1038 expect(decoded.path).toBe(path);
1040 }),
1041 );
1042​
1043 it.effect("rejects relative paths", () =>
1044 Effect.gen(function* () {
1045 for (const path of ["worktrees/nested", "./nested", "../sibling"]) {
1046 const exit = yield* Effect.exit(decode({ branch: "feature/x", path }));
1047 expect(Exit.isFailure(exit), `path '${path}' should be rejected`).toBe(true);
1049 }),
1050 );
1051​
1052 it.effect("rejects a missing or blank branch", () =>
1053 Effect.gen(function* () {
1054 expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true);
1055 expect(Exit.isFailure(yield* Effect.exit(decode({ branch: " " })))).toBe(true);
1056 }),
1057 );
1058​
1059 it.effect("rejects a blank continuationPrompt", () =>
1060 Effect.gen(function* () {
1061 const exit = yield* Effect.exit(decode({ branch: "feature/x", continuationPrompt: " " }));
1062 expect(Exit.isFailure(exit)).toBe(true);
1063 }),
1064 );
1065});