xonecas.io
64875
Mc

mini-coder / commit 2c263ec

Add subagent worktree merge handling and dirty-state sync

Sean2026-03-04 2c263ecd227c10054dc8db9be9709b89b36315bb parent e0552fa

8 files changed

src/agent/reporter.ts+1−0
@@ -25,6 +25,7 @@ export interface StatusBarData {
2525 export interface SubagentEventData {
2626 laneId: number;
2727 parentLabel?: string;
28+ worktreeBranch?: string;
2829 activeLanes: Set<number>;
2930 }
3031
src/agent/subagent-runner.ts+157−55
@@ -1,14 +1,34 @@
1+import { tmpdir } from "node:os";
2+import { join } from "node:path";
13 import { loadAgents } from "../cli/agents.ts";
24 import { formatSubagentLabel } from "../cli/output.ts";
35 import { resolveModel } from "../llm-api/providers.ts";
46 import { type CoreMessage, runTurn } from "../llm-api/turn.ts";
57 import type { SubagentOutput } from "../tools/subagent.ts";
8+import {
9+ MergeInProgressError,
10+ cleanupBranch,
11+ createWorktree,
12+ isGitRepo,
13+ mergeWorktree,
14+ removeWorktree,
15+ syncDirtyStateToWorktree,
16+} from "../tools/worktree.ts";
617 import type { AgentReporter } from "./reporter.ts";
718 import { buildSystemPrompt } from "./system-prompt.ts";
819 import { buildToolSet } from "./tools.ts";
920
1021 import type { ThinkingEffort } from "../llm-api/providers.ts";
1122
23+function makeWorktreeBranch(laneId: number): string {
24+ return `mc-sub-${laneId}-${Date.now()}`;
25+}
26+
27+function makeWorktreePath(laneId: number): string {
28+ const suffix = crypto.randomUUID().replace(/-/g, "").slice(0, 10);
29+ return join(tmpdir(), `mc-wt-${laneId}-${suffix}`);
30+}
31+
1232 export function createSubagentRunner(
1333 cwd: string,
1434 reporter: AgentReporter,
@@ -17,6 +37,17 @@ export function createSubagentRunner(
1737 ) {
1838 let nextLaneId = 1;
1939 const activeLanes = new Set<number>();
40+ const worktreesEnabledPromise = isGitRepo(cwd);
41+
42+ let mergeLock: Promise<void> = Promise.resolve();
43+ const withMergeLock = <T>(fn: () => Promise<T>): Promise<T> => {
44+ const task = mergeLock.then(fn, fn);
45+ mergeLock = task.then(
46+ () => undefined,
47+ () => undefined,
48+ );
49+ return task;
50+ };
2051
2152 const runSubagent = async (
2253 prompt: string,
@@ -25,66 +56,137 @@ export function createSubagentRunner(
2556 modelOverride?: string,
2657 parentLabel?: string,
2758 ): Promise<SubagentOutput> => {
28- const currentModel = getCurrentModel();
29- const allAgents = loadAgents(cwd);
30- const agentConfig = agentName ? allAgents.get(agentName) : undefined;
31- if (agentName && !agentConfig) {
32- throw new Error(
33- `Unknown agent "${agentName}". Available agents: ${[...allAgents.keys()].join(", ") || "(none)"}`,
34- );
35- }
36-
37- const model = modelOverride ?? agentConfig?.model ?? currentModel;
38- const systemPrompt =
39- agentConfig?.systemPrompt ?? buildSystemPrompt(cwd, model);
40-
41- const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
4259 const laneId = nextLaneId++;
4360 activeLanes.add(laneId);
44- const laneLabel = formatSubagentLabel(laneId, parentLabel);
45-
46- const subTools = buildToolSet({
47- cwd,
48- depth,
49- runSubagent,
50- onHook: (tool, path, ok) => reporter.renderHook(tool, path, ok),
51- availableAgents: allAgents,
52- parentLabel: laneLabel,
53- }).filter((tool) => tool.name !== "subagent");
54-
55- const subLlm = resolveModel(model);
56-
57- let result = "";
58- let inputTokens = 0;
59- let outputTokens = 0;
60-
61- const effort = getThinkingEffort();
62- const events = runTurn({
63- model: subLlm,
64- modelString: model,
65- messages: subMessages,
66- tools: subTools,
67- systemPrompt,
68- ...(effort ? { thinkingEffort: effort } : {}),
69- });
70-
71- for await (const event of events) {
72- reporter.stopSpinner();
73- reporter.renderSubagentEvent(event, {
74- laneId,
75- ...(parentLabel ? { parentLabel } : {}),
76- activeLanes,
61+
62+ let subagentCwd = cwd;
63+ let worktreeBranch: string | undefined;
64+ let worktreePath: string | undefined;
65+ let preserveBranchOnFailure = false;
66+
67+ try {
68+ const worktreesEnabled = await worktreesEnabledPromise;
69+ if (worktreesEnabled) {
70+ const nextBranch = makeWorktreeBranch(laneId);
71+ const nextPath = makeWorktreePath(laneId);
72+ await createWorktree(cwd, nextBranch, nextPath);
73+ await syncDirtyStateToWorktree(cwd, nextPath);
74+ worktreeBranch = nextBranch;
75+ worktreePath = nextPath;
76+ subagentCwd = nextPath;
77+ }
78+
79+ const currentModel = getCurrentModel();
80+ const allAgents = loadAgents(subagentCwd);
81+ const agentConfig = agentName ? allAgents.get(agentName) : undefined;
82+ if (agentName && !agentConfig) {
83+ throw new Error(
84+ `Unknown agent "${agentName}". Available agents: ${[...allAgents.keys()].join(", ") || "(none)"}`,
85+ );
86+ }
87+
88+ const model = modelOverride ?? agentConfig?.model ?? currentModel;
89+ const systemPrompt =
90+ agentConfig?.systemPrompt ?? buildSystemPrompt(subagentCwd, model);
91+
92+ const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
93+ const laneLabel = formatSubagentLabel(laneId, parentLabel);
94+
95+ const subTools = buildToolSet({
96+ cwd: subagentCwd,
97+ depth,
98+ runSubagent,
99+ onHook: (tool, path, ok) => reporter.renderHook(tool, path, ok),
100+ availableAgents: allAgents,
101+ parentLabel: laneLabel,
102+ }).filter((tool) => tool.name !== "subagent");
103+
104+ const subLlm = resolveModel(model);
105+
106+ let result = "";
107+ let inputTokens = 0;
108+ let outputTokens = 0;
109+
110+ const effort = getThinkingEffort();
111+ const events = runTurn({
112+ model: subLlm,
113+ modelString: model,
114+ messages: subMessages,
115+ tools: subTools,
116+ systemPrompt,
117+ ...(effort ? { thinkingEffort: effort } : {}),
77118 });
78- reporter.startSpinner("thinking");
79- if (event.type === "text-delta") result += event.delta;
80- if (event.type === "turn-complete") {
81- inputTokens = event.inputTokens;
82- outputTokens = event.outputTokens;
119+
120+ for await (const event of events) {
121+ reporter.stopSpinner();
122+ reporter.renderSubagentEvent(event, {
123+ laneId,
124+ ...(parentLabel ? { parentLabel } : {}),
125+ ...(worktreeBranch ? { worktreeBranch } : {}),
126+ activeLanes,
127+ });
128+ reporter.startSpinner("thinking");
129+ if (event.type === "text-delta") result += event.delta;
130+ if (event.type === "turn-complete") {
131+ inputTokens = event.inputTokens;
132+ outputTokens = event.outputTokens;
133+ }
83134 }
84- }
85135
86- activeLanes.delete(laneId);
87- return { result, inputTokens, outputTokens };
136+ const baseOutput: SubagentOutput = { result, inputTokens, outputTokens };
137+ const branch = worktreeBranch;
138+ const path = worktreePath;
139+ if (!branch || !path) return baseOutput;
140+
141+ preserveBranchOnFailure = true;
142+ return await withMergeLock(async () => {
143+ try {
144+ const mergeResult = await mergeWorktree(cwd, branch);
145+ await removeWorktree(cwd, path);
146+ if (mergeResult.success) {
147+ await cleanupBranch(cwd, branch);
148+ return baseOutput;
149+ }
150+ return {
151+ ...baseOutput,
152+ mergeConflict: {
153+ branch,
154+ conflictFiles: mergeResult.conflictFiles,
155+ },
156+ };
157+ } catch (error) {
158+ if (error instanceof MergeInProgressError) {
159+ await removeWorktree(cwd, path);
160+ return {
161+ ...baseOutput,
162+ mergeBlocked: {
163+ branch,
164+ conflictFiles: error.conflictFiles,
165+ },
166+ };
167+ }
168+ throw error;
169+ }
170+ });
171+ } catch (error) {
172+ if (worktreeBranch && worktreePath) {
173+ const branch = worktreeBranch;
174+ const path = worktreePath;
175+ try {
176+ await withMergeLock(async () => {
177+ await removeWorktree(cwd, path);
178+ if (!preserveBranchOnFailure) {
179+ await cleanupBranch(cwd, branch);
180+ }
181+ });
182+ } catch {
183+ // Preserve the original subagent failure.
184+ }
185+ }
186+ throw error;
187+ } finally {
188+ activeLanes.delete(laneId);
189+ }
88190 };
89191
90192 return runSubagent;
src/agent/tools.ts+9−3
@@ -1,6 +1,10 @@
11 import type { ToolDef } from "../llm-api/types.ts";
22 import { webContentTool, webSearchTool } from "../tools/exa.ts";
3-import type { SubagentOutput } from "../tools/subagent.ts";
3+import {
4+ type SubagentOutput,
5+ createSubagentTool,
6+ getSubagentMergeError,
7+} from "../tools/subagent.ts";
48
59 import type { CreateOutput } from "../tools/create.ts";
610 import { createTool } from "../tools/create.ts";
@@ -27,7 +31,6 @@ import type { ReplaceOutput } from "../tools/replace.ts";
2731 import { replaceTool } from "../tools/replace.ts";
2832 import type { ShellOutput } from "../tools/shell.ts";
2933 import { shellTool } from "../tools/shell.ts";
30-import { createSubagentTool } from "../tools/subagent.ts";
3134
3235 // ─── Tool wrappers ────────────────────────────────────────────────────────────
3336
@@ -198,13 +201,16 @@ export function buildToolSet(opts: {
198201 `Cannot spawn another subagent from depth ${depth}.`,
199202 );
200203 }
201- return opts.runSubagent(
204+ const output = await opts.runSubagent(
202205 prompt,
203206 depth + 1,
204207 agentName,
205208 undefined,
206209 opts.parentLabel,
207210 );
211+ const mergeError = getSubagentMergeError(output);
212+ if (mergeError) throw new Error(mergeError);
213+ return output;
208214 },
209215 opts.availableAgents,
210216 opts.parentLabel,
src/cli/commands.ts+11−1
@@ -1,7 +1,10 @@
11 import * as c from "yoctocolors";
22 import { fetchAvailableModels } from "../llm-api/providers.ts";
33 import type { ThinkingEffort } from "../llm-api/providers.ts";
4-import type { SubagentOutput } from "../tools/subagent.ts";
4+import {
5+ type SubagentOutput,
6+ getSubagentMergeError,
7+} from "../tools/subagent.ts";
58
69 import {
710 deleteMcpServer,
@@ -44,6 +47,11 @@ export type CommandResult =
4447 | { type: "exit" }
4548 | { type: "inject-user-message"; text: string };
4649
50+function assertSubagentMerged(output: SubagentOutput): void {
51+ const mergeError = getSubagentMergeError(output);
52+ if (mergeError) throw new Error(mergeError);
53+}
54+
4755 // ─── Command handlers ─────────────────────────────────────────────────────────
4856
4957 async function handleModel(ctx: CommandContext, args: string): Promise<void> {
@@ -343,6 +351,7 @@ async function handleReview(
343351
344352 try {
345353 const output = await ctx.runSubagent(REVIEW_PROMPT(ctx.cwd, focus));
354+ assertSubagentMerged(output);
346355
347356 // Show review results.
348357 write(renderMarkdown(output.result));
@@ -385,6 +394,7 @@ async function handleCustomCommand(
385394
386395 try {
387396 const output = await ctx.runSubagent(prompt, cmd.model);
397+ assertSubagentMerged(output);
388398
389399 write(renderMarkdown(output.result));
390400 writeln();
src/cli/tool-render.ts+29−7
@@ -497,14 +497,35 @@ export function renderToolResult(
497497 writeln(` ${c.dim(text.length > 120 ? `${text.slice(0, 117)}…` : text)}`);
498498 }
499499
500+function stripAnsiSgr(text: string): string {
501+ const esc = String.fromCharCode(0x1b);
502+ return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
503+}
504+
505+function normalizeParentLaneLabel(parentLabel: string): string {
506+ const plain = stripAnsiSgr(parentLabel);
507+ const match = plain.match(/\[([^\]]+)\]/);
508+ const inner = (match?.[1] ?? plain).trim();
509+ const lanePath = (inner.split("·")[0] ?? inner).trim();
510+ return lanePath || inner;
511+}
512+
513+function shortWorktreeBranch(branch: string): string {
514+ const match = branch.match(/^(mc-sub-\d+)-\d+$/);
515+ return match?.[1] ?? branch;
516+}
517+
500518 export function formatSubagentLabel(
501519 laneId: number,
502520 parentLabel?: string,
521+ worktreeBranch?: string,
503522 ): string {
504- const numStr = parentLabel
505- ? `${parentLabel.replace(/[\[\]]/g, "")}.${laneId}`
506- : `${laneId}`;
507- return c.dim(c.cyan(`[${numStr}]`));
523+ const parent = parentLabel ? normalizeParentLaneLabel(parentLabel) : "";
524+ const numStr = parent ? `${parent}.${laneId}` : `${laneId}`;
525+ const branchHint = worktreeBranch
526+ ? `·${shortWorktreeBranch(worktreeBranch)}`
527+ : "";
528+ return c.dim(c.cyan(`[${numStr}${branchHint}]`));
508529 }
509530
510531 const laneBuffers = new Map<number, string>();
@@ -514,13 +535,14 @@ export function renderSubagentEvent(
514535 opts: {
515536 laneId: number;
516537 parentLabel?: string | undefined;
538+ worktreeBranch?: string;
517539 activeLanes: Set<number>;
518540 },
519541 ): void {
520- const { laneId, parentLabel, activeLanes } = opts;
542+ const { laneId, parentLabel, worktreeBranch, activeLanes } = opts;
521543
522- const labelStr = formatSubagentLabel(laneId, parentLabel);
523- const prefix = activeLanes.size > 1 ? `${labelStr} ` : "";
544+ const labelStr = formatSubagentLabel(laneId, parentLabel, worktreeBranch);
545+ const prefix = activeLanes.size > 1 || worktreeBranch ? `${labelStr} ` : "";
524546
525547 if (event.type === "text-delta") {
526548 const buf = (laneBuffers.get(laneId) ?? "") + event.delta;
src/tools/subagent.ts+36−0
@@ -17,6 +17,42 @@ export interface SubagentOutput {
1717 result: string;
1818 inputTokens: number;
1919 outputTokens: number;
20+ mergeConflict?: {
21+ branch: string;
22+ conflictFiles: string[];
23+ };
24+ mergeBlocked?: {
25+ branch: string;
26+ conflictFiles: string[];
27+ };
28+}
29+
30+function formatConflictFiles(conflictFiles: string[]): string {
31+ if (conflictFiles.length === 0) return " - (unknown)";
32+ return conflictFiles.map((file) => ` - ${file}`).join("\n");
33+}
34+
35+export function getSubagentMergeError(output: SubagentOutput): string | null {
36+ if (output.mergeConflict) {
37+ const files = formatConflictFiles(output.mergeConflict.conflictFiles);
38+ return `⚠ Merge conflict: subagent branch "${output.mergeConflict.branch}" has been merged into your working tree
39+but has conflicts in these files:
40+${files}
41+
42+Resolve the conflicts (remove <<<<, ====, >>>> markers), stage the files with
43+\`git add <file>\`, then run \`git merge --continue\` to complete the merge.`;
44+ }
45+ if (output.mergeBlocked) {
46+ const files = formatConflictFiles(output.mergeBlocked.conflictFiles);
47+ return `⚠ Merge deferred: subagent branch "${output.mergeBlocked.branch}" was not merged because another merge is already in progress.
48+Current unresolved files:
49+${files}
50+
51+Resolve the current merge first (remove <<<<, ====, >>>> markers), stage files with
52+\`git add <file>\`, run \`git merge --continue\`, then merge the deferred branch with
53+\`git merge --no-ff ${output.mergeBlocked.branch}\`.`;
54+ }
55+ return null;
2056 }
2157
2258 /**
src/tools/worktree.test.ts+212−0
@@ -0,0 +1,212 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import {
6+ MergeInProgressError,
7+ cleanupBranch,
8+ createWorktree,
9+ hasDirtyWorkingTree,
10+ isGitRepo,
11+ mergeWorktree,
12+ removeWorktree,
13+ syncDirtyStateToWorktree,
14+} from "./worktree.ts";
15+
16+function git(cwd: string, args: string[]): string {
17+ const proc = Bun.spawnSync(["git", ...args], {
18+ cwd,
19+ stdout: "pipe",
20+ stderr: "pipe",
21+ });
22+ if (proc.exitCode !== 0) {
23+ throw new Error(`git ${args.join(" ")} failed: ${proc.stderr.toString()}`);
24+ }
25+ return proc.stdout.toString().trim();
26+}
27+
28+function gitStatusLines(cwd: string): string[] {
29+ const output = git(cwd, ["status", "--porcelain", "-u"]);
30+ if (!output) return [];
31+ return output
32+ .split("\n")
33+ .filter((line) => line.length > 0)
34+ .sort();
35+}
36+
37+function makeRepo(): string {
38+ const dir = join(
39+ tmpdir(),
40+ `mc-worktree-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
41+ );
42+ mkdirSync(dir, { recursive: true });
43+ git(dir, ["init"]);
44+ git(dir, ["config", "user.email", "test@example.com"]);
45+ git(dir, ["config", "user.name", "Test"]);
46+ writeFileSync(join(dir, "README.md"), "hello\n");
47+ git(dir, ["add", "README.md"]);
48+ git(dir, ["commit", "-m", "init"]);
49+ return dir;
50+}
51+
52+describe("worktree helpers", () => {
53+ let repoDir = "";
54+ const extraDirs: string[] = [];
55+
56+ beforeEach(() => {
57+ repoDir = makeRepo();
58+ });
59+
60+ afterEach(() => {
61+ for (const dir of extraDirs.splice(0)) {
62+ rmSync(dir, { recursive: true, force: true });
63+ }
64+ rmSync(repoDir, { recursive: true, force: true });
65+ });
66+
67+ test("detects git and non-git directories", async () => {
68+ expect(await isGitRepo(repoDir)).toBe(true);
69+
70+ const nonGit = join(
71+ tmpdir(),
72+ `mc-worktree-nongit-${Date.now()}-${Math.random().toString(36).slice(2)}`,
73+ );
74+ extraDirs.push(nonGit);
75+ mkdirSync(nonGit, { recursive: true });
76+ expect(await isGitRepo(nonGit)).toBe(false);
77+ });
78+
79+ test("detects dirty working tree state", async () => {
80+ expect(await hasDirtyWorkingTree(repoDir)).toBe(false);
81+
82+ writeFileSync(join(repoDir, "untracked.txt"), "dirty\n");
83+ expect(await hasDirtyWorkingTree(repoDir)).toBe(true);
84+ });
85+
86+ test("syncs dirty tracked, staged, and untracked state into worktree", async () => {
87+ const branch = `mc-sub-dirty-${Date.now()}`;
88+ const wtPath = join(
89+ tmpdir(),
90+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
91+ );
92+ extraDirs.push(wtPath);
93+
94+ await createWorktree(repoDir, branch, wtPath);
95+
96+ writeFileSync(join(repoDir, "README.md"), "tracked but unstaged\n");
97+ writeFileSync(join(repoDir, "staged.txt"), "staged file\n");
98+ git(repoDir, ["add", "staged.txt"]);
99+ writeFileSync(join(repoDir, "untracked.txt"), "untracked file\n");
100+
101+ await syncDirtyStateToWorktree(repoDir, wtPath);
102+
103+ expect(await Bun.file(join(wtPath, "README.md")).text()).toBe(
104+ "tracked but unstaged\n",
105+ );
106+ expect(await Bun.file(join(wtPath, "staged.txt")).text()).toBe(
107+ "staged file\n",
108+ );
109+ expect(await Bun.file(join(wtPath, "untracked.txt")).text()).toBe(
110+ "untracked file\n",
111+ );
112+ expect(gitStatusLines(wtPath)).toEqual(gitStatusLines(repoDir));
113+
114+ await removeWorktree(repoDir, wtPath);
115+ await cleanupBranch(repoDir, branch);
116+ });
117+
118+ test("creates a worktree and merges successfully", async () => {
119+ const branch = `mc-sub-1-${Date.now()}`;
120+ const wtPath = join(
121+ tmpdir(),
122+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
123+ );
124+ extraDirs.push(wtPath);
125+
126+ await createWorktree(repoDir, branch, wtPath);
127+ writeFileSync(join(wtPath, "feature.txt"), "from branch\n");
128+ git(wtPath, ["add", "feature.txt"]);
129+ git(wtPath, ["commit", "-m", "feature"]);
130+
131+ const merge = await mergeWorktree(repoDir, branch);
132+ expect(merge).toEqual({ success: true });
133+ expect(await Bun.file(join(repoDir, "feature.txt")).text()).toBe(
134+ "from branch\n",
135+ );
136+
137+ await removeWorktree(repoDir, wtPath);
138+ await cleanupBranch(repoDir, branch);
139+ });
140+
141+ test("returns conflict files when merge conflicts", async () => {
142+ const branch = `mc-sub-2-${Date.now()}`;
143+ const wtPath = join(
144+ tmpdir(),
145+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
146+ );
147+ extraDirs.push(wtPath);
148+
149+ await createWorktree(repoDir, branch, wtPath);
150+
151+ writeFileSync(join(repoDir, "README.md"), "main change\n");
152+ git(repoDir, ["commit", "-am", "main change"]);
153+
154+ writeFileSync(join(wtPath, "README.md"), "branch change\n");
155+ git(wtPath, ["commit", "-am", "branch change"]);
156+
157+ const merge = await mergeWorktree(repoDir, branch);
158+ expect(merge.success).toBe(false);
159+ if (!merge.success) {
160+ expect(merge.conflictFiles).toContain("README.md");
161+ }
162+
163+ git(repoDir, ["merge", "--abort"]);
164+ await removeWorktree(repoDir, wtPath);
165+ await cleanupBranch(repoDir, branch);
166+ });
167+
168+ test("throws MergeInProgressError when another merge is already in progress", async () => {
169+ const branch1 = `mc-sub-3-${Date.now()}`;
170+ const branch2 = `mc-sub-4-${Date.now()}`;
171+ const wtPath1 = join(
172+ tmpdir(),
173+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
174+ );
175+ const wtPath2 = join(
176+ tmpdir(),
177+ `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
178+ );
179+ extraDirs.push(wtPath1, wtPath2);
180+
181+ await createWorktree(repoDir, branch1, wtPath1);
182+ await createWorktree(repoDir, branch2, wtPath2);
183+
184+ writeFileSync(join(repoDir, "README.md"), "main change\n");
185+ git(repoDir, ["commit", "-am", "main change"]);
186+
187+ writeFileSync(join(wtPath1, "README.md"), "branch one\n");
188+ git(wtPath1, ["commit", "-am", "branch one"]);
189+
190+ writeFileSync(join(wtPath2, "README.md"), "branch two\n");
191+ git(wtPath2, ["commit", "-am", "branch two"]);
192+
193+ const firstMerge = await mergeWorktree(repoDir, branch1);
194+ expect(firstMerge.success).toBe(false);
195+
196+ try {
197+ await mergeWorktree(repoDir, branch2);
198+ throw new Error("expected mergeWorktree to throw");
199+ } catch (error) {
200+ expect(error).toBeInstanceOf(MergeInProgressError);
201+ if (error instanceof MergeInProgressError) {
202+ expect(error.conflictFiles).toContain("README.md");
203+ }
204+ }
205+
206+ git(repoDir, ["merge", "--abort"]);
207+ await removeWorktree(repoDir, wtPath1);
208+ await removeWorktree(repoDir, wtPath2);
209+ await cleanupBranch(repoDir, branch1);
210+ await cleanupBranch(repoDir, branch2);
211+ });
212+});
src/tools/worktree.ts+247−0
@@ -0,0 +1,247 @@
1+import {
2+ chmodSync,
3+ copyFileSync,
4+ lstatSync,
5+ mkdirSync,
6+ mkdtempSync,
7+ readlinkSync,
8+ rmSync,
9+ symlinkSync,
10+ writeFileSync,
11+} from "node:fs";
12+import { tmpdir } from "node:os";
13+import { dirname, join } from "node:path";
14+
15+interface GitResult {
16+ stdout: string;
17+ stderr: string;
18+ exitCode: number;
19+}
20+
21+async function runGit(cwd: string, args: string[]): Promise<GitResult> {
22+ try {
23+ const proc = Bun.spawn(["git", ...args], {
24+ cwd,
25+ stdout: "pipe",
26+ stderr: "pipe",
27+ });
28+ const [stdout, stderr, exitCode] = await Promise.all([
29+ new Response(proc.stdout).text(),
30+ new Response(proc.stderr).text(),
31+ proc.exited,
32+ ]);
33+ return { stdout, stderr, exitCode };
34+ } catch {
35+ return { stdout: "", stderr: "failed to execute git", exitCode: -1 };
36+ }
37+}
38+
39+function gitError(action: string, detail: string): Error {
40+ return new Error(`${action}: ${detail || "unknown git error"}`);
41+}
42+
43+function splitNonEmptyLines(text: string): string[] {
44+ return text
45+ .split("\n")
46+ .map((line) => line.trim())
47+ .filter((line) => line.length > 0);
48+}
49+
50+async function listUnmergedFiles(cwd: string): Promise<string[]> {
51+ const conflictResult = await runGit(cwd, [
52+ "diff",
53+ "--name-only",
54+ "--diff-filter=U",
55+ ]);
56+ if (conflictResult.exitCode !== 0) return [];
57+ return splitNonEmptyLines(conflictResult.stdout);
58+}
59+
60+async function hasMergeInProgress(cwd: string): Promise<boolean> {
61+ const mergeHead = await runGit(cwd, [
62+ "rev-parse",
63+ "-q",
64+ "--verify",
65+ "MERGE_HEAD",
66+ ]);
67+ return mergeHead.exitCode === 0;
68+}
69+
70+export async function isGitRepo(cwd: string): Promise<boolean> {
71+ const result = await runGit(cwd, ["rev-parse", "--git-dir"]);
72+ return result.exitCode === 0;
73+}
74+
75+export async function hasDirtyWorkingTree(cwd: string): Promise<boolean> {
76+ const result = await runGit(cwd, ["status", "--porcelain", "-u"]);
77+ if (result.exitCode !== 0) return true;
78+ return result.stdout.trim().length > 0;
79+}
80+
81+function splitNullSeparated(text: string): string[] {
82+ return text.split("\0").filter((value) => value.length > 0);
83+}
84+
85+async function getRepoRoot(cwd: string): Promise<string> {
86+ const result = await runGit(cwd, ["rev-parse", "--show-toplevel"]);
87+ if (result.exitCode !== 0) {
88+ throw gitError(
89+ "Failed to resolve repository root",
90+ (result.stderr || result.stdout).trim(),
91+ );
92+ }
93+ return result.stdout.trim();
94+}
95+
96+async function applyPatch(
97+ cwd: string,
98+ patch: string,
99+ args: string[],
100+): Promise<void> {
101+ if (patch.trim().length === 0) return;
102+ const tempDir = mkdtempSync(join(tmpdir(), "mc-worktree-patch-"));
103+ const patchPath = join(tempDir, "changes.patch");
104+ try {
105+ writeFileSync(patchPath, patch);
106+ const result = await runGit(cwd, ["apply", ...args, patchPath]);
107+ if (result.exitCode !== 0) {
108+ throw gitError(
109+ "Failed to apply dirty-state patch to worktree",
110+ (result.stderr || result.stdout).trim(),
111+ );
112+ }
113+ } finally {
114+ rmSync(tempDir, { recursive: true, force: true });
115+ }
116+}
117+
118+function copyUntrackedPath(source: string, destination: string): void {
119+ const stat = lstatSync(source);
120+ mkdirSync(dirname(destination), { recursive: true });
121+ if (stat.isSymbolicLink()) {
122+ rmSync(destination, { recursive: true, force: true });
123+ symlinkSync(readlinkSync(source), destination);
124+ return;
125+ }
126+ copyFileSync(source, destination);
127+ chmodSync(destination, stat.mode);
128+}
129+
130+export async function syncDirtyStateToWorktree(
131+ mainCwd: string,
132+ worktreeCwd: string,
133+): Promise<void> {
134+ const [staged, unstaged, untracked, mainRoot, worktreeRoot] =
135+ await Promise.all([
136+ runGit(mainCwd, ["diff", "--binary", "--cached"]),
137+ runGit(mainCwd, ["diff", "--binary"]),
138+ runGit(mainCwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
139+ getRepoRoot(mainCwd),
140+ getRepoRoot(worktreeCwd),
141+ ]);
142+ if (staged.exitCode !== 0) {
143+ throw gitError(
144+ "Failed to read staged changes",
145+ (staged.stderr || staged.stdout).trim(),
146+ );
147+ }
148+ if (unstaged.exitCode !== 0) {
149+ throw gitError(
150+ "Failed to read unstaged changes",
151+ (unstaged.stderr || unstaged.stdout).trim(),
152+ );
153+ }
154+ if (untracked.exitCode !== 0) {
155+ throw gitError(
156+ "Failed to list untracked files",
157+ (untracked.stderr || untracked.stdout).trim(),
158+ );
159+ }
160+
161+ await applyPatch(worktreeRoot, staged.stdout, ["--index"]);
162+ await applyPatch(worktreeRoot, unstaged.stdout, []);
163+
164+ for (const relPath of splitNullSeparated(untracked.stdout)) {
165+ copyUntrackedPath(join(mainRoot, relPath), join(worktreeRoot, relPath));
166+ }
167+}
168+
169+export async function createWorktree(
170+ mainCwd: string,
171+ branch: string,
172+ path: string,
173+): Promise<string> {
174+ const result = await runGit(mainCwd, ["worktree", "add", path, "-b", branch]);
175+ if (result.exitCode !== 0) {
176+ throw gitError(
177+ `Failed to create worktree for branch "${branch}"`,
178+ (result.stderr || result.stdout).trim(),
179+ );
180+ }
181+ return path;
182+}
183+
184+export type MergeWorktreeResult =
185+ | { success: true }
186+ | { success: false; conflictFiles: string[] };
187+
188+export class MergeInProgressError extends Error {
189+ readonly conflictFiles: string[];
190+
191+ constructor(branch: string, conflictFiles: string[]) {
192+ super(
193+ `Cannot merge branch "${branch}" because another merge is already in progress. Resolve it first before merging this branch.`,
194+ );
195+ this.name = "MergeInProgressError";
196+ this.conflictFiles = conflictFiles;
197+ }
198+}
199+
200+export async function mergeWorktree(
201+ mainCwd: string,
202+ branch: string,
203+): Promise<MergeWorktreeResult> {
204+ if (await hasMergeInProgress(mainCwd)) {
205+ const conflictFiles = await listUnmergedFiles(mainCwd);
206+ throw new MergeInProgressError(branch, conflictFiles);
207+ }
208+
209+ const merge = await runGit(mainCwd, ["merge", "--no-ff", branch]);
210+ if (merge.exitCode === 0) return { success: true };
211+
212+ const conflictFiles = await listUnmergedFiles(mainCwd);
213+ if (conflictFiles.length > 0) {
214+ return { success: false, conflictFiles };
215+ }
216+
217+ throw gitError(
218+ `Failed to merge branch "${branch}"`,
219+ (merge.stderr || merge.stdout).trim(),
220+ );
221+}
222+
223+export async function removeWorktree(
224+ mainCwd: string,
225+ path: string,
226+): Promise<void> {
227+ const result = await runGit(mainCwd, ["worktree", "remove", "--force", path]);
228+ if (result.exitCode !== 0) {
229+ throw gitError(
230+ `Failed to remove worktree "${path}"`,
231+ (result.stderr || result.stdout).trim(),
232+ );
233+ }
234+}
235+
236+export async function cleanupBranch(
237+ mainCwd: string,
238+ branch: string,
239+): Promise<void> {
240+ const result = await runGit(mainCwd, ["branch", "-D", branch]);
241+ if (result.exitCode !== 0) {
242+ throw gitError(
243+ `Failed to delete branch "${branch}"`,
244+ (result.stderr || result.stdout).trim(),
245+ );
246+ }
247+}