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
2012 lines (1799 loc) · 63.9 KB
/
Copy pathgit.ts
File metadata and controls
2012 lines (1799 loc) · 63.9 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, execFileSync as _execFileSync, spawn } from 'child_process';
import { promisify } from 'util';
import fs from 'fs';
import path from 'path';
import type { BrowserWindow } from 'electron';
import { debug as logDebug } from '../log.js';
const _exec = promisify(execFile);
/**
* Trace + run a git command (or any execFile invocation).
* Emits a `debug` entry under category `git` with the args before
* execution so verbose logs can reconstruct the command stream.
*/
const exec: typeof _exec = ((cmd: string, args: string[], options?: unknown) => {
if (cmd === 'git') logDebug('git', args.join(' '));
return (_exec as unknown as (...a: unknown[]) => unknown)(cmd, args, options);
}) as typeof _exec;
const execFileSync: typeof _execFileSync = ((cmd: string, args: string[], options?: unknown) => {
if (cmd === 'git') logDebug('git', args.join(' '));
return (_execFileSync as unknown as (...a: unknown[]) => unknown)(cmd, args, options);
}) as typeof _execFileSync;
// --- 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;
}
interface PickedMergeBase {
sha: string;
ref: string;
}
interface DiffBaseCacheEntry {
value: PickedMergeBase;
expiresAt: number;
}
const mainBranchCache = new Map<string, CacheEntry>();
const diffBaseCache = new Map<string, DiffBaseCacheEntry>();
const MAIN_BRANCH_TTL = 60_000; // 60s
const DIFF_BASE_TTL = 30_000; // 30s
const MAX_BUFFER = 10 * 1024 * 1024; // 10MB
const STDERR_CAP = 4096; // cap for stderr buffers in spawned git processes
/** Git's well-known empty tree SHA — used to diff the initial commit against nothing. */
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf899d69f82cf7202';
// 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 diffBaseCache) {
if (v.expiresAt <= now) diffBaseCache.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 invalidateDiffBaseCache(): void {
diffBaseCache.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 = [
'.cursor',
'.aider',
'.copilot',
'.codeium',
'.continue',
'.windsurf',
'.env',
'node_modules',
];
/**
* Entries inside `.claude/` that must NOT be seeded from the main repo's
* `.claude/` into new worktrees (per-worktree-local state).
*/
const CLAUDE_DIR_EXCLUDE = new Set(['plans', 'steps.json']);
/**
* Files Claude Code's sandbox (bwrap) read-only-binds on startup. They must
* exist at the worktree path or the sandbox fails before Claude launches.
*/
const CLAUDE_REQUIRED_FILES = ['settings.json', 'settings.local.json'];
/**
* Worktree-root filenames bwrap leaves behind as character-device placeholders
* when it bind-mounts user-home dotfiles into the Claude Code sandbox. They
* aren't project files and must not surface in `git status` / changed-files.
* Mirrored into `.git/info/exclude` so the filter works on branches whose
* committed `.gitignore` predates the fix. Patterns are root-anchored (`/`)
* so a legitimate nested file with the same name (e.g. `subproj/.gitmodules`)
* is still shown.
*/
const SANDBOX_EXCLUDE_PATTERNS = [
'/.bash_profile',
'/.bashrc',
'/.gitconfig',
'/.gitmodules',
'/.mcp.json',
'/.profile',
'/.ripgreprc',
'/.zprofile',
'/.zshrc',
];
const SANDBOX_EXCLUDE_HEADER = '# parallel-code: sandbox bind-mount artifacts';
const seededSandboxExcludes = new Set<string>();
// --- 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();
}
/**
* Pick the merge-base SHA closest to HEAD between local `<branch>` and
* `origin/<branch>`.
*
* Either ref can be stale relative to the other: local can be ahead of origin
* (the user merged a PR locally without pushing) or origin can be ahead of
* local (the user fetched without pulling). Whichever ref's merge-base with
* HEAD is a *descendant* of the other's is the more recent branch point and
* gives the smallest correct diff. When neither merge-base is an ancestor of
* the other (the two refs have themselves diverged), the local merge-base is
* preferred — origin can carry teammate work the user has not seen yet.
*
* Returns null when neither ref exists or both merge-base lookups fail.
*/
async function pickMergeBase(
repoRoot: string,
branch: string,
head: string,
): Promise<PickedMergeBase | null> {
const [hasLocal, hasOrigin] = await Promise.all([
localBranchExists(repoRoot, branch),
remoteTrackingRefExists(repoRoot, branch),
]);
if (!hasLocal && !hasOrigin) return null;
const mergeBaseFor = async (ref: string): Promise<string | null> => {
try {
const { stdout } = await exec('git', ['merge-base', ref, head], { cwd: repoRoot });
return stdout.trim() || null;
} catch {
return null;
}
};
const [localMb, originMb] = await Promise.all([
hasLocal ? mergeBaseFor(branch) : Promise.resolve(null),
hasOrigin ? mergeBaseFor(`origin/${branch}`) : Promise.resolve(null),
]);
if (!localMb && !originMb) return null;
if (!localMb && originMb) return { sha: originMb, ref: `origin/${branch}` };
if (!originMb && localMb) return { sha: localMb, ref: branch };
if (!localMb || !originMb) return null;
if (localMb === originMb) return { sha: localMb, ref: branch };
const isAncestor = async (anc: string, desc: string): Promise<boolean> => {
try {
await exec('git', ['merge-base', '--is-ancestor', anc, desc], { cwd: repoRoot });
return true;
} catch {
return false;
}
};
if (await isAncestor(originMb, localMb)) return { sha: localMb, ref: branch };
if (await isAncestor(localMb, originMb)) return { sha: originMb, ref: `origin/${branch}` };
return { sha: localMb, ref: branch };
}
/**
* Refine a picked merge-base by dropping commits that are patch-equivalent
* to ones already on `base.ref` (rebased duplicates from a prior `git merge`
* of the upstream that was later rebased onto a new base).
*
* Uses git's built-in patch-id detection via `--cherry-pick --right-only`.
* The first call's `%H %P` format embeds the oldest unique commit's parent
* SHA so we don't need a separate `rev-parse` step.
*
* Three outcomes:
* - **No unique commits** (branch is fully merged upstream): collapse the
* diff range to `head...head` (empty) so the user sees zero changes
* instead of the noisy patch-equivalent set.
* - **Unique commits contiguous at the tip** (the common case for
* agent-driven branches): refine the base to the oldest unique commit's
* parent so the diff range only contains real branch work.
* - **Interleaved** (a patch-equivalent commit sits between unique ones):
* keep the picked base — accepting the noise is cheaper than stitching
* per-commit patches. Logged for diagnostics.
*
* Any git invocation failure falls back to the picked base unchanged.
*
* Dual-side counterpart: `checkMergeStatus` applies `--cherry-pick
* --right-only` to `HEAD...<main>` to count *main's* unique commits not in
* HEAD (i.e. how stale HEAD is relative to main), so the merge dialog's
* "Rebase first" prompt agrees with this filter.
*/
async function refineDiffBaseWithCherryPick(
repoRoot: string,
base: PickedMergeBase,
head: string,
): Promise<PickedMergeBase> {
let unique: string[];
let oldestParent: string | null = null;
try {
const { stdout } = await exec(
'git',
[
'log',
'--cherry-pick',
'--right-only',
'--no-merges',
'--reverse',
'--pretty=%H %P',
`${base.ref}...${head}`,
],
{ cwd: repoRoot, maxBuffer: MAX_BUFFER },
);
const lines = stdout
.split('\n')
.map((s) => s.trim())
.filter(Boolean);
unique = lines.map((line) => line.split(' ', 1)[0]);
if (lines.length > 0) {
// First line is the oldest unique commit (--reverse). With --no-merges
// every commit has exactly one parent, so the first SHA after the
// commit hash is that parent.
const parts = lines[0].split(' ');
oldestParent = parts[1] ?? null;
}
} catch {
return base;
}
if (unique.length === 0) {
// Fully merged upstream — every branch commit is patch-equivalent to
// one already on the base. Collapse the diff range to empty so the
// user sees no changes (instead of the noisy duplicated patch set
// that `base.ref...HEAD` would produce).
return { sha: head, ref: head };
}
if (!oldestParent) return base;
let rangeCount: number;
try {
const { stdout } = await exec(
'git',
['rev-list', '--count', '--no-merges', `${oldestParent}..${head}`],
{ cwd: repoRoot },
);
rangeCount = parseInt(stdout.trim(), 10);
if (isNaN(rangeCount)) return base;
} catch {
return base;
}
if (rangeCount === unique.length) {
return { sha: oldestParent, ref: oldestParent };
}
logDebug(
'git',
`cherry-pick refine: interleaved (unique=${unique.length}, range=${rangeCount}) — keeping ${base.ref}`,
);
return base;
}
/**
* Resolve both sides needed for one-way diffs.
*
* Git's three-dot diff is directional: `git diff base...head` means
* `git diff $(git merge-base base head) head`, while `git diff head...base`
* shows base-only commits. Keep the picked base ref around so committed-only
* diffs can use the correctly ordered three-dot range.
*
* Working-tree diffs are different: `git diff base...` still compares against
* HEAD, not the dirty working tree. For those callers, use `base.sha` as the
* single diff start point (`git diff <merge-base-sha>`) so tracked local edits
* remain visible.
*
* Result is post-refinement: rebased patch-equivalent commits are dropped from
* the diff range when possible. See `refineDiffBaseWithCherryPick`.
*/
async function detectDiffBase(
repoRoot: string,
head?: string,
baseBranch?: string,
): Promise<PickedMergeBase> {
const branch = baseBranch ?? (await detectMainBranch(repoRoot));
// Resolve the literal 'HEAD' to its commit SHA so the cache key tracks
// HEAD movement. Otherwise a cached `{sha:'HEAD', ref:'HEAD'}` (returned
// by refineDiffBaseWithCherryPick when the branch was fully patch-
// equivalent to base) survives a new commit on the branch — callers then
// run `git log HEAD..HEAD` against the literal and see no commits, even
// though HEAD just moved forward.
const requestedHead = head ?? 'HEAD';
const headRef = requestedHead === 'HEAD' ? await pinHead(repoRoot) : requestedHead;
const key = `${cacheKey(repoRoot)}:${branch}:${headRef}`;
const cached = diffBaseCache.get(key);
if (cached) {
if (cached.expiresAt > Date.now()) return cached.value;
diffBaseCache.delete(key);
}
const picked = await pickMergeBase(repoRoot, branch, headRef);
if (!picked) return { sha: headRef, ref: headRef };
const refined = await refineDiffBaseWithCherryPick(repoRoot, picked, headRef);
diffBaseCache.set(key, { value: refined, expiresAt: Date.now() + DIFF_BASE_TTL });
return refined;
}
/**
* Resolve the diff base SHA for `head` against `baseBranch` (or the detected
* main branch). Falls back to `headRef` when no candidate ref resolves so
* callers diff against themselves (empty diff) rather than against the branch
* tip.
*/
async function detectMergeBase(
repoRoot: string,
head?: string,
baseBranch?: string,
): Promise<string> {
const headRef = head ?? 'HEAD';
const result = await detectDiffBase(repoRoot, headRef, baseBranch);
return result.sha;
}
function oneWayDiffRange(base: PickedMergeBase, head: string): string {
return `${base.ref}...${head}`;
}
async function detectOneWayDiffRange(
repoRoot: string,
head?: string,
baseBranch?: string,
): Promise<string> {
const headRef = head ?? 'HEAD';
return oneWayDiffRange(await detectDiffBase(repoRoot, headRef, baseBranch), 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 splitContentLines(content: string): string[] {
if (content.length === 0) return [];
const lines = content.split('\n');
return content.endsWith('\n') ? lines.slice(0, -1) : lines;
}
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;
}
function safeRealpath(p: string): string {
try {
return fs.realpathSync(p);
} catch {
return p;
}
}
interface ListedWorktree {
path: string;
branchName: string | null;
detached: boolean;
}
function parseWorktreeList(output: string): ListedWorktree[] {
const entries: ListedWorktree[] = [];
let current: ListedWorktree | null = null;
for (const rawLine of output.split('\n')) {
const line = rawLine.trimEnd();
if (!line) {
if (current?.path) entries.push(current);
current = null;
continue;
}
if (line.startsWith('worktree ')) {
if (current?.path) entries.push(current);
current = {
path: line.slice('worktree '.length).trim(),
branchName: null,
detached: false,
};
continue;
}
if (!current) continue;
if (line.startsWith('branch ')) {
const ref = line.slice('branch '.length).trim();
const prefix = 'refs/heads/';
current.branchName = ref.startsWith(prefix) ? ref.slice(prefix.length) : ref;
continue;
}
if (line === 'detached') {
current.detached = true;
}
}
if (current?.path) entries.push(current);
return entries;
}
async function computeBranchDiffStats(
projectRoot: string,
mainBranch: string,
branchName: string,
): Promise<{ linesAdded: number; linesRemoved: number }> {
const diffRange = await detectOneWayDiffRange(projectRoot, branchName, mainBranch);
const { stdout } = await exec('git', ['diff', '--numstat', diffRange], {
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 };
}
// --- 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. `.claude` is handled separately below — it
// can't be a symlink because Claude Code's bwrap sandbox binds specific
// entries inside it, and bwrap refuses to bind-mount at symlink paths.
for (const name of symlinkDirs) {
if (name === '.claude') continue;
// 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;
fs.symlinkSync(source, target);
} catch (err) {
console.warn(`Failed to symlink directory '${name}' into worktree:`, err);
}
}
ensureClaudeSandboxFiles(worktreePath, repoRoot);
ensureSandboxExcludes(worktreePath);
return { path: worktreePath, branch: branchName };
}
/**
* Ensure the worktree's `.claude/` is bwrap-safe and seeded from the main
* repo's `.claude/`, matching Claude Code's `/worktree` model: each worktree
* gets an independent real `.claude/` directory (no symlinks), one-time
* copied from the source at creation. bwrap's `create_file` cannot place a
* bind-mount placeholder at a symlink destination — it fails with
* "Can't create file at … .claude/X: No such file or directory" — so every
* entry must be a real file or directory.
*
* Also runs as a backfill on agent spawn: deletes any symlinks left over
* from the previous shallow-symlink behavior and seeds any newly-missing
* entries from the source.
*/
export function ensureClaudeSandboxFiles(worktreePath: string, repoRoot?: string): void {
const claudeDir = path.join(worktreePath, '.claude');
try {
fs.mkdirSync(claudeDir, { recursive: true });
} catch (err) {
console.warn(`Failed to create ${claudeDir}:`, err);
return;
}
// Remove any symlinks under .claude/ — they're leftover from the old
// shallow-symlink behavior and bwrap cannot bind to them. Real files/dirs
// are preserved (may contain worktree-local edits).
let existing: fs.Dirent[] = [];
try {
existing = fs.readdirSync(claudeDir, { withFileTypes: true });
} catch (err) {
console.warn(`Failed to readdir ${claudeDir}:`, err);
}
for (const entry of existing) {
if (!entry.isSymbolicLink()) continue;
try {
fs.unlinkSync(path.join(claudeDir, entry.name));
} catch (err) {
console.warn(`Failed to unlink ${path.join(claudeDir, entry.name)}:`, err);
}
}
// Seed missing entries from the main repo's .claude/. Dereferences any
// symlinks in the source so the copy is pure real files (bwrap-safe).
const root = repoRoot ?? detectRepoRoot(worktreePath);
if (root && root !== worktreePath) {
const source = path.join(root, '.claude');
if (fs.existsSync(source)) {
let srcEntries: fs.Dirent[] = [];
try {
srcEntries = fs.readdirSync(source, { withFileTypes: true });
} catch (err) {
console.warn(`Failed to readdir ${source}:`, err);
}
for (const entry of srcEntries) {
if (CLAUDE_DIR_EXCLUDE.has(entry.name)) continue;
const dst = path.join(claudeDir, entry.name);
if (fs.existsSync(dst)) continue;
try {
fs.cpSync(path.join(source, entry.name), dst, {
recursive: true,
dereference: true,
});
} catch (err) {
console.warn(`Failed to seed ${dst} from source:`, err);
}
}
}
}
// Ensure required settings placeholders exist — bwrap binds them even when
// absent from both worktree and source.
for (const file of CLAUDE_REQUIRED_FILES) {
const p = path.join(claudeDir, file);
if (fs.existsSync(p)) continue;
try {
fs.writeFileSync(p, '{}\n');
} catch (err) {
console.warn(`Failed to create placeholder ${p}:`, err);
}
}
}
/**
* Append `SANDBOX_EXCLUDE_PATTERNS` to the shared `.git/info/exclude` so the
* bwrap-left char-device placeholders at the worktree root are filtered out
* of `git status` / `git ls-files` regardless of what the branch's committed
* `.gitignore` looks like. Uses the header line as an idempotency marker;
* safe to call on every agent spawn. Memoized per common git dir for the
* process lifetime.
*/
export function ensureSandboxExcludes(worktreePath: string): void {
let commonDir: string;
try {
const out = execFileSync('git', ['rev-parse', '--git-common-dir'], {
cwd: worktreePath,
encoding: 'utf8',
timeout: 3000,
}).trim();
commonDir = path.isAbsolute(out) ? out : path.join(worktreePath, out);
} catch {
return;
}
if (seededSandboxExcludes.has(commonDir)) return;
const excludePath = path.join(commonDir, 'info', 'exclude');
let existing = '';
try {
existing = fs.readFileSync(excludePath, 'utf8');
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
console.warn(`Failed to read ${excludePath}:`, err);
return;
}
// File is absent — `.git/info/` itself is guaranteed by `git init`, so no mkdir needed.
}
if (existing.includes(SANDBOX_EXCLUDE_HEADER)) {
seededSandboxExcludes.add(commonDir);
return;
}
const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
const block = prefix + SANDBOX_EXCLUDE_HEADER + '\n' + SANDBOX_EXCLUDE_PATTERNS.join('\n') + '\n';
try {
fs.appendFileSync(excludePath, block);
seededSandboxExcludes.add(commonDir);
} catch (err) {
console.warn(`Failed to append to ${excludePath}:`, err);
}
}
/**
* Find the main repository root for a worktree via `git rev-parse
* --git-common-dir`. Returns null when the cwd isn't inside a git repo.
*/
function detectRepoRoot(worktreePath: string): string | null {
try {
const out = execFileSync('git', ['rev-parse', '--git-common-dir'], {
cwd: worktreePath,
encoding: 'utf8',
timeout: 3000,
}).trim();
const abs = path.isAbsolute(out) ? out : path.join(worktreePath, out);
return path.dirname(abs);
} catch {
return null;
}
}
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. Docker Desktop's VirtioFS bind-mount
// may still be releasing after the container exits — retry with backoff.
const delays = [0, 500, 1500, 3000];
let lastErr: unknown;
for (const delay of delays) {
if (delay > 0) await new Promise((r) => setTimeout(r, delay));
try {
fs.rmSync(worktreePath, { recursive: true, force: true });
lastErr = undefined;
break;
} catch (e) {
lastErr = e;
}
}
if (lastErr) throw lastErr;
}
}
// 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);