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

WorktreeMcpService.test.ts

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