Open History to see the last commit
1import { existsSync } from "node:fs";
2import { mkdtemp, rm, writeFile } from "node:fs/promises";
3import { tmpdir } from "node:os";
4import path from "node:path";
5import { describe, expect, it, vi } from "vitest";
6
7import {
8 GitCoreService,
9 checkoutGitBranch,
10 createGitBranch,
11 createGitWorktree,
12 initGitRepo,
13 listGitBranches,
14 pullGitBranch,
15 removeGitWorktree,
16 runTerminalCommand,
17} from "./git";
18
19// ── Helpers ──
20
21/** Run a raw git command for test setup (not under test). */
22async function git(cwd: string, command: string): Promise<string> {
23 const result = await runTerminalCommand({
24 command: `git ${command}`,
25 cwd,
26 timeoutMs: 10_000,
27 });
28 if (result.code !== 0) {
29 throw new Error(`git ${command} failed: ${result.stderr}`);
30 }
31 return result.stdout.trim();
32}
33
34/** Create a disposable temp directory that cleans up automatically. */
35async function makeTmpDir() {
36 const dir = await mkdtemp(path.join(tmpdir(), "git-test-"));
37 return {
38 path: dir,
39 [Symbol.asyncDispose]: async () => {
40 await rm(dir, { recursive: true, force: true });
41 },
42 };
43}
44
45/** Create a repo with an initial commit so branches work. */
46async function initRepoWithCommit(cwd: string): Promise<void> {
47 await initGitRepo({ cwd });
48 await git(cwd, "config user.email 'test@test.com'");
49 await git(cwd, "config user.name 'Test'");
50 await writeFile(path.join(cwd, "README.md"), "# test\n");
51 await git(cwd, "add .");
52 await git(cwd, "commit -m 'initial commit'");
53}
54
55async function commitWithDate(
56 cwd: string,
57 fileName: string,
58 fileContents: string,
59 dateIsoString: string,
60 message: string,
61): Promise<void> {
62 await writeFile(path.join(cwd, fileName), fileContents);
63 await git(cwd, `add ${fileName}`);
64 const commitResult = await runTerminalCommand({
65 command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
66 cwd,
67 timeoutMs: 10_000,
68 });
69 if (commitResult.code !== 0) {
70 throw new Error(`git dated commit failed: ${commitResult.stderr}`);
71 }
72}
73
74// ── Tests ──
75
76describe("git integration", () => {
77 describe("runTerminalCommand", () => {
78 it("caps captured output when maxOutputBytes is exceeded", async () => {
79 const result = await runTerminalCommand({
80 command: `node -e "process.stdout.write('x'.repeat(2000))"`,
81 cwd: process.cwd(),
82 timeoutMs: 10_000,
83 maxOutputBytes: 128,
84 });
85
86 expect(result.code).toBe(0);
87 expect(result.stdout.length).toBeLessThanOrEqual(128);
88 expect(result.stderr).toContain("output truncated");
89 });
90 });
91
92 // ── initGitRepo ──
93
94 describe("initGitRepo", () => {
95 it("creates a valid git repo", async () => {
96 await using tmp = await makeTmpDir();
97 await initGitRepo({ cwd: tmp.path });
98 expect(existsSync(path.join(tmp.path, ".git"))).toBe(true);
99 });
100
101 it("listGitBranches reports isRepo: true after init + commit", async () => {
102 await using tmp = await makeTmpDir();
103 await initRepoWithCommit(tmp.path);
104 const result = await listGitBranches({ cwd: tmp.path });
105 expect(result.isRepo).toBe(true);
106 expect(result.branches.length).toBeGreaterThanOrEqual(1);
107 });
108 });
109
110 // ── listGitBranches ──
111
112 describe("listGitBranches", () => {
113 it("returns isRepo: false for non-git directory", async () => {
114 await using tmp = await makeTmpDir();
115 const result = await listGitBranches({ cwd: tmp.path });
116 expect(result.isRepo).toBe(false);
117 expect(result.branches).toEqual([]);
118 });
119
120 it("returns the current branch with current: true", async () => {
121 await using tmp = await makeTmpDir();
122 await initRepoWithCommit(tmp.path);
123 const result = await listGitBranches({ cwd: tmp.path });
124 const current = result.branches.find((b) => b.current);
125 expect(current).toBeDefined();
126 expect(current!.current).toBe(true);
127 });
128
129 it("keeps current branch first and sorts the remaining branches by recency", async () => {
130 await using tmp = await makeTmpDir();
131 await initRepoWithCommit(tmp.path);
132 const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
133 (branch) => branch.current,
134 )!.name;
135
136 await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
137 await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
138 await commitWithDate(
139 tmp.path,
140 "older.txt",
141 "older branch change\n",
142 "Thu, 1 Jan 2037 00:00:00 +0000",
143 "older branch change",
144 );
145
146 await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
147 await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
148 await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
149 await commitWithDate(
150 tmp.path,
151 "newer.txt",
152 "newer branch change\n",
153 "Fri, 1 Jan 2038 00:00:00 +0000",
154 "newer branch change",
155 );
156
157 // Switch away to show current branch is pinned, then remaining branches are recency-sorted.
158 await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
159
160 const result = await listGitBranches({ cwd: tmp.path });
161 expect(result.branches[0]!.name).toBe("older-branch");
162 expect(result.branches[1]!.name).toBe("newer-branch");
163 });
164
165 it("keeps default branch right after current branch", async () => {
166 await using tmp = await makeTmpDir();
167 await using remote = await makeTmpDir();
168 await initRepoWithCommit(tmp.path);
169 const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
170 (branch) => branch.current,
171 )!.name;
172
173 await git(remote.path, "init --bare");
174 await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
175 await git(tmp.path, `push -u origin ${defaultBranch}`);
176 await git(tmp.path, `remote set-head origin ${defaultBranch}`);
177
178 await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
179 await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
180 await commitWithDate(
181 tmp.path,
182 "current.txt",
183 "current change\n",
184 "Thu, 1 Jan 2037 00:00:00 +0000",
185 "current change",
186 );
187
188 await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
189 await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
190 await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
191 await commitWithDate(
192 tmp.path,
193 "newer.txt",
194 "newer change\n",
195 "Fri, 1 Jan 2038 00:00:00 +0000",
196 "newer change",
197 );
198
199 await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
200
201 const result = await listGitBranches({ cwd: tmp.path });
202 expect(result.branches[0]!.name).toBe("current-branch");
203 expect(result.branches[1]!.name).toBe(defaultBranch);
204 expect(result.branches[2]!.name).toBe("newer-branch");
205 });
206
207 it("lists multiple branches after creating them", async () => {
208 await using tmp = await makeTmpDir();
209 await initRepoWithCommit(tmp.path);
210 await createGitBranch({ cwd: tmp.path, branch: "feature-a" });
211 await createGitBranch({ cwd: tmp.path, branch: "feature-b" });
212
213 const result = await listGitBranches({ cwd: tmp.path });
214 const names = result.branches.map((b) => b.name);
215 expect(names).toContain("feature-a");
216 expect(names).toContain("feature-b");
217 });
218
219 it("isDefault is false when no remote exists", async () => {
220 await using tmp = await makeTmpDir();
221 await initRepoWithCommit(tmp.path);
222 const result = await listGitBranches({ cwd: tmp.path });
223 expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
224 });
225 });
226
227 // ── checkoutGitBranch ──
228
229 describe("checkoutGitBranch", () => {
230 it("checks out an existing branch", async () => {
231 await using tmp = await makeTmpDir();
232 await initRepoWithCommit(tmp.path);
233 await createGitBranch({ cwd: tmp.path, branch: "feature" });
234
235 await checkoutGitBranch({ cwd: tmp.path, branch: "feature" });
236
237 const result = await listGitBranches({ cwd: tmp.path });
238 const current = result.branches.find((b) => b.current);
239 expect(current!.name).toBe("feature");
240 });
241
242 it("refreshes upstream behind count after checkout when remote branch advanced", async () => {
243 await using remote = await makeTmpDir();
244 await using source = await makeTmpDir();
245 await using clone = await makeTmpDir();
246 await git(remote.path, "init --bare");
247
248 await initRepoWithCommit(source.path);
249 const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
250 (branch) => branch.current,
251 )!.name;
252 await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
253 await git(source.path, `push -u origin ${defaultBranch}`);
254
255 const featureBranch = "feature-behind";
256 await createGitBranch({ cwd: source.path, branch: featureBranch });
257 await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
258 await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
259 await git(source.path, "add feature.txt");
260 await git(source.path, "commit -m 'feature base'");
261 await git(source.path, `push -u origin ${featureBranch}`);
262 await checkoutGitBranch({ cwd: source.path, branch: defaultBranch });
263
264 await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
265 await git(clone.path, "config user.email 'test@test.com'");
266 await git(clone.path, "config user.name 'Test'");
267 await git(clone.path, `checkout -b ${featureBranch} --track origin/${featureBranch}`);
268 await writeFile(path.join(clone.path, "feature.txt"), "feature from remote\n");
269 await git(clone.path, "add feature.txt");
270 await git(clone.path, "commit -m 'remote feature update'");
271 await git(clone.path, `push origin ${featureBranch}`);
272
273 await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
274 const core = new GitCoreService();
275 await vi.waitFor(async () => {
276 const details = await core.statusDetails(source.path);
277 expect(details.branch).toBe(featureBranch);
278 expect(details.aheadCount).toBe(0);
279 expect(details.behindCount).toBe(1);
280 });
281 });
282
283 it("keeps checkout successful when upstream refresh fails", async () => {
284 await using remote = await makeTmpDir();
285 await using source = await makeTmpDir();
286 await git(remote.path, "init --bare");
287
288 await initRepoWithCommit(source.path);
289 const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
290 (branch) => branch.current,
291 )!.name;
292 await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
293 await git(source.path, `push -u origin ${defaultBranch}`);
294
295 const featureBranch = "feature-refresh-failure";
296 await git(source.path, `branch ${featureBranch}`);
297 await git(source.path, `checkout ${featureBranch}`);
298 await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
299 await git(source.path, "add feature.txt");
300 await git(source.path, "commit -m 'feature base'");
301 await git(source.path, `push -u origin ${featureBranch}`);
302 await git(source.path, `checkout ${defaultBranch}`);
303
304 class RefreshFailingGitCoreService extends GitCoreService {
305 refreshFetchAttempts = 0;
306
307 override async git(
308 cwd: string,
309 args: readonly string[],
310 allowNonZeroExit = false,
311 ): Promise<void> {
312 if (args[0] === "fetch") {
313 this.refreshFetchAttempts += 1;
314 throw new Error("simulated fetch timeout");
315 }
316 await super.git(cwd, args, allowNonZeroExit);
317 }
318 }
319
320 const core = new RefreshFailingGitCoreService();
321 await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
322 undefined,
323 );
324 await vi.waitFor(() => {
325 expect(core.refreshFetchAttempts).toBe(1);
326 });
327 expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
328 });
329
330 it("refresh fetch is scoped to the checked out branch upstream refspec", async () => {
331 await using remote = await makeTmpDir();
332 await using source = await makeTmpDir();
333 await git(remote.path, "init --bare");
334
335 await initRepoWithCommit(source.path);
336 const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
337 (branch) => branch.current,
338 )!.name;
339 await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
340 await git(source.path, `push -u origin ${defaultBranch}`);
341
342 const featureBranch = "feature/scoped-fetch";
343 await git(source.path, `checkout -b ${featureBranch}`);
344 await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
345 await git(source.path, "add feature.txt");
346 await git(source.path, "commit -m 'feature base'");
347 await git(source.path, `push -u origin ${featureBranch}`);
348 await git(source.path, `checkout ${defaultBranch}`);
349
350 class FetchRecordingGitCoreService extends GitCoreService {
351 fetchArgs: readonly string[] | null = null;
352
353 override async git(
354 cwd: string,
355 args: readonly string[],
356 allowNonZeroExit = false,
357 ): Promise<void> {
358 if (args[0] === "fetch") {
359 this.fetchArgs = args;
360 return;
361 }
362 await super.git(cwd, args, allowNonZeroExit);
363 }
364 }
365
366 const core = new FetchRecordingGitCoreService();
367 await core.checkoutBranch({ cwd: source.path, branch: featureBranch });
368 await vi.waitFor(() => {
369 expect(core.fetchArgs).not.toBeNull();
370 });
371
372 expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
373 expect(core.fetchArgs).toEqual([
374 "fetch",
375 "--quiet",
376 "--no-tags",
377 "origin",
378 `+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
379 ]);
380 });
381
382 it("returns checkout result before background upstream refresh completes", async () => {
383 await using remote = await makeTmpDir();
384 await using source = await makeTmpDir();
385 await git(remote.path, "init --bare");
386
387 await initRepoWithCommit(source.path);
388 const defaultBranch = (await listGitBranches({ cwd: source.path })).branches.find(
389 (branch) => branch.current,
390 )!.name;
391 await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
392 await git(source.path, `push -u origin ${defaultBranch}`);
393
394 const featureBranch = "feature/background-refresh";
395 await git(source.path, `checkout -b ${featureBranch}`);
396 await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
397 await git(source.path, "add feature.txt");
398 await git(source.path, "commit -m 'feature base'");
399 await git(source.path, `push -u origin ${featureBranch}`);
400 await git(source.path, `checkout ${defaultBranch}`);
401
402 class SlowRefreshGitCoreService extends GitCoreService {
403 fetchStarted = false;
404 private readonly waitForReleasePromise: Promise<void>;
405 private releaseWait: () => void = () => undefined;
406
407 constructor() {
408 super();
409 this.waitForReleasePromise = new Promise<void>((resolve) => {
410 this.releaseWait = resolve;
411 });
412 }
413
414 releaseFetch(): void {
415 this.releaseWait();
416 }
417
418 override async git(
419 cwd: string,
420 args: readonly string[],
421 allowNonZeroExit = false,
422 ): Promise<void> {
423 if (args[0] === "fetch") {
424 this.fetchStarted = true;
425 await this.waitForReleasePromise;
426 return;
427 }
428 await super.git(cwd, args, allowNonZeroExit);
429 }
430 }
431
432 const core = new SlowRefreshGitCoreService();
433 await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
434 undefined,
435 );
436 await vi.waitFor(() => {
437 expect(core.fetchStarted).toBe(true);
438 });
439 expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
440 core.releaseFetch();
441 });
442
443 it("throws when branch does not exist", async () => {
444 await using tmp = await makeTmpDir();
445 await initRepoWithCommit(tmp.path);
446 await expect(checkoutGitBranch({ cwd: tmp.path, branch: "nonexistent" })).rejects.toThrow();
447 });
448
449 it("throws when checkout would overwrite uncommitted changes", async () => {
450 await using tmp = await makeTmpDir();
451 await initRepoWithCommit(tmp.path);
452 await createGitBranch({ cwd: tmp.path, branch: "other" });
453
454 // Create a conflicting change: modify README on current branch
455 await writeFile(path.join(tmp.path, "README.md"), "modified\n");
456 await git(tmp.path, "add README.md");
457
458 // First, checkout other branch cleanly
459 await git(tmp.path, "stash");
460 await checkoutGitBranch({ cwd: tmp.path, branch: "other" });
461 await writeFile(path.join(tmp.path, "README.md"), "other content\n");
462 await git(tmp.path, "add .");
463 await git(tmp.path, "commit -m 'other change'");
464
465 // Go back to default branch
466 const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
467 (b) => !b.current,
468 )!.name;
469 await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
470
471 // Make uncommitted changes to the same file
472 await writeFile(path.join(tmp.path, "README.md"), "conflicting local\n");
473
474 // Checkout should fail due to uncommitted changes
475 await expect(checkoutGitBranch({ cwd: tmp.path, branch: "other" })).rejects.toThrow();
476 });
477 });
478
479 // ── createGitBranch ──
480
481 describe("createGitBranch", () => {
482 it("creates a new branch visible in listGitBranches", async () => {
483 await using tmp = await makeTmpDir();
484 await initRepoWithCommit(tmp.path);
485 await createGitBranch({ cwd: tmp.path, branch: "new-feature" });
486
487 const result = await listGitBranches({ cwd: tmp.path });
488 expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
489 });
490
491 it("throws when branch already exists", async () => {
492 await using tmp = await makeTmpDir();
493 await initRepoWithCommit(tmp.path);
494 await createGitBranch({ cwd: tmp.path, branch: "dupe" });
495 await expect(createGitBranch({ cwd: tmp.path, branch: "dupe" })).rejects.toThrow();
496 });
497 });
498
499 // ── createGitWorktree + removeGitWorktree ──
500
501 describe("createGitWorktree", () => {
502 it("creates a worktree with a new branch from the base branch", async () => {
503 await using tmp = await makeTmpDir();
504 await initRepoWithCommit(tmp.path);
505
506 const wtPath = path.join(tmp.path, "worktree-out");
507 const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
508 (b) => b.current,
509 )!.name;
510
511 const result = await createGitWorktree({
512 cwd: tmp.path,
513 branch: currentBranch,
514 newBranch: "wt-branch",
515 path: wtPath,
516 });
517
518 expect(result.worktree.path).toBe(wtPath);
519 expect(result.worktree.branch).toBe("wt-branch");
520 expect(existsSync(wtPath)).toBe(true);
521 expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
522
523 // Clean up worktree before tmp dir disposal
524 await removeGitWorktree({ cwd: tmp.path, path: wtPath });
525 });
526
527 it("worktree has the new branch checked out", async () => {
528 await using tmp = await makeTmpDir();
529 await initRepoWithCommit(tmp.path);
530
531 const wtPath = path.join(tmp.path, "wt-check-dir");
532 const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
533 (b) => b.current,
534 )!.name;
535
536 await createGitWorktree({
537 cwd: tmp.path,
538 branch: currentBranch,
539 newBranch: "wt-check",
540 path: wtPath,
541 });
542
543 // Verify the worktree is on the new branch
544 const branchOutput = await git(wtPath, "branch --show-current");
545 expect(branchOutput).toBe("wt-check");
546
547 await removeGitWorktree({ cwd: tmp.path, path: wtPath });
548 });
549
550 it("throws when new branch name already exists", async () => {
551 await using tmp = await makeTmpDir();
552 await initRepoWithCommit(tmp.path);
553 await createGitBranch({ cwd: tmp.path, branch: "existing" });
554
555 const wtPath = path.join(tmp.path, "wt-conflict");
556 const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
557 (b) => b.current,
558 )!.name;
559
560 await expect(
561 createGitWorktree({
562 cwd: tmp.path,
563 branch: currentBranch,
564 newBranch: "existing",
565 path: wtPath,
566 }),
567 ).rejects.toThrow();
568 });
569
570 it("listGitBranches from worktree cwd reports worktree branch as current", async () => {
571 await using tmp = await makeTmpDir();
572 await initRepoWithCommit(tmp.path);
573
574 const wtPath = path.join(tmp.path, "wt-list-dir");
575 const mainBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
576 (b) => b.current,
577 )!.name;
578
579 await createGitWorktree({
580 cwd: tmp.path,
581 branch: mainBranch,
582 newBranch: "wt-list",
583 path: wtPath,
584 });
585
586 // listGitBranches from the worktree should show wt-list as current
587 const wtBranches = await listGitBranches({ cwd: wtPath });
588 expect(wtBranches.isRepo).toBe(true);
589 const wtCurrent = wtBranches.branches.find((b) => b.current);
590 expect(wtCurrent!.name).toBe("wt-list");
591
592 // Main repo should still show the original branch as current
593 const mainBranches = await listGitBranches({ cwd: tmp.path });
594 const mainCurrent = mainBranches.branches.find((b) => b.current);
595 expect(mainCurrent!.name).toBe(mainBranch);
596
597 await removeGitWorktree({ cwd: tmp.path, path: wtPath });
598 });
599
600 it("removeGitWorktree cleans up the worktree", async () => {
601 await using tmp = await makeTmpDir();
602 await initRepoWithCommit(tmp.path);
603
604 const wtPath = path.join(tmp.path, "wt-remove-dir");
605 const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
606 (b) => b.current,
607 )!.name;
608
609 await createGitWorktree({
610 cwd: tmp.path,
611 branch: currentBranch,
612 newBranch: "wt-remove",
613 path: wtPath,
614 });
615 expect(existsSync(wtPath)).toBe(true);
616
617 await removeGitWorktree({ cwd: tmp.path, path: wtPath });
618 expect(existsSync(wtPath)).toBe(false);
619 });
620 });
621
622 // ── Full flow: local branch checkout ──
623
624 describe("full flow: local branch checkout", () => {
625 it("init → commit → create branch → checkout → verify current", async () => {
626 await using tmp = await makeTmpDir();
627 await initRepoWithCommit(tmp.path);
628 await createGitBranch({ cwd: tmp.path, branch: "feature-login" });
629 await checkoutGitBranch({ cwd: tmp.path, branch: "feature-login" });
630
631 const result = await listGitBranches({ cwd: tmp.path });
632 const current = result.branches.find((b) => b.current);
633 expect(current!.name).toBe("feature-login");
634 });
635 });
636
637 // ── Full flow: worktree creation from base branch ──
638
639 describe("full flow: worktree creation", () => {
640 it("creates worktree with new branch from current branch", async () => {
641 await using tmp = await makeTmpDir();
642 await initRepoWithCommit(tmp.path);
643
644 const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
645 (b) => b.current,
646 )!.name;
647
648 const wtPath = path.join(tmp.path, "my-worktree");
649 const result = await createGitWorktree({
650 cwd: tmp.path,
651 branch: currentBranch,
652 newBranch: "feature-wt",
653 path: wtPath,
654 });
655
656 // Worktree exists
657 expect(existsSync(result.worktree.path)).toBe(true);
658
659 // Main repo still on original branch
660 const mainBranches = await listGitBranches({ cwd: tmp.path });
661 const mainCurrent = mainBranches.branches.find((b) => b.current);
662 expect(mainCurrent!.name).toBe(currentBranch);
663
664 // Worktree is on the new branch
665 const wtBranch = await git(wtPath, "branch --show-current");
666 expect(wtBranch).toBe("feature-wt");
667
668 await removeGitWorktree({ cwd: tmp.path, path: wtPath });
669 });
670 });
671
672 // ── Full flow: thread switching simulation ──
673
674 describe("full flow: thread switching (checkout toggling)", () => {
675 it("checkout a → checkout b → checkout a → current matches", async () => {
676 await using tmp = await makeTmpDir();
677 await initRepoWithCommit(tmp.path);
678 await createGitBranch({ cwd: tmp.path, branch: "branch-a" });
679 await createGitBranch({ cwd: tmp.path, branch: "branch-b" });
680
681 // Simulate switching to thread A's branch
682 await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
683 let branches = await listGitBranches({ cwd: tmp.path });
684 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
685
686 // Simulate switching to thread B's branch
687 await checkoutGitBranch({ cwd: tmp.path, branch: "branch-b" });
688 branches = await listGitBranches({ cwd: tmp.path });
689 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b");
690
691 // Switch back to thread A
692 await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
693 branches = await listGitBranches({ cwd: tmp.path });
694 expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
695 });
696 });
697
698 // ── Full flow: checkout conflict ──
699
700 describe("full flow: checkout conflict", () => {
701 it("uncommitted changes prevent checkout to a diverged branch", async () => {
702 await using tmp = await makeTmpDir();
703 await initRepoWithCommit(tmp.path);
704 await createGitBranch({ cwd: tmp.path, branch: "diverged" });
705
706 // Make diverged branch have different file content
707 await checkoutGitBranch({ cwd: tmp.path, branch: "diverged" });
708 await writeFile(path.join(tmp.path, "README.md"), "diverged content\n");
709 await git(tmp.path, "add .");
710 await git(tmp.path, "commit -m 'diverge'");
711
712 // Actually, let's just get back to the initial branch explicitly
713 const allBranches = await listGitBranches({ cwd: tmp.path });
714 const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name;
715 await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
716
717 // Make local uncommitted changes to the same file
718 await writeFile(path.join(tmp.path, "README.md"), "local uncommitted\n");
719
720 // Attempt checkout should fail
721 await expect(checkoutGitBranch({ cwd: tmp.path, branch: "diverged" })).rejects.toThrow();
722
723 // Current branch should still be the initial one
724 const result = await listGitBranches({ cwd: tmp.path });
725 expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
726 });
727 });
728
729 describe("GitCoreService", () => {
730 it("supports branch lifecycle operations through the service API", async () => {
731 await using tmp = await makeTmpDir();
732 const core = new GitCoreService();
733
734 await core.initRepo({ cwd: tmp.path });
735 await git(tmp.path, "config user.email 'test@test.com'");
736 await git(tmp.path, "config user.name 'Test'");
737 await writeFile(path.join(tmp.path, "README.md"), "# test\n");
738 await git(tmp.path, "add .");
739 await git(tmp.path, "commit -m 'initial commit'");
740
741 await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" });
742 await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" });
743 const branches = await core.listBranches({ cwd: tmp.path });
744
745 expect(branches.isRepo).toBe(true);
746 expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api");
747 });
748
749 it("reports status details and dirty state", async () => {
750 await using tmp = await makeTmpDir();
751 await initRepoWithCommit(tmp.path);
752 const core = new GitCoreService();
753
754 const clean = await core.status({ cwd: tmp.path });
755 expect(clean.hasWorkingTreeChanges).toBe(false);
756 expect(clean.branch).toBeTruthy();
757
758 await writeFile(path.join(tmp.path, "README.md"), "updated\n");
759 const dirty = await core.statusDetails(tmp.path);
760 expect(dirty.hasWorkingTreeChanges).toBe(true);
761 });
762
763 it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
764 await using remote = await makeTmpDir();
765 await using source = await makeTmpDir();
766 await using clone = await makeTmpDir();
767 await git(remote.path, "init --bare");
768
769 await initRepoWithCommit(source.path);
770 const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
771 (branch) => branch.current,
772 )!.name;
773 await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
774 await git(source.path, `push -u origin ${initialBranch}`);
775
776 await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
777 await git(clone.path, "config user.email 'test@test.com'");
778 await git(clone.path, "config user.name 'Test'");
779 await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
780 await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
781 await git(clone.path, "add CHANGELOG.md");
782 await git(clone.path, "commit -m 'remote update'");
783 await git(clone.path, `push origin ${initialBranch}`);
784
785 const core = new GitCoreService();
786 const details = await core.statusDetails(source.path);
787 expect(details.branch).toBe(initialBranch);
788 expect(details.aheadCount).toBe(0);
789 expect(details.behindCount).toBe(1);
790 });
791
792 it("prepares commit context by auto-staging and creates commit", async () => {
793 await using tmp = await makeTmpDir();
794 await initRepoWithCommit(tmp.path);
795 const core = new GitCoreService();
796
797 await writeFile(path.join(tmp.path, "README.md"), "new content\n");
798 const context = await core.prepareCommitContext(tmp.path);
799 expect(context).not.toBeNull();
800 expect(context!.stagedSummary.length).toBeGreaterThan(0);
801 expect(context!.stagedPatch.length).toBeGreaterThan(0);
802
803 const created = await core.commit(tmp.path, "Add README update", "- include updated content");
804 expect(created.commitSha.length).toBeGreaterThan(0);
805 expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
806 });
807
808 it("pushes with upstream setup and then skips when up to date", async () => {
809 await using tmp = await makeTmpDir();
810 await using remote = await makeTmpDir();
811 await initRepoWithCommit(tmp.path);
812 await git(remote.path, "init --bare");
813 await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
814 await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
815 await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
816
817 await writeFile(path.join(tmp.path, "feature.txt"), "push me\n");
818 const core = new GitCoreService();
819 const context = await core.prepareCommitContext(tmp.path);
820 expect(context).not.toBeNull();
821 await core.commit(tmp.path, "Add feature file", "");
822
823 const pushed = await core.pushCurrentBranch(tmp.path, null);
824 expect(pushed.status).toBe("pushed");
825 expect(pushed.setUpstream).toBe(true);
826 expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe(
827 "origin/feature/core-push",
828 );
829
830 const skipped = await core.pushCurrentBranch(tmp.path, null);
831 expect(skipped.status).toBe("skipped_up_to_date");
832 });
833
834 it("pulls behind branch and then reports up-to-date", async () => {
835 await using remote = await makeTmpDir();
836 await using source = await makeTmpDir();
837 await using clone = await makeTmpDir();
838 await git(remote.path, "init --bare");
839
840 await initRepoWithCommit(source.path);
841 const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
842 (branch) => branch.current,
843 )!.name;
844 await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
845 await git(source.path, `push -u origin ${initialBranch}`);
846
847 await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
848 await git(clone.path, "config user.email 'test@test.com'");
849 await git(clone.path, "config user.name 'Test'");
850 await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
851 await git(clone.path, "add CHANGELOG.md");
852 await git(clone.path, "commit -m 'remote update'");
853 await git(clone.path, `push origin ${initialBranch}`);
854
855 const core = new GitCoreService();
856 const pulled = await core.pullCurrentBranch(source.path);
857 expect(pulled.status).toBe("pulled");
858 expect((await core.statusDetails(source.path)).behindCount).toBe(0);
859
860 const skipped = await core.pullCurrentBranch(source.path);
861 expect(skipped.status).toBe("skipped_up_to_date");
862 });
863
864 it("top-level pullGitBranch rejects when no upstream exists", async () => {
865 await using tmp = await makeTmpDir();
866 await initRepoWithCommit(tmp.path);
867 await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
868 });
869
870 it("lists branches when recency lookup fails", async () => {
871 await using tmp = await makeTmpDir();
872 await initRepoWithCommit(tmp.path);
873 const core = new GitCoreService();
874 const recencySpy = vi
875 .spyOn(core as any, "readBranchRecency")
876 .mockRejectedValueOnce(new Error("timeout"));
877
878 const result = await core.listBranches({ cwd: tmp.path });
879
880 expect(result.isRepo).toBe(true);
881 expect(result.branches.length).toBeGreaterThan(0);
882 expect(result.branches[0]?.current).toBe(true);
883 recencySpy.mockRestore();
884 });
885 });
886});