Open History to see the last commit
1import { existsSync } from "node:fs";
2import path from "node:path";
3
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { it } from "@effect/vitest";
6import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
7import { describe, expect, vi } from "vitest";
8
9import { GitServiceLive } from "./GitService.ts";
10import { GitService, type GitServiceShape } from "../Services/GitService.ts";
11import { GitCoreLive } from "./GitCore.ts";
12import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
13import { GitCommandError } from "../Errors.ts";
14import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
15
16// ── Helpers ──
17
18const GitServiceTestLayer = GitServiceLive.pipe(Layer.provide(NodeServices.layer));
19const GitCoreTestLayer = GitCoreLive.pipe(
20 Layer.provide(GitServiceTestLayer),
21 Layer.provide(NodeServices.layer),
22);
23const TestLayer = Layer.mergeAll(NodeServices.layer, GitServiceTestLayer, GitCoreTestLayer);
24
25function makeTmpDir(
26 prefix = "git-test-",
27): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
28 return Effect.gen(function* () {
29 const fileSystem = yield* FileSystem.FileSystem;
30 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
31 });
32}
33
34function writeTextFile(
35 filePath: string,
36 contents: string,
37): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
38 return Effect.gen(function* () {
39 const fileSystem = yield* FileSystem.FileSystem;
40 yield* fileSystem.writeFileString(filePath, contents);
41 });
42}
43
44/** Run a raw git command for test setup (not under test). */
45function git(
46 cwd: string,
47 args: ReadonlyArray<string>,
48 env?: NodeJS.ProcessEnv,
49): Effect.Effect<string, GitCommandError, GitService> {
50 return Effect.gen(function* () {
51 const gitService = yield* GitService;
52 const result = yield* gitService.execute({
53 operation: "GitCore.test.git",
54 cwd,
55 args,
56 ...(env ? { env } : {}),
57 timeoutMs: 10_000,
58 });
59 return result.stdout.trim();
60 });
61}
62
63function runShellCommand(input: {
64 command: string;
65 cwd: string;
66 timeoutMs?: number;
67 maxOutputBytes?: number;
68}): Effect.Effect<ProcessRunResult, Error> {
69 return Effect.promise(() => {
70 const shellPath =
71 process.platform === "win32"
72 ? (process.env.ComSpec ?? "cmd.exe")
73 : (process.env.SHELL ?? "/bin/sh");
74
75 const args =
76 process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
77
78 return runProcess(shellPath, args, {
79 cwd: input.cwd,
80 timeoutMs: input.timeoutMs ?? 30_000,
81 allowNonZeroExit: true,
82 maxBufferBytes: input.maxOutputBytes ?? 1_000_000,
83 outputMode: "truncate",
84 });
85 });
86}
87
88const makeIsolatedGitCore = (gitService: GitServiceShape) =>
89 Effect.promise(async () => {
90 const gitServiceLayer = Layer.succeed(GitService, gitService);
91 const coreLayer = GitCoreLive.pipe(
92 Layer.provide(gitServiceLayer),
93 Layer.provide(NodeServices.layer),
94 );
95 const core = await Effect.runPromise(Effect.service(GitCore).pipe(Effect.provide(coreLayer)));
96
97 return {
98 status: (input) => core.status(input),
99 statusDetails: (cwd) => core.statusDetails(cwd),
100 prepareCommitContext: (cwd) => core.prepareCommitContext(cwd),
101 commit: (cwd, subject, body) => core.commit(cwd, subject, body),
102 pushCurrentBranch: (cwd, fallbackBranch) => core.pushCurrentBranch(cwd, fallbackBranch),
103 pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd),
104 readRangeContext: (cwd, baseBranch) => core.readRangeContext(cwd, baseBranch),
105 readConfigValue: (cwd, key) => core.readConfigValue(cwd, key),
106 listBranches: (input) => core.listBranches(input),
107 createWorktree: (input) => core.createWorktree(input),
108 removeWorktree: (input) => core.removeWorktree(input),
109 createBranch: (input) => core.createBranch(input),
110 checkoutBranch: (input) => core.checkoutBranch(input),
111 initRepo: (input) => core.initRepo(input),
112 } satisfies GitCoreShape;
113 });
114
115function listGitBranches(input: Parameters<GitCoreShape["listBranches"]>[0]) {
116 return Effect.gen(function* () {
117 const core = yield* GitCore;
118 return yield* core.listBranches(input);
119 });
120}
121
122function initGitRepo(input: Parameters<GitCoreShape["initRepo"]>[0]) {
123 return Effect.gen(function* () {
124 const core = yield* GitCore;
125 return yield* core.initRepo(input);
126 });
127}
128
129function createGitBranch(input: Parameters<GitCoreShape["createBranch"]>[0]) {
130 return Effect.gen(function* () {
131 const core = yield* GitCore;
132 return yield* core.createBranch(input);
133 });
134}
135
136function checkoutGitBranch(input: Parameters<GitCoreShape["checkoutBranch"]>[0]) {
137 return Effect.gen(function* () {
138 const core = yield* GitCore;
139 return yield* core.checkoutBranch(input);
140 });
141}
142
143function createGitWorktree(input: Parameters<GitCoreShape["createWorktree"]>[0]) {
144 return Effect.gen(function* () {
145 const core = yield* GitCore;
146 return yield* core.createWorktree(input);
147 });
148}
149
150function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0]) {
151 return Effect.gen(function* () {
152 const core = yield* GitCore;
153 return yield* core.removeWorktree(input);
154 });
155}
156
157function pullGitBranch({ cwd }: { cwd: string }) {
158 return Effect.gen(function* () {
159 const core = yield* GitCore;
160 return yield* core.pullCurrentBranch(cwd);
161 });
162}
163
164/** Create a repo with an initial commit so branches work. */
165function initRepoWithCommit(
166 cwd: string,
167): Effect.Effect<
168 void,
169 GitCommandError | PlatformError.PlatformError,
170 GitCore | GitService | FileSystem.FileSystem
171> {
172 return Effect.gen(function* () {
173 yield* initGitRepo({ cwd });
174 yield* git(cwd, ["config", "user.email", "test@test.com"]);
175 yield* git(cwd, ["config", "user.name", "Test"]);
176 yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
177 yield* git(cwd, ["add", "."]);
178 yield* git(cwd, ["commit", "-m", "initial commit"]);
179 });
180}
181
182function commitWithDate(
183 cwd: string,
184 fileName: string,
185 fileContents: string,
186 dateIsoString: string,
187 message: string,
188): Effect.Effect<
189 void,
190 GitCommandError | PlatformError.PlatformError,
191 GitService | FileSystem.FileSystem
192> {
193 return Effect.gen(function* () {
194 yield* writeTextFile(path.join(cwd, fileName), fileContents);
195 yield* git(cwd, ["add", fileName]);
196 yield* git(cwd, ["commit", "-m", message], {
197 ...process.env,
198 GIT_AUTHOR_DATE: dateIsoString,
199 GIT_COMMITTER_DATE: dateIsoString,
200 });
201 });
202}
203
204// ── Tests ──
205
206it.layer(TestLayer)("git integration", (it) => {
207 describe("shell process execution", () => {
208 it.effect("caps captured output when maxOutputBytes is exceeded", () =>
209 Effect.gen(function* () {
210 const result = yield* runShellCommand({
211 command: `node -e "process.stdout.write('x'.repeat(2000))"`,
212 cwd: process.cwd(),
213 timeoutMs: 10_000,
214 maxOutputBytes: 128,
215 });
216
217 expect(result.code).toBe(0);
218 expect(result.stdout.length).toBeLessThanOrEqual(128);
219 expect(result.stdoutTruncated || result.stderrTruncated).toBe(true);
220 }),
221 );
222 });
223
224 // ── initGitRepo ──
225
226 describe("initGitRepo", () => {
227 it.effect("creates a valid git repo", () =>
228 Effect.gen(function* () {
229 const tmp = yield* makeTmpDir();
230 yield* initGitRepo({ cwd: tmp });
231 expect(existsSync(path.join(tmp, ".git"))).toBe(true);
232 }),
233 );
234
235 it.effect("listGitBranches reports isRepo: true after init + commit", () =>
236 Effect.gen(function* () {
237 const tmp = yield* makeTmpDir();
238 yield* initRepoWithCommit(tmp);
239 const result = yield* listGitBranches({ cwd: tmp });
240 expect(result.isRepo).toBe(true);
241 expect(result.branches.length).toBeGreaterThanOrEqual(1);
242 }),
243 );
244 });
245
246 // ── listGitBranches ──
247
248 describe("listGitBranches", () => {
249 it.effect("returns isRepo: false for non-git directory", () =>
250 Effect.gen(function* () {
251 const tmp = yield* makeTmpDir();
252 const result = yield* listGitBranches({ cwd: tmp });
253 expect(result.isRepo).toBe(false);
254 expect(result.branches).toEqual([]);
255 }),
256 );
257
258 it.effect("returns the current branch with current: true", () =>
259 Effect.gen(function* () {
260 const tmp = yield* makeTmpDir();
261 yield* initRepoWithCommit(tmp);
262 const result = yield* listGitBranches({ cwd: tmp });
263 const current = result.branches.find((b) => b.current);
264 expect(current).toBeDefined();
265 expect(current!.current).toBe(true);
266 }),
267 );
268
269 it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
270 Effect.gen(function* () {
271 const tmp = yield* makeTmpDir();
272 yield* initRepoWithCommit(tmp);
273 const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
274 (branch) => branch.current,
275 )!.name;
276
277 yield* createGitBranch({ cwd: tmp, branch: "older-branch" });
278 yield* checkoutGitBranch({ cwd: tmp, branch: "older-branch" });
279 yield* commitWithDate(
280 tmp,
281 "older.txt",
282 "older branch change\n",
283 "Thu, 1 Jan 2037 00:00:00 +0000",
284 "older branch change",
285 );
286
287 yield* checkoutGitBranch({ cwd: tmp, branch: initialBranch });
288 yield* createGitBranch({ cwd: tmp, branch: "newer-branch" });
289 yield* checkoutGitBranch({ cwd: tmp, branch: "newer-branch" });
290 yield* commitWithDate(
291 tmp,
292 "newer.txt",
293 "newer branch change\n",
294 "Fri, 1 Jan 2038 00:00:00 +0000",
295 "newer branch change",
296 );
297
298 // Switch away to show current branch is pinned, then remaining branches are recency-sorted.
299 yield* checkoutGitBranch({ cwd: tmp, branch: "older-branch" });
300
301 const result = yield* listGitBranches({ cwd: tmp });
302 expect(result.branches[0]!.name).toBe("older-branch");
303 expect(result.branches[1]!.name).toBe("newer-branch");
304 }),
305 );
306
307 it.effect("keeps default branch right after current branch", () =>
308 Effect.gen(function* () {
309 const tmp = yield* makeTmpDir();
310 const remote = yield* makeTmpDir();
311 yield* initRepoWithCommit(tmp);
312 const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
313 (branch) => branch.current,
314 )!.name;
315
316 yield* git(remote, ["init", "--bare"]);
317 yield* git(tmp, ["remote", "add", "origin", remote]);
318 yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
319 yield* git(tmp, ["remote", "set-head", "origin", defaultBranch]);
320
321 yield* createGitBranch({ cwd: tmp, branch: "current-branch" });
322 yield* checkoutGitBranch({ cwd: tmp, branch: "current-branch" });
323 yield* commitWithDate(
324 tmp,
325 "current.txt",
326 "current change\n",
327 "Thu, 1 Jan 2037 00:00:00 +0000",
328 "current change",
329 );
330
331 yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
332 yield* createGitBranch({ cwd: tmp, branch: "newer-branch" });
333 yield* checkoutGitBranch({ cwd: tmp, branch: "newer-branch" });
334 yield* commitWithDate(
335 tmp,
336 "newer.txt",
337 "newer change\n",
338 "Fri, 1 Jan 2038 00:00:00 +0000",
339 "newer change",
340 );
341
342 yield* checkoutGitBranch({ cwd: tmp, branch: "current-branch" });
343
344 const result = yield* listGitBranches({ cwd: tmp });
345 expect(result.branches[0]!.name).toBe("current-branch");
346 expect(result.branches[1]!.name).toBe(defaultBranch);
347 expect(result.branches[2]!.name).toBe("newer-branch");
348 }),
349 );
350
351 it.effect("lists multiple branches after creating them", () =>
352 Effect.gen(function* () {
353 const tmp = yield* makeTmpDir();
354 yield* initRepoWithCommit(tmp);
355 yield* createGitBranch({ cwd: tmp, branch: "feature-a" });
356 yield* createGitBranch({ cwd: tmp, branch: "feature-b" });
357
358 const result = yield* listGitBranches({ cwd: tmp });
359 const names = result.branches.map((b) => b.name);
360 expect(names).toContain("feature-a");
361 expect(names).toContain("feature-b");
362 }),
363 );
364
365 it.effect("isDefault is false when no remote exists", () =>
366 Effect.gen(function* () {
367 const tmp = yield* makeTmpDir();
368 yield* initRepoWithCommit(tmp);
369 const result = yield* listGitBranches({ cwd: tmp });
370 expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
371 }),
372 );
373 });
374
375 // ── checkoutGitBranch ──
376
377 describe("checkoutGitBranch", () => {
378 it.effect("checks out an existing branch", () =>
379 Effect.gen(function* () {
380 const tmp = yield* makeTmpDir();
381 yield* initRepoWithCommit(tmp);
382 yield* createGitBranch({ cwd: tmp, branch: "feature" });
383
384 yield* checkoutGitBranch({ cwd: tmp, branch: "feature" });
385
386 const result = yield* listGitBranches({ cwd: tmp });
387 const current = result.branches.find((b) => b.current);
388 expect(current!.name).toBe("feature");
389 }),
390 );
391
392 it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
393 Effect.gen(function* () {
394 const remote = yield* makeTmpDir();
395 const source = yield* makeTmpDir();
396 const clone = yield* makeTmpDir();
397 yield* git(remote, ["init", "--bare"]);
398
399 yield* initRepoWithCommit(source);
400 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
401 (branch) => branch.current,
402 )!.name;
403 yield* git(source, ["remote", "add", "origin", remote]);
404 yield* git(source, ["push", "-u", "origin", defaultBranch]);
405
406 const featureBranch = "feature-behind";
407 yield* createGitBranch({ cwd: source, branch: featureBranch });
408 yield* checkoutGitBranch({ cwd: source, branch: featureBranch });
409 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
410 yield* git(source, ["add", "feature.txt"]);
411 yield* git(source, ["commit", "-m", "feature base"]);
412 yield* git(source, ["push", "-u", "origin", featureBranch]);
413 yield* checkoutGitBranch({ cwd: source, branch: defaultBranch });
414
415 yield* git(clone, ["clone", remote, "."]);
416 yield* git(clone, ["config", "user.email", "test@test.com"]);
417 yield* git(clone, ["config", "user.name", "Test"]);
418 yield* git(clone, ["checkout", "-b", featureBranch, "--track", `origin/${featureBranch}`]);
419 yield* writeTextFile(path.join(clone, "feature.txt"), "feature from remote\n");
420 yield* git(clone, ["add", "feature.txt"]);
421 yield* git(clone, ["commit", "-m", "remote feature update"]);
422 yield* git(clone, ["push", "origin", featureBranch]);
423
424 yield* checkoutGitBranch({ cwd: source, branch: featureBranch });
425 const core = yield* GitCore;
426 yield* Effect.promise(() =>
427 vi.waitFor(async () => {
428 const details = await Effect.runPromise(core.statusDetails(source));
429 expect(details.branch).toBe(featureBranch);
430 expect(details.aheadCount).toBe(0);
431 expect(details.behindCount).toBe(1);
432 }),
433 );
434 }),
435 );
436
437 it.effect("keeps checkout successful when upstream refresh fails", () =>
438 Effect.gen(function* () {
439 const remote = yield* makeTmpDir();
440 const source = yield* makeTmpDir();
441 yield* git(remote, ["init", "--bare"]);
442
443 yield* initRepoWithCommit(source);
444 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
445 (branch) => branch.current,
446 )!.name;
447 yield* git(source, ["remote", "add", "origin", remote]);
448 yield* git(source, ["push", "-u", "origin", defaultBranch]);
449
450 const featureBranch = "feature-refresh-failure";
451 yield* git(source, ["branch", featureBranch]);
452 yield* git(source, ["checkout", featureBranch]);
453 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
454 yield* git(source, ["add", "feature.txt"]);
455 yield* git(source, ["commit", "-m", "feature base"]);
456 yield* git(source, ["push", "-u", "origin", featureBranch]);
457 yield* git(source, ["checkout", defaultBranch]);
458
459 const realGitService = yield* GitService;
460 let refreshFetchAttempts = 0;
461 const core = yield* makeIsolatedGitCore({
462 execute: (input) => {
463 if (input.args[0] === "fetch") {
464 refreshFetchAttempts += 1;
465 return Effect.fail(
466 new GitCommandError({
467 operation: "git.test.refreshFailure",
468 command: `git ${input.args.join(" ")}`,
469 cwd: input.cwd,
470 detail: "simulated fetch timeout",
471 }),
472 );
473 }
474 return realGitService.execute(input);
475 },
476 });
477 yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
478 yield* Effect.promise(() =>
479 vi.waitFor(() => {
480 expect(refreshFetchAttempts).toBe(1);
481 }),
482 );
483 expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
484 }),
485 );
486
487 it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
488 Effect.gen(function* () {
489 const remote = yield* makeTmpDir();
490 const source = yield* makeTmpDir();
491 yield* git(remote, ["init", "--bare"]);
492
493 yield* initRepoWithCommit(source);
494 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
495 (branch) => branch.current,
496 )!.name;
497 yield* git(source, ["remote", "add", "origin", remote]);
498 yield* git(source, ["push", "-u", "origin", defaultBranch]);
499
500 const featureBranch = "feature/scoped-fetch";
501 yield* git(source, ["checkout", "-b", featureBranch]);
502 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
503 yield* git(source, ["add", "feature.txt"]);
504 yield* git(source, ["commit", "-m", "feature base"]);
505 yield* git(source, ["push", "-u", "origin", featureBranch]);
506 yield* git(source, ["checkout", defaultBranch]);
507
508 const realGitService = yield* GitService;
509 let fetchArgs: readonly string[] | null = null;
510 const core = yield* makeIsolatedGitCore({
511 execute: (input) => {
512 if (input.args[0] === "fetch") {
513 fetchArgs = [...input.args];
514 return Effect.succeed({ code: 0, stdout: "", stderr: "" });
515 }
516 return realGitService.execute(input);
517 },
518 });
519 yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
520 yield* Effect.promise(() =>
521 vi.waitFor(() => {
522 expect(fetchArgs).not.toBeNull();
523 }),
524 );
525
526 expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
527 expect(fetchArgs).toEqual([
528 "fetch",
529 "--quiet",
530 "--no-tags",
531 "origin",
532 `+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
533 ]);
534 }),
535 );
536
537 it.effect("returns checkout result before background upstream refresh completes", () =>
538 Effect.gen(function* () {
539 const remote = yield* makeTmpDir();
540 const source = yield* makeTmpDir();
541 yield* git(remote, ["init", "--bare"]);
542
543 yield* initRepoWithCommit(source);
544 const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
545 (branch) => branch.current,
546 )!.name;
547 yield* git(source, ["remote", "add", "origin", remote]);
548 yield* git(source, ["push", "-u", "origin", defaultBranch]);
549
550 const featureBranch = "feature/background-refresh";
551 yield* git(source, ["checkout", "-b", featureBranch]);
552 yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
553 yield* git(source, ["add", "feature.txt"]);
554 yield* git(source, ["commit", "-m", "feature base"]);
555 yield* git(source, ["push", "-u", "origin", featureBranch]);
556 yield* git(source, ["checkout", defaultBranch]);
557
558 const realGitService = yield* GitService;
559 let fetchStarted = false;
560 let releaseFetch: () => void = () => undefined;
561 const waitForReleasePromise = new Promise<void>((resolve) => {
562 releaseFetch = resolve;
563 });
564 const core = yield* makeIsolatedGitCore({
565 execute: (input) => {
566 if (input.args[0] === "fetch") {
567 fetchStarted = true;
568 return Effect.promise(() =>
569 waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
570 );
571 }
572 return realGitService.execute(input);
573 },
574 });
575 yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
576 yield* Effect.promise(() =>
577 vi.waitFor(() => {
578 expect(fetchStarted).toBe(true);
579 }),
580 );
581 expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
582 releaseFetch();
583 }),
584 );
585
586 it.effect("throws when branch does not exist", () =>
587 Effect.gen(function* () {
588 const tmp = yield* makeTmpDir();
589 yield* initRepoWithCommit(tmp);
590 const result = yield* Effect.result(checkoutGitBranch({ cwd: tmp, branch: "nonexistent" }));
591 expect(result._tag).toBe("Failure");
592 }),
593 );
594
595 it.effect("throws when checkout would overwrite uncommitted changes", () =>
596 Effect.gen(function* () {
597 const tmp = yield* makeTmpDir();
598 yield* initRepoWithCommit(tmp);
599 yield* createGitBranch({ cwd: tmp, branch: "other" });
600
601 // Create a conflicting change: modify README on current branch
602 yield* writeTextFile(path.join(tmp, "README.md"), "modified\n");
603 yield* git(tmp, ["add", "README.md"]);
604
605 // First, checkout other branch cleanly
606 yield* git(tmp, ["stash"]);
607 yield* checkoutGitBranch({ cwd: tmp, branch: "other" });
608 yield* writeTextFile(path.join(tmp, "README.md"), "other content\n");
609 yield* git(tmp, ["add", "."]);
610 yield* git(tmp, ["commit", "-m", "other change"]);
611
612 // Go back to default branch
613 const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
614 (b) => !b.current,
615 )!.name;
616 yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
617
618 // Make uncommitted changes to the same file
619 yield* writeTextFile(path.join(tmp, "README.md"), "conflicting local\n");
620
621 // Checkout should fail due to uncommitted changes
622 const result = yield* Effect.result(checkoutGitBranch({ cwd: tmp, branch: "other" }));
623 expect(result._tag).toBe("Failure");
624 }),
625 );
626 });
627
628 // ── createGitBranch ──
629
630 describe("createGitBranch", () => {
631 it.effect("creates a new branch visible in listGitBranches", () =>
632 Effect.gen(function* () {
633 const tmp = yield* makeTmpDir();
634 yield* initRepoWithCommit(tmp);
635 yield* createGitBranch({ cwd: tmp, branch: "new-feature" });
636
637 const result = yield* listGitBranches({ cwd: tmp });
638 expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
639 }),
640 );
641
642 it.effect("throws when branch already exists", () =>
643 Effect.gen(function* () {
644 const tmp = yield* makeTmpDir();
645 yield* initRepoWithCommit(tmp);
646 yield* createGitBranch({ cwd: tmp, branch: "dupe" });
647 const result = yield* Effect.result(createGitBranch({ cwd: tmp, branch: "dupe" }));
648 expect(result._tag).toBe("Failure");
649 }),
650 );
651 });
652
653 // ── createGitWorktree + removeGitWorktree ──
654
655 describe("createGitWorktree", () => {
656 it.effect("creates a worktree with a new branch from the base branch", () =>
657 Effect.gen(function* () {
658 const tmp = yield* makeTmpDir();
659 yield* initRepoWithCommit(tmp);
660
661 const wtPath = path.join(tmp, "worktree-out");
662 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
663 (b) => b.current,
664 )!.name;
665
666 const result = yield* createGitWorktree({
667 cwd: tmp,
668 branch: currentBranch,
669 newBranch: "wt-branch",
670 path: wtPath,
671 });
672
673 expect(result.worktree.path).toBe(wtPath);
674 expect(result.worktree.branch).toBe("wt-branch");
675 expect(existsSync(wtPath)).toBe(true);
676 expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
677
678 // Clean up worktree before tmp dir disposal
679 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
680 }),
681 );
682
683 it.effect("worktree has the new branch checked out", () =>
684 Effect.gen(function* () {
685 const tmp = yield* makeTmpDir();
686 yield* initRepoWithCommit(tmp);
687
688 const wtPath = path.join(tmp, "wt-check-dir");
689 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
690 (b) => b.current,
691 )!.name;
692
693 yield* createGitWorktree({
694 cwd: tmp,
695 branch: currentBranch,
696 newBranch: "wt-check",
697 path: wtPath,
698 });
699
700 // Verify the worktree is on the new branch
701 const branchOutput = yield* git(wtPath, ["branch", "--show-current"]);
702 expect(branchOutput).toBe("wt-check");
703
704 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
705 }),
706 );
707
708 it.effect("throws when new branch name already exists", () =>
709 Effect.gen(function* () {
710 const tmp = yield* makeTmpDir();
711 yield* initRepoWithCommit(tmp);
712 yield* createGitBranch({ cwd: tmp, branch: "existing" });
713
714 const wtPath = path.join(tmp, "wt-conflict");
715 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
716 (b) => b.current,
717 )!.name;
718
719 const result = yield* Effect.result(
720 createGitWorktree({
721 cwd: tmp,
722 branch: currentBranch,
723 newBranch: "existing",
724 path: wtPath,
725 }),
726 );
727 expect(result._tag).toBe("Failure");
728 }),
729 );
730
731 it.effect("listGitBranches from worktree cwd reports worktree branch as current", () =>
732 Effect.gen(function* () {
733 const tmp = yield* makeTmpDir();
734 yield* initRepoWithCommit(tmp);
735
736 const wtPath = path.join(tmp, "wt-list-dir");
737 const mainBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
738 (b) => b.current,
739 )!.name;
740
741 yield* createGitWorktree({
742 cwd: tmp,
743 branch: mainBranch,
744 newBranch: "wt-list",
745 path: wtPath,
746 });
747
748 // listGitBranches from the worktree should show wt-list as current
749 const wtBranches = yield* listGitBranches({ cwd: wtPath });
750 expect(wtBranches.isRepo).toBe(true);
751 const wtCurrent = wtBranches.branches.find((b) => b.current);
752 expect(wtCurrent!.name).toBe("wt-list");
753
754 // Main repo should still show the original branch as current
755 const mainBranches = yield* listGitBranches({ cwd: tmp });
756 const mainCurrent = mainBranches.branches.find((b) => b.current);
757 expect(mainCurrent!.name).toBe(mainBranch);
758
759 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
760 }),
761 );
762
763 it.effect("removeGitWorktree cleans up the worktree", () =>
764 Effect.gen(function* () {
765 const tmp = yield* makeTmpDir();
766 yield* initRepoWithCommit(tmp);
767
768 const wtPath = path.join(tmp, "wt-remove-dir");
769 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
770 (b) => b.current,
771 )!.name;
772
773 yield* createGitWorktree({
774 cwd: tmp,
775 branch: currentBranch,
776 newBranch: "wt-remove",
777 path: wtPath,
778 });
779 expect(existsSync(wtPath)).toBe(true);
780
781 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
782 expect(existsSync(wtPath)).toBe(false);
783 }),
784 );
785
786 it.effect("removeGitWorktree force removes a dirty worktree", () =>
787 Effect.gen(function* () {
788 const tmp = yield* makeTmpDir();
789 yield* initRepoWithCommit(tmp);
790
791 const wtPath = path.join(tmp, "wt-dirty-dir");
792 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
793 (b) => b.current,
794 )!.name;
795
796 yield* createGitWorktree({
797 cwd: tmp,
798 branch: currentBranch,
799 newBranch: "wt-dirty",
800 path: wtPath,
801 });
802 expect(existsSync(wtPath)).toBe(true);
803
804 yield* writeTextFile(path.join(wtPath, "README.md"), "dirty change\n");
805
806 const failedRemove = yield* Effect.result(removeGitWorktree({ cwd: tmp, path: wtPath }));
807 expect(failedRemove._tag).toBe("Failure");
808 expect(existsSync(wtPath)).toBe(true);
809
810 yield* removeGitWorktree({ cwd: tmp, path: wtPath, force: true });
811 expect(existsSync(wtPath)).toBe(false);
812 }),
813 );
814 });
815
816 // ── Full flow: local branch checkout ──
817
818 describe("full flow: local branch checkout", () => {
819 it.effect("init → commit → create branch → checkout → verify current", () =>
820 Effect.gen(function* () {
821 const tmp = yield* makeTmpDir();
822 yield* initRepoWithCommit(tmp);
823 yield* createGitBranch({ cwd: tmp, branch: "feature-login" });
824 yield* checkoutGitBranch({ cwd: tmp, branch: "feature-login" });
825
826 const result = yield* listGitBranches({ cwd: tmp });
827 const current = result.branches.find((b) => b.current);
828 expect(current!.name).toBe("feature-login");
829 }),
830 );
831 });
832
833 // ── Full flow: worktree creation from base branch ──
834
835 describe("full flow: worktree creation", () => {
836 it.effect("creates worktree with new branch from current branch", () =>
837 Effect.gen(function* () {
838 const tmp = yield* makeTmpDir();
839 yield* initRepoWithCommit(tmp);
840
841 const currentBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
842 (b) => b.current,
843 )!.name;
844
845 const wtPath = path.join(tmp, "my-worktree");
846 const result = yield* createGitWorktree({
847 cwd: tmp,
848 branch: currentBranch,
849 newBranch: "feature-wt",
850 path: wtPath,
851 });
852
853 // Worktree exists
854 expect(existsSync(result.worktree.path)).toBe(true);
855
856 // Main repo still on original branch
857 const mainBranches = yield* listGitBranches({ cwd: tmp });
858 const mainCurrent = mainBranches.branches.find((b) => b.current);
859 expect(mainCurrent!.name).toBe(currentBranch);
860
861 // Worktree is on the new branch
862 const wtBranch = yield* git(wtPath, ["branch", "--show-current"]);
863 expect(wtBranch).toBe("feature-wt");
864
865 yield* removeGitWorktree({ cwd: tmp, path: wtPath });
866 }),
867 );
868 });
869
870 // ── Full flow: thread switching simulation ──
871
872 describe("full flow: thread switching (checkout toggling)", () => {
873 it.effect("checkout a → checkout b → checkout a → current matches", () =>
874 Effect.gen(function* () {
875 const tmp = yield* makeTmpDir();
876 yield* initRepoWithCommit(tmp);
877 yield* createGitBranch({ cwd: tmp, branch: "branch-a" });
878 yield* createGitBranch({ cwd: tmp, branch: "branch-b" });
879
880 // Simulate switching to thread A's branch
881 yield* checkoutGitBranch({ cwd: tmp, branch: "branch-a" });
882 let branches = yield* listGitBranches({ cwd: tmp });
883 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
884
885 // Simulate switching to thread B's branch
886 yield* checkoutGitBranch({ cwd: tmp, branch: "branch-b" });
887 branches = yield* listGitBranches({ cwd: tmp });
888 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b");
889
890 // Switch back to thread A
891 yield* checkoutGitBranch({ cwd: tmp, branch: "branch-a" });
892 branches = yield* listGitBranches({ cwd: tmp });
893 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
894 }),
895 );
896 });
897
898 // ── Full flow: checkout conflict ──
899
900 describe("full flow: checkout conflict", () => {
901 it.effect("uncommitted changes prevent checkout to a diverged branch", () =>
902 Effect.gen(function* () {
903 const tmp = yield* makeTmpDir();
904 yield* initRepoWithCommit(tmp);
905 yield* createGitBranch({ cwd: tmp, branch: "diverged" });
906
907 // Make diverged branch have different file content
908 yield* checkoutGitBranch({ cwd: tmp, branch: "diverged" });
909 yield* writeTextFile(path.join(tmp, "README.md"), "diverged content\n");
910 yield* git(tmp, ["add", "."]);
911 yield* git(tmp, ["commit", "-m", "diverge"]);
912
913 // Actually, let's just get back to the initial branch explicitly
914 const allBranches = yield* listGitBranches({ cwd: tmp });
915 const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name;
916 yield* checkoutGitBranch({ cwd: tmp, branch: initialBranch });
917
918 // Make local uncommitted changes to the same file
919 yield* writeTextFile(path.join(tmp, "README.md"), "local uncommitted\n");
920
921 // Attempt checkout should fail
922 const failedCheckout = yield* Effect.result(
923 checkoutGitBranch({ cwd: tmp, branch: "diverged" }),
924 );
925 expect(failedCheckout._tag).toBe("Failure");
926
927 // Current branch should still be the initial one
928 const result = yield* listGitBranches({ cwd: tmp });
929 expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
930 }),
931 );
932 });
933
934 describe("GitCore", () => {
935 it.effect("supports branch lifecycle operations through the service API", () =>
936 Effect.gen(function* () {
937 const tmp = yield* makeTmpDir();
938 const core = yield* GitCore;
939
940 yield* core.initRepo({ cwd: tmp });
941 yield* git(tmp, ["config", "user.email", "test@test.com"]);
942 yield* git(tmp, ["config", "user.name", "Test"]);
943 yield* writeTextFile(path.join(tmp, "README.md"), "# test\n");
944 yield* git(tmp, ["add", "."]);
945 yield* git(tmp, ["commit", "-m", "initial commit"]);
946
947 yield* core.createBranch({ cwd: tmp, branch: "feature/service-api" });
948 yield* core.checkoutBranch({ cwd: tmp, branch: "feature/service-api" });
949 const branches = yield* core.listBranches({ cwd: tmp });
950
951 expect(branches.isRepo).toBe(true);
952 expect(
953 branches.branches.find((branch: { current: boolean; name: string }) => branch.current)
954 ?.name,
955 ).toBe("feature/service-api");
956 }),
957 );
958
959 it.effect("reports status details and dirty state", () =>
960 Effect.gen(function* () {
961 const tmp = yield* makeTmpDir();
962 yield* initRepoWithCommit(tmp);
963 const core = yield* GitCore;
964
965 const clean = yield* core.status({ cwd: tmp });
966 expect(clean.hasWorkingTreeChanges).toBe(false);
967 expect(clean.branch).toBeTruthy();
968
969 yield* writeTextFile(path.join(tmp, "README.md"), "updated\n");
970 const dirty = yield* core.statusDetails(tmp);
971 expect(dirty.hasWorkingTreeChanges).toBe(true);
972 }),
973 );
974
975 it.effect("includes command context when worktree removal fails", () =>
976 Effect.gen(function* () {
977 const tmp = yield* makeTmpDir();
978 yield* initRepoWithCommit(tmp);
979 const core = yield* GitCore;
980 const missingWorktreePath = path.join(tmp, "missing-worktree");
981
982 const removeResult = yield* Effect.result(
983 core.removeWorktree({ cwd: tmp, path: missingWorktreePath }),
984 );
985 expect(removeResult._tag).toBe("Failure");
986 if (removeResult._tag !== "Failure") {
987 return;
988 }
989 const message = removeResult.failure.message;
990 expect(message).toContain("git worktree remove");
991 expect(message).toContain(`cwd: ${tmp}`);
992 expect(message).toContain(missingWorktreePath);
993 }),
994 );
995
996 it.effect(
997 "refreshes upstream before statusDetails so behind count reflects remote updates",
998 () =>
999 Effect.gen(function* () {
1000 const remote = yield* makeTmpDir();
1001 const source = yield* makeTmpDir();
1002 const clone = yield* makeTmpDir();
1003 yield* git(remote, ["init", "--bare"]);
1004
1005 yield* initRepoWithCommit(source);
1006 const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
1007 (branch) => branch.current,
1008 )!.name;
1009 yield* git(source, ["remote", "add", "origin", remote]);
1010 yield* git(source, ["push", "-u", "origin", initialBranch]);
1011
1012 yield* git(clone, ["clone", remote, "."]);
1013 yield* git(clone, ["config", "user.email", "test@test.com"]);
1014 yield* git(clone, ["config", "user.name", "Test"]);
1015 yield* git(clone, [
1016 "checkout",
1017 "-B",
1018 initialBranch,
1019 "--track",
1020 `origin/${initialBranch}`,
1021 ]);
1022 yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
1023 yield* git(clone, ["add", "CHANGELOG.md"]);
1024 yield* git(clone, ["commit", "-m", "remote update"]);
1025 yield* git(clone, ["push", "origin", initialBranch]);
1026
1027 const core = yield* GitCore;
1028 const details = yield* core.statusDetails(source);
1029 expect(details.branch).toBe(initialBranch);
1030 expect(details.aheadCount).toBe(0);
1031 expect(details.behindCount).toBe(1);
1032 }),
1033 );
1034
1035 it.effect("prepares commit context by auto-staging and creates commit", () =>
1036 Effect.gen(function* () {
1037 const tmp = yield* makeTmpDir();
1038 yield* initRepoWithCommit(tmp);
1039 const core = yield* GitCore;
1040
1041 yield* writeTextFile(path.join(tmp, "README.md"), "new content\n");
1042 const context = yield* core.prepareCommitContext(tmp);
1043 expect(context).not.toBeNull();
1044 expect(context!.stagedSummary.length).toBeGreaterThan(0);
1045 expect(context!.stagedPatch.length).toBeGreaterThan(0);
1046
1047 const created = yield* core.commit(tmp, "Add README update", "- include updated content");
1048 expect(created.commitSha.length).toBeGreaterThan(0);
1049 expect(yield* git(tmp, ["log", "-1", "--pretty=%s"])).toBe("Add README update");
1050 }),
1051 );
1052
1053 it.effect("pushes with upstream setup and then skips when up to date", () =>
1054 Effect.gen(function* () {
1055 const tmp = yield* makeTmpDir();
1056 const remote = yield* makeTmpDir();
1057 yield* initRepoWithCommit(tmp);
1058 yield* git(remote, ["init", "--bare"]);
1059 yield* git(tmp, ["remote", "add", "origin", remote]);
1060 yield* createGitBranch({ cwd: tmp, branch: "feature/core-push" });
1061 yield* checkoutGitBranch({ cwd: tmp, branch: "feature/core-push" });
1062
1063 yield* writeTextFile(path.join(tmp, "feature.txt"), "push me\n");
1064 const core = yield* GitCore;
1065 const context = yield* core.prepareCommitContext(tmp);
1066 expect(context).not.toBeNull();
1067 yield* core.commit(tmp, "Add feature file", "");
1068
1069 const pushed = yield* core.pushCurrentBranch(tmp, null);
1070 expect(pushed.status).toBe("pushed");
1071 expect(pushed.setUpstream).toBe(true);
1072 expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
1073 "origin/feature/core-push",
1074 );
1075
1076 const skipped = yield* core.pushCurrentBranch(tmp, null);
1077 expect(skipped.status).toBe("skipped_up_to_date");
1078 }),
1079 );
1080
1081 it.effect("pulls behind branch and then reports up-to-date", () =>
1082 Effect.gen(function* () {
1083 const remote = yield* makeTmpDir();
1084 const source = yield* makeTmpDir();
1085 const clone = yield* makeTmpDir();
1086 yield* git(remote, ["init", "--bare"]);
1087
1088 yield* initRepoWithCommit(source);
1089 const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
1090 (branch) => branch.current,
1091 )!.name;
1092 yield* git(source, ["remote", "add", "origin", remote]);
1093 yield* git(source, ["push", "-u", "origin", initialBranch]);
1094
1095 yield* git(clone, ["clone", remote, "."]);
1096 yield* git(clone, ["config", "user.email", "test@test.com"]);
1097 yield* git(clone, ["config", "user.name", "Test"]);
1098 yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
1099 yield* git(clone, ["add", "CHANGELOG.md"]);
1100 yield* git(clone, ["commit", "-m", "remote update"]);
1101 yield* git(clone, ["push", "origin", initialBranch]);
1102
1103 const core = yield* GitCore;
1104 const pulled = yield* core.pullCurrentBranch(source);
1105 expect(pulled.status).toBe("pulled");
1106 expect((yield* core.statusDetails(source)).behindCount).toBe(0);
1107
1108 const skipped = yield* core.pullCurrentBranch(source);
1109 expect(skipped.status).toBe("skipped_up_to_date");
1110 }),
1111 );
1112
1113 it.effect("top-level pullGitBranch rejects when no upstream exists", () =>
1114 Effect.gen(function* () {
1115 const tmp = yield* makeTmpDir();
1116 yield* initRepoWithCommit(tmp);
1117 const result = yield* Effect.result(pullGitBranch({ cwd: tmp }));
1118 expect(result._tag).toBe("Failure");
1119 if (result._tag === "Failure") {
1120 expect(result.failure.message.toLowerCase()).toContain("no upstream");
1121 }
1122 }),
1123 );
1124
1125 it.effect("lists branches when recency lookup fails", () =>
1126 Effect.gen(function* () {
1127 const tmp = yield* makeTmpDir();
1128 yield* initRepoWithCommit(tmp);
1129 const realGitService = yield* GitService;
1130 let didFailRecency = false;
1131 const core = yield* makeIsolatedGitCore({
1132 execute: (input) => {
1133 if (!didFailRecency && input.args[0] === "for-each-ref") {
1134 didFailRecency = true;
1135 return Effect.fail(
1136 new GitCommandError({
1137 operation: "git.test.listBranchesRecency",
1138 command: `git ${input.args.join(" ")}`,
1139 cwd: input.cwd,
1140 detail: "timeout",
1141 }),
1142 );
1143 }
1144 return realGitService.execute(input);
1145 },
1146 });
1147
1148 const result = yield* core.listBranches({ cwd: tmp });
1149
1150 expect(result.isRepo).toBe(true);
1151 expect(result.branches.length).toBeGreaterThan(0);
1152 expect(result.branches[0]?.current).toBe(true);
1153 expect(didFailRecency).toBe(true);
1154 }),
1155 );
1156 });
1157});