Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(git): add addWorktree/removeWorktree helpers for agent isolation

Chaitanya Giri8715c783b9db
diff --git a/src/main/git.ts b/src/main/git.ts
index 24042730..8dd229e5 100644
--- a/src/main/git.ts
+++ b/src/main/git.ts
@@ -141,3 +141,35 @@ export async function isRepo(cwd: string): Promise<boolean> {
const res = await runGit(cwd, ['rev-parse', '--is-inside-work-tree']);
return res.ok && res.stdout.trim() === 'true';
}
+
+/** Derive a safe `agent/<id>` branch name from a worktree path's basename. */
+function agentBranchFor(wtPath: string): string {
+ const base = wtPath.split(/[\\/]/).filter(Boolean).pop() ?? 'agent';
+ const slug = base.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'agent';
+ return `agent/${slug}`;
+}
+
+/** Provision an isolated git worktree for an agent at `wtPath`, branching off
+ * `baseBranch`. Tries to create a fresh `agent/<id>` branch first; if that
+ * branch already exists, falls back to checking out `baseBranch` directly. */
+export async function addWorktree(
+ cwd: string, wtPath: string, baseBranch: string
+): Promise<{ ok: boolean; error?: string }> {
+ const branch = agentBranchFor(wtPath);
+ const fresh = await runGit(cwd, ['worktree', 'add', wtPath, '-b', branch, baseBranch]);
+ if (fresh.ok) return { ok: true };
+ // Branch likely already exists (or the path is taken) — retry without -b.
+ const fallback = await runGit(cwd, ['worktree', 'add', wtPath, baseBranch]);
+ if (fallback.ok) return { ok: true };
+ return { ok: false, error: fallback.error };
+}
+
+/** Best-effort removal of an agent's worktree. Forced so a dirty tree doesn't
+ * block teardown; failures are surfaced but callers may ignore them. */
+export async function removeWorktree(
+ cwd: string, wtPath: string
+): Promise<{ ok: boolean; error?: string }> {
+ const res = await runGit(cwd, ['worktree', 'remove', '--force', wtPath]);
+ if (res.ok) return { ok: true };
+ return { ok: false, error: res.error };
+}