forked from johannesjo/parallel-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.ts
More file actions
1233 lines (1088 loc) · 38.4 KB
/
git.ts
File metadata and controls
1233 lines (1088 loc) · 38.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execFile, spawn } from 'child_process';
import { promisify } from 'util';
import fs from 'fs';
import path from 'path';
import type { BrowserWindow } from 'electron';
const exec = promisify(execFile);
// --- Types ---
/** A file entry from a git diff with status and line counts. */
export interface ChangedFile {
path: string;
lines_added: number;
lines_removed: number;
status: string;
committed: boolean;
}
// --- TTL Caches ---
interface CacheEntry {
value: string;
expiresAt: number;
}
const mainBranchCache = new Map<string, CacheEntry>();
const mergeBaseCache = new Map<string, CacheEntry>();
const MAIN_BRANCH_TTL = 60_000; // 60s
const MERGE_BASE_TTL = 30_000; // 30s
const MAX_BUFFER = 10 * 1024 * 1024; // 10MB
const STDERR_CAP = 4096; // cap for stderr buffers in spawned git processes
// Sweep expired cache entries periodically so stale entries from repos that
// are no longer queried don't accumulate (lazy deletion alone isn't enough).
const CACHE_SWEEP_INTERVAL = 5 * 60_000; // 5 min
setInterval(() => {
const now = Date.now();
for (const [k, v] of mainBranchCache) {
if (v.expiresAt <= now) mainBranchCache.delete(k);
}
for (const [k, v] of mergeBaseCache) {
if (v.expiresAt <= now) mergeBaseCache.delete(k);
}
}, CACHE_SWEEP_INTERVAL).unref();
/** Check if a file is binary by looking for null bytes in the first 8KB (same heuristic as git). */
async function isBinaryFile(filePath: string): Promise<boolean> {
let fd: fs.promises.FileHandle;
try {
fd = await fs.promises.open(filePath, 'r');
} catch {
return true; // unreadable files are safer treated as binary
}
try {
const buf = Buffer.alloc(8000);
const { bytesRead } = await fd.read(buf, 0, 8000, 0);
return buf.subarray(0, bytesRead).includes(0);
} finally {
await fd.close();
}
}
function invalidateMergeBaseCache(): void {
mergeBaseCache.clear();
}
function cacheKey(p: string): string {
return p.replace(/\/+$/, '');
}
// --- Worktree lock serialization ---
const worktreeLocks = new Map<string, Promise<void>>();
function withWorktreeLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
const prev = worktreeLocks.get(key) ?? Promise.resolve();
const next = prev.then(fn, fn);
const voidNext = next.then(
() => {},
() => {},
);
worktreeLocks.set(key, voidNext);
voidNext.then(() => {
if (worktreeLocks.get(key) === voidNext) {
worktreeLocks.delete(key);
}
});
return next;
}
// --- Symlink candidates ---
const SYMLINK_CANDIDATES = [
'.claude',
'.cursor',
'.aider',
'.copilot',
'.codeium',
'.continue',
'.windsurf',
'.env',
'node_modules',
];
/** Entries inside `.claude` that must NOT be symlinked (kept per-worktree). */
const CLAUDE_DIR_EXCLUDE = new Set(['plans', 'settings.local.json']);
// --- Internal helpers ---
async function detectMainBranch(repoRoot: string): Promise<string> {
const key = cacheKey(repoRoot);
const cached = mainBranchCache.get(key);
if (cached) {
if (cached.expiresAt > Date.now()) return cached.value;
mainBranchCache.delete(key);
}
const result = await detectMainBranchUncached(repoRoot);
mainBranchCache.set(key, { value: result, expiresAt: Date.now() + MAIN_BRANCH_TTL });
return result;
}
/** Read the branch name that refs/remotes/origin/HEAD points to, or null. */
async function resolveOriginHead(repoRoot: string): Promise<string | null> {
const prefix = 'refs/remotes/origin/';
try {
const { stdout } = await exec('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], {
cwd: repoRoot,
});
const refname = stdout.trim();
return refname.startsWith(prefix) ? refname.slice(prefix.length) : null;
} catch {
return null;
}
}
/** Check whether the remote-tracking ref origin/<branch> exists locally. */
async function remoteTrackingRefExists(repoRoot: string, branch: string): Promise<boolean> {
try {
await exec('git', ['rev-parse', '--verify', `refs/remotes/origin/${branch}`], {
cwd: repoRoot,
});
return true;
} catch {
return false;
}
}
/** Check whether a local branch ref exists. */
async function localBranchExists(repoRoot: string, branch: string): Promise<boolean> {
try {
await exec('git', ['rev-parse', '--verify', `refs/heads/${branch}`], {
cwd: repoRoot,
});
return true;
} catch {
return false;
}
}
async function detectMainBranchUncached(repoRoot: string): Promise<string> {
// Try remote HEAD reference first
const branch = await resolveOriginHead(repoRoot);
if (branch) {
// Verify the remote-tracking ref exists — refs/remotes/origin/HEAD can go
// stale when the default branch is changed on the remote.
if (await remoteTrackingRefExists(repoRoot, branch)) return branch;
// Stale ref — try refreshing from the remote
try {
await exec('git', ['remote', 'set-head', 'origin', '--auto'], {
cwd: repoRoot,
timeout: 5_000,
});
const refreshed = await resolveOriginHead(repoRoot);
if (refreshed && (await remoteTrackingRefExists(repoRoot, refreshed))) return refreshed;
} catch {
/* no network or no remote — fall through */
}
}
// Check common default branch names (remote-tracking first, then local)
for (const candidate of ['main', 'master']) {
if (await remoteTrackingRefExists(repoRoot, candidate)) return candidate;
}
for (const candidate of ['main', 'master']) {
if (await localBranchExists(repoRoot, candidate)) return candidate;
}
// Empty repo (no commits yet) — use configured default branch or fall back to "main"
try {
const { stdout } = await exec('git', ['config', '--get', 'init.defaultBranch'], {
cwd: repoRoot,
});
const configured = stdout.trim();
if (configured) return configured;
} catch {
/* ignore */
}
return 'main';
}
async function getCurrentBranchName(repoRoot: string): Promise<string> {
const { stdout } = await exec('git', ['symbolic-ref', '--short', 'HEAD'], { cwd: repoRoot });
return stdout.trim();
}
async function detectMergeBase(
repoRoot: string,
head?: string,
baseBranch?: string,
): Promise<string> {
const branch = baseBranch ?? (await detectMainBranch(repoRoot));
const headRef = head ?? 'HEAD';
const key = `${cacheKey(repoRoot)}:${branch}:${headRef}`;
const cached = mergeBaseCache.get(key);
if (cached) {
if (cached.expiresAt > Date.now()) return cached.value;
mergeBaseCache.delete(key);
}
try {
const { stdout } = await exec('git', ['merge-base', branch, headRef], { cwd: repoRoot });
const result = stdout.trim();
if (result) {
mergeBaseCache.set(key, { value: result, expiresAt: Date.now() + MERGE_BASE_TTL });
return result;
}
} catch {
/* branch may not resolve */
}
// Fall back to headRef so callers diff HEAD against itself (empty diff)
// rather than diffing against the branch tip.
return headRef;
}
async function pinHead(worktreePath: string): Promise<string> {
try {
const { stdout } = await exec('git', ['rev-parse', 'HEAD'], { cwd: worktreePath });
return stdout.trim();
} catch {
return 'HEAD';
}
}
async function detectRepoLockKey(p: string): Promise<string> {
const { stdout } = await exec('git', ['rev-parse', '--git-common-dir'], { cwd: p });
const commonDir = stdout.trim();
const commonPath = path.isAbsolute(commonDir) ? commonDir : path.join(p, commonDir);
try {
return await fs.promises.realpath(commonPath);
} catch {
return commonPath;
}
}
function normalizeStatusPath(raw: string): string {
const trimmed = raw.trim();
if (!trimmed) return '';
// Handle rename/copy "old -> new"
const destination = trimmed.split(' -> ').pop()?.trim() ?? trimmed;
return destination.replace(/^"|"$/g, '').replace(/\\(.)/g, '$1');
}
/** Parse combined `git diff --raw --numstat` output into status and numstat maps. */
function parseDiffRawNumstat(output: string): {
statusMap: Map<string, string>;
numstatMap: Map<string, [number, number]>;
} {
const statusMap = new Map<string, string>();
const numstatMap = new Map<string, [number, number]>();
for (const line of output.split('\n')) {
if (line.startsWith(':')) {
// --raw format: ":old_mode new_mode old_hash new_hash status\tpath"
const parts = line.split('\t');
if (parts.length >= 2) {
const statusLetter = parts[0].split(/\s+/).pop()?.charAt(0) ?? 'M';
const rawPath = parts[parts.length - 1];
const p = normalizeStatusPath(rawPath);
if (p) statusMap.set(p, statusLetter);
}
continue;
}
// --numstat format: "added\tremoved\tpath"
const parts = line.split('\t');
if (parts.length >= 3) {
const added = parseInt(parts[0], 10);
const removed = parseInt(parts[1], 10);
if (!isNaN(added) && !isNaN(removed)) {
const rawPath = parts[parts.length - 1];
const p = normalizeStatusPath(rawPath);
if (p) numstatMap.set(p, [added, removed]);
}
}
}
return { statusMap, numstatMap };
}
function parseConflictPath(line: string): string | null {
const trimmed = line.trim();
// Format: "CONFLICT (...): Merge conflict in <path>"
const mergeConflictIdx = trimmed.indexOf('Merge conflict in ');
if (mergeConflictIdx !== -1) {
const p = trimmed.slice(mergeConflictIdx + 'Merge conflict in '.length).trim();
return p || null;
}
if (!trimmed.startsWith('CONFLICT')) return null;
// Format: "CONFLICT (...): path <marker>"
const parenClose = trimmed.indexOf('): ');
if (parenClose === -1) return null;
const afterParen = trimmed.slice(parenClose + 3);
const markers = [' deleted in ', ' modified in ', ' added in ', ' renamed in ', ' changed in '];
let cutoff = Infinity;
for (const m of markers) {
const idx = afterParen.indexOf(m);
if (idx !== -1 && idx < cutoff) cutoff = idx;
}
const candidate = (cutoff === Infinity ? afterParen : afterParen.slice(0, cutoff)).trim();
return candidate || null;
}
async function computeBranchDiffStats(
projectRoot: string,
mainBranch: string,
branchName: string,
): Promise<{ linesAdded: number; linesRemoved: number }> {
const { stdout } = await exec('git', ['diff', '--numstat', `${mainBranch}...${branchName}`], {
cwd: projectRoot,
maxBuffer: MAX_BUFFER,
});
let linesAdded = 0;
let linesRemoved = 0;
for (const line of stdout.split('\n')) {
const parts = line.split('\t');
if (parts.length < 3) continue;
linesAdded += parseInt(parts[0], 10) || 0;
linesRemoved += parseInt(parts[1], 10) || 0;
}
return { linesAdded, linesRemoved };
}
/**
* "Shallow-symlink" a directory: create a real directory at `target` and
* symlink each entry from `source` into it, EXCEPT entries in `exclude`.
*/
function shallowSymlinkDir(source: string, target: string, exclude: Set<string>): void {
fs.mkdirSync(target, { recursive: true });
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(source, { withFileTypes: true });
} catch (err) {
console.warn(`Failed to read directory ${source} for shallow-symlink:`, err);
return;
}
for (const entry of entries) {
if (exclude.has(entry.name)) continue;
const src = path.join(source, entry.name);
const dst = path.join(target, entry.name);
try {
if (!fs.existsSync(dst)) {
fs.symlinkSync(src, dst);
}
} catch (err) {
console.warn(`Failed to symlink ${src} -> ${dst}:`, err);
}
}
}
// --- Public functions (used by tasks.ts and register.ts) ---
export async function createWorktree(
repoRoot: string,
branchName: string,
symlinkDirs: string[],
baseBranch?: string,
forceClean = false,
): Promise<{ path: string; branch: string }> {
const worktreePath = `${repoRoot}/.worktrees/${branchName}`;
if (forceClean) {
// Clean up stale worktree/branch from a previous session that wasn't properly removed
if (fs.existsSync(worktreePath)) {
try {
await exec('git', ['worktree', 'remove', '--force', worktreePath], { cwd: repoRoot });
} catch {
fs.rmSync(worktreePath, { recursive: true, force: true });
}
await exec('git', ['worktree', 'prune'], { cwd: repoRoot }).catch((e) =>
console.warn('git worktree prune failed:', e),
);
}
// Delete stale branch ref if it still exists
try {
await exec('git', ['branch', '-D', branchName], { cwd: repoRoot });
} catch {
// Branch doesn't exist — fine
}
}
// Validate the start-point ref exists before attempting worktree creation
const startRef = baseBranch || 'HEAD';
try {
await exec('git', ['rev-parse', '--verify', startRef], { cwd: repoRoot });
} catch {
const isEmptyRepo = await exec('git', ['rev-list', '-n1', '--all'], { cwd: repoRoot })
.then(({ stdout }) => !stdout.trim())
.catch(() => true);
if (isEmptyRepo) {
throw new Error(
'Cannot create a worktree in a repository with no commits. ' +
'Please make an initial commit first.',
);
}
throw new Error(
`Branch "${startRef}" does not exist. ` +
'Please select a valid base branch or create the branch first.',
);
}
// Create fresh worktree with new branch
const worktreeArgs = ['worktree', 'add', '-b', branchName, worktreePath];
if (baseBranch) worktreeArgs.push(baseBranch);
await exec('git', worktreeArgs, { cwd: repoRoot });
// Symlink selected directories
for (const name of symlinkDirs) {
// Reject names that could escape the worktree directory
if (name.includes('/') || name.includes('\\') || name.includes('..') || name === '.') continue;
const source = path.join(repoRoot, name);
const target = path.join(worktreePath, name);
try {
if (!fs.existsSync(source)) continue;
if (fs.existsSync(target)) continue;
if (name === '.claude') {
// Shallow-symlink: real dir with per-entry symlinks, excluding per-worktree entries
shallowSymlinkDir(source, target, CLAUDE_DIR_EXCLUDE);
} else {
fs.symlinkSync(source, target);
}
} catch (err) {
console.warn(`Failed to symlink directory '${name}' into worktree:`, err);
}
}
return { path: worktreePath, branch: branchName };
}
export async function removeWorktree(
repoRoot: string,
branchName: string,
deleteBranch: boolean,
): Promise<void> {
const worktreePath = `${repoRoot}/.worktrees/${branchName}`;
if (!fs.existsSync(repoRoot)) return;
if (fs.existsSync(worktreePath)) {
try {
await exec('git', ['worktree', 'remove', '--force', worktreePath], { cwd: repoRoot });
} catch {
// Fallback: direct directory removal
fs.rmSync(worktreePath, { recursive: true, force: true });
}
}
// Prune stale worktree entries
try {
await exec('git', ['worktree', 'prune'], { cwd: repoRoot });
} catch {
/* ignore */
}
if (deleteBranch) {
try {
await exec('git', ['branch', '-D', '--', branchName], { cwd: repoRoot });
} catch (e: unknown) {
const msg = String(e);
if (!msg.toLowerCase().includes('not found')) throw e;
}
}
}
// --- IPC command functions ---
export async function getGitIgnoredDirs(projectRoot: string): Promise<string[]> {
const results: string[] = [];
for (const name of SYMLINK_CANDIDATES) {
const dirPath = path.join(projectRoot, name);
try {
await fs.promises.stat(dirPath); // throws if entry doesn't exist
} catch {
continue;
}
try {
await exec('git', ['check-ignore', '-q', name], { cwd: projectRoot });
results.push(name);
} catch {
/* not ignored */
}
}
return results;
}
export async function getMainBranch(projectRoot: string): Promise<string> {
return detectMainBranch(projectRoot);
}
export async function getCurrentBranch(projectRoot: string): Promise<string> {
return getCurrentBranchName(projectRoot);
}
export async function checkoutBranch(projectRoot: string, branchName: string): Promise<void> {
await exec('git', ['checkout', branchName], { cwd: projectRoot });
}
export async function getBranches(projectRoot: string): Promise<string[]> {
const { stdout } = await exec('git', ['branch', '--list', '--format=%(refname:short)'], {
cwd: projectRoot,
});
return stdout
.split('\n')
.map((b) => b.trim())
.filter(Boolean);
}
export async function getChangedFiles(
worktreePath: string,
baseBranch?: string,
): Promise<ChangedFile[]> {
const headHash = await pinHead(worktreePath);
// Diff merge-base → HEAD: one-way diff showing only what the feature branch changed.
const base = await detectMergeBase(worktreePath, headHash, baseBranch).catch(() => headHash);
let diffStr = '';
try {
const { stdout } = await exec('git', ['diff', '--raw', '--numstat', base, headHash], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
});
diffStr = stdout;
} catch {
/* empty */
}
const { statusMap: committedStatusMap, numstatMap: committedNumstatMap } =
parseDiffRawNumstat(diffStr);
// git diff --raw --numstat <headHash> — tracked uncommitted changes (HEAD vs working tree).
// Compares HEAD tree directly to the working tree, so it does not need the index
// write lock and works reliably even while an agent holds it.
// git ls-files --others --exclude-standard — untracked files (no index lock needed).
// Both commands run in parallel since they are independent.
const [uncommittedResult, untrackedResult] = await Promise.all([
exec('git', ['diff', '--raw', '--numstat', headHash], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
}).catch(() => ({ stdout: '' })),
exec('git', ['ls-files', '--others', '--exclude-standard'], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
}).catch(() => ({ stdout: '' })),
]);
const { statusMap: uncommittedStatusMap, numstatMap: uncommittedNumstatMap } =
parseDiffRawNumstat(uncommittedResult.stdout);
const untrackedPaths = new Set<string>();
for (const line of untrackedResult.stdout.split('\n')) {
const p = normalizeStatusPath(line);
if (p) untrackedPaths.add(p);
}
const files: ChangedFile[] = [];
const seen = new Set<string>();
// Committed files from diff base..HEAD
for (const [p, [added, removed]] of committedNumstatMap) {
const status = committedStatusMap.get(p) ?? 'M';
// If also in uncommitted diff, mark as uncommitted (has local changes on top)
const committed =
!uncommittedNumstatMap.has(p) && !uncommittedStatusMap.has(p) && !untrackedPaths.has(p);
seen.add(p);
files.push({ path: p, lines_added: added, lines_removed: removed, status, committed });
}
// Committed binary/special files (in statusMap but not numstatMap)
for (const [p, status] of committedStatusMap) {
if (seen.has(p)) continue;
const committed =
!uncommittedNumstatMap.has(p) && !uncommittedStatusMap.has(p) && !untrackedPaths.has(p);
seen.add(p);
files.push({ path: p, lines_added: 0, lines_removed: 0, status, committed });
}
// Tracked uncommitted files not in committed diff
for (const [p, [added, removed]] of uncommittedNumstatMap) {
if (seen.has(p)) continue;
const status = uncommittedStatusMap.get(p) ?? 'M';
seen.add(p);
files.push({ path: p, lines_added: added, lines_removed: removed, status, committed: false });
}
// Uncommitted binary/special files (in statusMap but not numstatMap)
for (const [p, status] of uncommittedStatusMap) {
if (seen.has(p) || uncommittedNumstatMap.has(p)) continue;
seen.add(p);
files.push({ path: p, lines_added: 0, lines_removed: 0, status, committed: false });
}
// Untracked (new) files: count all lines as added
for (const p of untrackedPaths) {
if (seen.has(p)) continue;
let added = 0;
const fullPath = path.join(worktreePath, p);
try {
const stat = await fs.promises.stat(fullPath);
if (stat.isFile() && stat.size < MAX_BUFFER) {
const content = await fs.promises.readFile(fullPath, 'utf8');
const lines = content.split('\n');
added = content.endsWith('\n') ? lines.length - 1 : lines.length;
}
} catch {
/* ignore */
}
files.push({ path: p, lines_added: added, lines_removed: 0, status: '?', committed: false });
}
files.sort((a, b) => {
if (a.committed !== b.committed) return a.committed ? -1 : 1;
return a.path.localeCompare(b.path);
});
return files;
}
export async function getAllFileDiffs(worktreePath: string, baseBranch?: string): Promise<string> {
const headHash = await pinHead(worktreePath);
// Diff merge-base → working tree: one-way diff showing only feature branch changes
// (including uncommitted edits).
const base = await detectMergeBase(worktreePath, headHash, baseBranch).catch(() => headHash);
let combinedDiff = '';
try {
const { stdout } = await exec('git', ['diff', '-U3', base], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
});
combinedDiff = stdout;
} catch {
/* empty */
}
// Untracked files: build pseudo-diffs
const untrackedParts: string[] = [];
try {
const { stdout } = await exec('git', ['status', '--porcelain'], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
});
for (const line of stdout.split('\n')) {
if (!line.startsWith('??')) continue;
const filePath = normalizeStatusPath(line.slice(3));
if (!filePath) continue;
const fullPath = path.join(worktreePath, filePath);
try {
const stat = await fs.promises.stat(fullPath);
if (!stat.isFile() || stat.size >= MAX_BUFFER) continue;
if (await isBinaryFile(fullPath)) {
untrackedParts.push(
`diff --git a/${filePath} b/${filePath}\nnew file mode 100644\nBinary files /dev/null and b/${filePath} differ\n`,
);
continue;
}
const content = await fs.promises.readFile(fullPath, 'utf8');
const lines = content.split('\n');
const lineCount = content.endsWith('\n') ? lines.length - 1 : lines.length;
const pseudoLines: string[] = [];
pseudoLines.push(`diff --git a/${filePath} b/${filePath}`);
pseudoLines.push('new file mode 100644');
pseudoLines.push('--- /dev/null');
pseudoLines.push(`+++ b/${filePath}`);
pseudoLines.push(`@@ -0,0 +1,${lineCount} @@`);
for (let i = 0; i < lineCount; i++) {
pseudoLines.push(`+${lines[i]}`);
}
untrackedParts.push(pseudoLines.join('\n') + '\n');
} catch {
/* skip unreadable files */
}
}
} catch {
/* empty */
}
const parts = [combinedDiff, untrackedParts.join('')].filter((p) => p.length > 0);
return parts.join('\n');
}
export async function getAllFileDiffsFromBranch(
projectRoot: string,
branchName: string,
baseBranch?: string,
): Promise<string> {
const mainBranch = baseBranch ?? (await detectMainBranch(projectRoot));
try {
const { stdout } = await exec('git', ['diff', '-U3', `${mainBranch}...${branchName}`], {
cwd: projectRoot,
maxBuffer: MAX_BUFFER,
});
return stdout;
} catch {
return '';
}
}
interface FileDiffResult {
diff: string;
oldContent: string;
newContent: string;
}
export async function getFileDiff(
worktreePath: string,
filePath: string,
baseBranch?: string,
): Promise<FileDiffResult> {
const headHash = await pinHead(worktreePath);
const base = await detectMergeBase(worktreePath, headHash, baseBranch).catch(() => headHash);
// Old content from merge-base (what existed when the branch was created)
let oldContent = '';
try {
const { stdout } = await exec('git', ['show', `${base}:${filePath}`], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
});
oldContent = stdout;
} catch {
/* file didn't exist at merge-base — new file */
}
// New content: prefer committed content from HEAD, fall back to disk
let newContent = '';
let committedContent = '';
let fileExistsOnDisk = false;
let fileContentReadable = false;
// Try reading committed content from git
try {
const { stdout } = await exec('git', ['show', `${headHash}:${filePath}`], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
});
committedContent = stdout;
} catch {
/* file not in HEAD — untracked or new */
}
// Read disk content
const fullPath = path.join(worktreePath, filePath);
let diskContent = '';
try {
const stat = await fs.promises.stat(fullPath);
if (stat.isFile()) {
fileExistsOnDisk = true;
if (stat.size < MAX_BUFFER) {
diskContent = await fs.promises.readFile(fullPath, 'utf8');
fileContentReadable = true;
}
}
} catch {
/* file doesn't exist — deleted file */
}
// Detect uncommitted deletion: file tracked in HEAD but deleted locally
const isUncommittedDeletion = !fileExistsOnDisk && committedContent !== '';
// Select newContent based on file state
const hasUncommittedChanges =
committedContent && fileExistsOnDisk && fileContentReadable && diskContent !== committedContent;
if (isUncommittedDeletion) {
newContent = '';
// File added in branch but deleted locally — show committed content as "old" side
if (!oldContent && committedContent) {
oldContent = committedContent;
}
} else if (hasUncommittedChanges) {
newContent = diskContent;
} else if (committedContent) {
newContent = committedContent;
} else {
newContent = diskContent;
}
// Generate diff between merge-base and HEAD for committed files
let diff = '';
try {
const { stdout } = await exec('git', ['diff', base, headHash, '--', filePath], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
});
if (stdout.trim()) diff = stdout;
} catch {
/* empty */
}
// Untracked/uncommitted file with no committed diff — build pseudo-diff from disk content
// Only when content was actually readable (skip for files exceeding MAX_BUFFER)
if (!diff && fileExistsOnDisk && !oldContent && fileContentReadable) {
if (await isBinaryFile(fullPath)) {
diff = `Binary files /dev/null and b/${filePath} differ`;
} else {
const lines = newContent.split('\n');
const pseudoLines: string[] = [];
pseudoLines.push(`--- /dev/null`);
pseudoLines.push(`+++ b/${filePath}`);
pseudoLines.push(`@@ -0,0 +1,${lines.length} @@`);
for (const line of lines) {
pseudoLines.push(`+${line}`);
}
diff = pseudoLines.join('\n') + '\n';
}
}
// Uncommitted deletion with no committed diff — build deletion pseudo-diff
if (!diff && isUncommittedDeletion && oldContent) {
const lines = oldContent.split('\n');
const pseudoLines: string[] = [];
pseudoLines.push(`--- a/${filePath}`);
pseudoLines.push(`+++ /dev/null`);
pseudoLines.push(`@@ -1,${lines.length} +0,0 @@`);
for (const line of lines) {
pseudoLines.push(`-${line}`);
}
diff = pseudoLines.join('\n') + '\n';
}
return { diff, oldContent, newContent };
}
export async function getWorktreeStatus(
worktreePath: string,
baseBranch?: string,
): Promise<{
has_committed_changes: boolean;
has_uncommitted_changes: boolean;
current_branch: string | null;
}> {
const { stdout: statusOut } = await exec('git', ['status', '--porcelain'], {
cwd: worktreePath,
maxBuffer: MAX_BUFFER,
});
const hasUncommittedChanges = statusOut.trim().length > 0;
const currentBranch = await getCurrentBranchName(worktreePath).catch(() => null);
const mergeBase = await detectMergeBase(worktreePath, 'HEAD', baseBranch);
let hasCommittedChanges = false;
try {
const { stdout: logOut } = await exec('git', ['log', `${mergeBase}..HEAD`, '--oneline'], {
cwd: worktreePath,
});
hasCommittedChanges = logOut.trim().length > 0;
} catch {
/* ignore */
}
return {
has_committed_changes: hasCommittedChanges,
has_uncommitted_changes: hasUncommittedChanges,
current_branch: currentBranch,
};
}
/** Stage all changes and commit in a worktree. */
export async function commitAll(worktreePath: string, message: string): Promise<void> {
await exec('git', ['add', '-A'], { cwd: worktreePath });
await exec('git', ['commit', '-m', message], { cwd: worktreePath });
}
/** Discard all uncommitted changes in a worktree (keeps committed work). */
export async function discardUncommitted(worktreePath: string): Promise<void> {
await exec('git', ['checkout', '.'], { cwd: worktreePath });
await exec('git', ['clean', '-fd'], { cwd: worktreePath });
}
export async function checkMergeStatus(
worktreePath: string,
baseBranch?: string,
): Promise<{ main_ahead_count: number; conflicting_files: string[] }> {
const mainBranch = baseBranch ?? (await detectMainBranch(worktreePath));
let mainAheadCount = 0;
try {
const { stdout } = await exec('git', ['rev-list', '--count', `HEAD..${mainBranch}`], {
cwd: worktreePath,
});
mainAheadCount = parseInt(stdout.trim(), 10) || 0;
} catch {
/* ignore */
}
if (mainAheadCount === 0) return { main_ahead_count: 0, conflicting_files: [] };
const conflictingFiles: string[] = [];
try {
await exec('git', ['merge-tree', '--write-tree', 'HEAD', mainBranch], { cwd: worktreePath });
} catch (e: unknown) {
// merge-tree outputs conflict info on failure
const output = String(e);
for (const line of output.split('\n')) {
const p = parseConflictPath(line);
if (p) conflictingFiles.push(p);
}
}
return { main_ahead_count: mainAheadCount, conflicting_files: conflictingFiles };
}
export async function mergeTask(
projectRoot: string,
branchName: string,
squash: boolean,
message: string | null,
cleanup: boolean,
baseBranch?: string,
): Promise<{ main_branch: string; lines_added: number; lines_removed: number }> {
const lockKey = await detectRepoLockKey(projectRoot).catch(() => projectRoot);
return withWorktreeLock(lockKey, async () => {
const mainBranch = baseBranch ?? (await detectMainBranch(projectRoot));
// Safety check: verify the worktree is actually on the expected branch.
// AI agents sometimes check out a different branch (or detach HEAD),
// and merging the original branch would silently discard their work.
const worktreePath = path.join(projectRoot, '.worktrees', branchName);
if (fs.existsSync(worktreePath)) {
const actualBranch = await getCurrentBranchName(worktreePath).catch(() => null);
if (actualBranch === null) {
throw new Error(
`The worktree for '${branchName}' has a detached HEAD. ` +
`Merging would use the stale branch ref and discard work. ` +
`Please check out '${branchName}' in the worktree first.`,
);
}
if (actualBranch !== branchName) {
throw new Error(
`Branch mismatch: the worktree is on '${actualBranch}' but the task expects '${branchName}'. ` +
`Changes on '${actualBranch}' would be lost. Please check out '${branchName}' in the worktree first, or update the task branch.`,
);
}
}
const { linesAdded, linesRemoved } = await computeBranchDiffStats(
projectRoot,
mainBranch,
branchName,
);
// Verify clean working tree
const { stdout: statusOut } = await exec('git', ['status', '--porcelain'], {
cwd: projectRoot,
});
if (statusOut.trim())
throw new Error(
'Project root has uncommitted changes. Please commit or stash them before merging.',
);
const originalBranch = await getCurrentBranchName(projectRoot).catch(() => null);
// Checkout main (bare branch name, not remote-tracking ref)
await exec('git', ['checkout', mainBranch], { cwd: projectRoot });
const restoreBranch = async () => {
if (originalBranch) {
try {
await exec('git', ['checkout', originalBranch], { cwd: projectRoot });
} catch (e) {
console.warn(`Failed to restore branch '${originalBranch}':`, e);
}
}
};
if (squash) {
try {
await exec('git', ['merge', '--squash', '--', branchName], { cwd: projectRoot });