xonecas.io
64875
Mc

mini-coder / commit 2fe1f44

refactor(subagent): remove worktree isolation

The worktree isolation feature was complex and buggy, often leading to broken states. This refactor removes the worktreeBranch and assertSubagentMerged logic, dropping worktree support entirely to simplify the subagent tool implementation and improve its reliability.

xonecas2026-03-11 2fe1f4488e65abda82bdc3ecfb3f11b411f59680 parent 920e277

9 files changed

TODO.md+0−11
@@ -1,13 +1,5 @@
11 # TODO
22
3-## Worktrees feature is not working as expected.
4-
5-Currently it completly breaks the subagent tool as the changes are discard when the subprocess exits. They are never consolidated with the current agents filesystem, essentially making subagents no-op always.
6-
7-Our worktrees implementation never worked correctly, and I think we need to remove it for now. Let's take the opportunity to simplify and refactor for better code readability and organization of the code.
8-
9----
10-
113 ## ESC cleared the whole last turn from memory
124
135 See the output bellow, once interrupted and prompted about it's actions, the assitant was not aware of any previous input from the user. Notice the context numbers also reset to 0%.
@@ -64,6 +56,3 @@ We need to do research first, but maybe we can leverage the hooks feature to ach
6456 ## Deferred fixes
6557
6658 - model-info: in `resolveFromProviderRow`, when canonical capability exists but `contextWindow` is null, fall back to provider row context (`capability.contextWindow ?? row.contextWindow`).
67-- Worktrees share bun lockfile and node_modules. Question this choice, is this really a good idea, or just an opportunity for things to go wrong?
68-- `subagent-runner.ts`: `Bun.file(proc.stdio[3] as unknown as number).text()` — the double-cast signals a type mismatch. Investigate whether `new Response(proc.stdio[3]).text()` is more correct and whether the current form breaks silently across Bun versions.
69-- `worktree.ts` tracked-change sync: `copyFileSync` turns symlinks into regular files. Preserve symlinks via `lstatSync(...).isSymbolicLink()` + `readlinkSync`/`symlinkSync` (or restore git-native apply for tracked changes).
mini-coder-idea.md+1−1
@@ -28,7 +28,7 @@ conventions and not introduce more specs. (`.agents` / `AGENTS.md`, while also s
2828
2929 - `glob`, `grep`, `read`, `replace`,`insert`, `create`, `shell`, and `subagent` tools for LLMs
3030 - Optional `webSearch` and `webContent` tools when `EXA_API_KEY` is set.
31-- `subagent` tool spawns a fresh `mc` subprocess — full capability parity with the main agent, support for recursive subagents (up to 10 levels), and git worktree isolation/merge-back when available. Custom agents and custom commands from `.agents` and `.claude` are supported in subagents.
31+- `subagent` tool spawns a fresh `mc` subprocess — full capability parity with the main agent, support for recursive subagents (up to 10 levels). Custom agents and custom commands from `.agents` and `.claude` are supported in subagents.
3232 - tool hooks support for supported built-in tools
3333 - Commands in CLI prompt:
3434 - `/model` command allows the user to pick a model from connected providers. As well as thinking effort for the model if supported. Selection persists accross sessions.
src/agent/subagent-runner.ts+5−62
@@ -1,9 +1,4 @@
11 import type { SubagentOutput, SubagentSummary } from "../tools/subagent.ts";
2-import {
3- cleanupBranch,
4- MergeInProgressError,
5- mergeWorktree,
6-} from "../tools/worktree.ts";
72
83 /**
94 * Resolve the command to invoke a new `mc` subprocess.
@@ -39,11 +34,8 @@ export function createSubagentRunner(
3934 cwd: string,
4035 getCurrentModel: () => string,
4136 ) {
42- // Active subprocesses — maps proc to branch name (if any) for interrupt cleanup.
43- const activeProcs = new Map<
44- ReturnType<typeof Bun.spawn>,
45- string | undefined
46- >();
37+ // Active subprocesses for interrupt cleanup.
38+ const activeProcs = new Set<ReturnType<typeof Bun.spawn>>();
4739
4840 // Depth is injected by the parent subprocess via MC_SUBAGENT_DEPTH env var.
4941 const subagentDepth = Number.parseInt(
@@ -51,42 +43,10 @@ export function createSubagentRunner(
5143 10,
5244 );
5345
54- // Merge lock: serialises merge operations from concurrent subagents.
55- let mergeLockTail = Promise.resolve();
56-
57- const mergeSubagentBranch = async (
58- branch: string,
59- ): Promise<{ mergeConflicts?: string[] }> => {
60- const prev = mergeLockTail;
61- let releaseLock!: () => void;
62- mergeLockTail = new Promise((resolve) => {
63- releaseLock = resolve;
64- });
65- try {
66- await prev;
67- const result = await mergeWorktree(cwd, branch);
68- if (result.success) {
69- await cleanupBranch(cwd, branch);
70- return {};
71- }
72- // Merge produced conflicts — leave branch for user to resolve.
73- return { mergeConflicts: result.conflictFiles };
74- } catch (err) {
75- if (err instanceof MergeInProgressError) {
76- // Another merge is in progress — return its conflict files.
77- return { mergeConflicts: err.conflictFiles };
78- }
79- throw err;
80- } finally {
81- releaseLock();
82- }
83- };
84-
8546 const runSubagent = async (
8647 prompt: string,
8748 agentName?: string,
8849 modelOverride?: string,
89- _parentLabel?: string,
9050 ): Promise<SubagentOutput> => {
9151 if (subagentDepth >= MAX_SUBAGENT_DEPTH) {
9252 throw new Error(
@@ -96,9 +56,6 @@ export function createSubagentRunner(
9656 }
9757
9858 const model = modelOverride ?? getCurrentModel();
99- // Parent generates the branch name so it can clean it up on interrupt.
100- const laneId = crypto.randomUUID().slice(0, 8);
101- const worktreeBranch = `mc-sub-${laneId}`;
10259 const cmd = [
10360 ...getMcCommand(),
10461 "--subagent",
@@ -108,8 +65,6 @@ export function createSubagentRunner(
10865 model,
10966 "--output-fd",
11067 "3",
111- "--worktree-branch",
112- worktreeBranch,
11368 ...(agentName ? ["--agent", agentName] : []),
11469 prompt,
11570 ];
@@ -123,11 +78,11 @@ export function createSubagentRunner(
12378 stdio: ["ignore", "inherit", "inherit", "pipe"],
12479 });
12580
126- activeProcs.set(proc, worktreeBranch);
81+ activeProcs.add(proc);
12782
12883 try {
12984 const [text] = await Promise.all([
130- Bun.file(proc.stdio[3] as unknown as number).text(),
85+ Bun.file(proc.stdio[3] as number).text(),
13186 proc.exited,
13287 ]);
13388
@@ -162,13 +117,6 @@ export function createSubagentRunner(
162117 outputTokens: parsed.outputTokens,
163118 };
164119
165- if (parsed.worktreeBranch) {
166- const mergeResult = await mergeSubagentBranch(parsed.worktreeBranch);
167- if (mergeResult.mergeConflicts) {
168- output.mergeConflicts = mergeResult.mergeConflicts;
169- }
170- }
171-
172120 return output;
173121 } finally {
174122 activeProcs.delete(proc);
@@ -178,17 +126,12 @@ export function createSubagentRunner(
178126 return {
179127 runSubagent,
180128 killAll: () => {
181- for (const [proc, branch] of activeProcs) {
129+ for (const proc of activeProcs) {
182130 try {
183131 proc.kill("SIGTERM");
184132 } catch {
185133 // Process may have already exited.
186134 }
187- if (branch) {
188- // Wait for the subprocess to exit (so it can remove its worktree dir)
189- // before deleting the branch — git refuses to delete a checked-out branch.
190- proc.exited.then(() => cleanupBranch(cwd, branch)).catch(() => {});
191- }
192135 }
193136 },
194137 };
src/agent/tools.ts+5−21
@@ -25,11 +25,7 @@ import type { ReplaceToolOutput } from "../tools/replace.ts";
2525 import { replaceTool } from "../tools/replace.ts";
2626 import type { ShellOutput } from "../tools/shell.ts";
2727 import { shellTool } from "../tools/shell.ts";
28-import {
29- assertSubagentMerged,
30- createSubagentTool,
31- type SubagentOutput,
32-} from "../tools/subagent.ts";
28+import { createSubagentTool, type SubagentOutput } from "../tools/subagent.ts";
3329 import {
3430 finalizeWriteResult,
3531 stripWriteResultMeta,
@@ -123,12 +119,10 @@ export function buildToolSet(opts: {
123119 prompt: string,
124120 agentName?: string,
125121 modelOverride?: string,
126- parentLabel?: string,
127122 ) => Promise<SubagentOutput>;
128123
129124 onHook: (toolName: string, scriptPath: string, success: boolean) => void;
130125 availableAgents: ReadonlyMap<string, { description: string }>;
131- parentLabel?: string;
132126 }): ToolDef[] {
133127 const { cwd, onHook } = opts;
134128 const lookupHook = createHookCache(HOOKABLE_TOOLS, cwd);
@@ -210,20 +204,10 @@ export function buildToolSet(opts: {
210204 (result, input) => hookEnvForShell(result, input, cwd),
211205 onHook,
212206 ) as ToolDef,
213- createSubagentTool(
214- async (prompt, agentName, parentLabel) => {
215- const output = await opts.runSubagent(
216- prompt,
217- agentName,
218- undefined,
219- parentLabel,
220- );
221- assertSubagentMerged(output);
222- return output;
223- },
224- opts.availableAgents,
225- opts.parentLabel,
226- ) as ToolDef,
207+ createSubagentTool(async (prompt, agentName) => {
208+ const output = await opts.runSubagent(prompt, agentName, undefined);
209+ return output;
210+ }, opts.availableAgents) as ToolDef,
227211 ];
228212
229213 if (process.env.EXA_API_KEY) {
src/cli/commands.ts+1−5
@@ -7,10 +7,7 @@ import {
77 listMcpServers,
88 upsertMcpServer,
99 } from "../session/db/index.ts";
10-import {
11- assertSubagentMerged,
12- type SubagentOutput,
13-} from "../tools/subagent.ts";
10+import type { SubagentOutput } from "../tools/subagent.ts";
1411
1512 import { loadAgents } from "./agents.ts";
1613 import {
@@ -456,7 +453,6 @@ async function handleCustomCommand(
456453 try {
457454 ctx.startSpinner("subagent");
458455 const output = await ctx.runSubagent(prompt, cmd.agent, cmd.model);
459- assertSubagentMerged(output);
460456
461457 write(renderMarkdown(output.result));
462458 writeln();
src/index.ts+3−62
@@ -1,6 +1,6 @@
11 #!/usr/bin/env bun
22 import { existsSync, mkdirSync, writeFileSync, writeSync } from "node:fs";
3-import { homedir, tmpdir } from "node:os";
3+import { homedir } from "node:os";
44 import { join } from "node:path";
55
66 import * as c from "yoctocolors";
@@ -30,13 +30,6 @@ import {
3030 getPreferredToolResultPayloadCapBytes,
3131 } from "./session/db/index.ts";
3232 import { getMostRecentSession, printSessionList } from "./session/manager.ts";
33-import {
34- applyParentChanges,
35- createWorktree,
36- initializeWorktree,
37- isGitRepo,
38- removeWorktree,
39-} from "./tools/worktree.ts";
4033
4134 // Register terminal cleanup handlers as early as possible so the cursor is
4235 // always restored even if the process crashes or is killed.
@@ -59,7 +52,6 @@ interface CliArgs {
5952 subagent: boolean;
6053 agentName: string | null;
6154 outputFd: number | null;
62- worktreeBranch: string | null;
6355 }
6456
6557 function parseArgs(argv: string[]): CliArgs {
@@ -74,7 +66,6 @@ function parseArgs(argv: string[]): CliArgs {
7466 subagent: false,
7567 agentName: null,
7668 outputFd: null,
77- worktreeBranch: null,
7869 };
7970
8071 const positional: string[] = [];
@@ -116,9 +107,6 @@ function parseArgs(argv: string[]): CliArgs {
116107 if (!Number.isNaN(fd)) args.outputFd = fd;
117108 break;
118109 }
119- case "--worktree-branch":
120- args.worktreeBranch = argv[++i] ?? null;
121- break;
122110 default:
123111 if (!arg.startsWith("-")) positional.push(arg);
124112 }
@@ -256,51 +244,10 @@ async function main(): Promise<void> {
256244 if (agentConfig.model) modelOverride = agentConfig.model;
257245 }
258246
259- // Worktree lifecycle: create before run, remove dir after (keep branch for parent to merge).
260- let worktreePath: string | undefined;
261- // Use the branch name the parent assigned (so it can clean up on interrupt).
262- let worktreeBranch: string | undefined = args.worktreeBranch ?? undefined;
263- let runCwd = parentCwd;
264-
265- if (await isGitRepo(parentCwd)) {
266- if (!worktreeBranch) {
267- // Fallback: generate our own if the parent didn't pass one (shouldn't happen in practice).
268- worktreeBranch = `mc-sub-${crypto.randomUUID().slice(0, 8)}`;
269- }
270- worktreePath = join(tmpdir(), worktreeBranch);
271- try {
272- await createWorktree(parentCwd, worktreeBranch, worktreePath);
273- await initializeWorktree(parentCwd, worktreePath);
274- await applyParentChanges(parentCwd, worktreePath);
275- runCwd = worktreePath;
276- } catch {
277- // Worktree creation failed — fall back to running in the original cwd.
278- worktreeBranch = undefined;
279- worktreePath = undefined;
280- }
281- }
282-
283- // SIGTERM handler: clean up worktree directory only; leave branch for parent to discard.
284- process.on("SIGTERM", () => {
285- if (worktreePath) {
286- Bun.spawnSync(["git", "worktree", "remove", "--force", worktreePath], {
287- cwd: parentCwd,
288- });
289- }
290- process.exit(1);
291- });
292-
293- const cleanupWorktree = async (): Promise<void> => {
294- if (worktreePath) {
295- await removeWorktree(parentCwd, worktreePath).catch(() => {});
296- worktreePath = undefined;
297- }
298- };
299-
300247 try {
301248 const summary = await runAgent({
302249 model: modelOverride,
303- cwd: runCwd,
250+ cwd: parentCwd,
304251 initialThinkingEffort: getPreferredThinkingEffort(),
305252 initialShowReasoning: getPreferredShowReasoning(),
306253 initialPruningMode: getPreferredContextPruningMode(),
@@ -312,17 +259,11 @@ async function main(): Promise<void> {
312259 ...(agentSystemPrompt ? { agentSystemPrompt } : {}),
313260 });
314261
315- await cleanupWorktree();
316-
317262 if (args.outputFd !== null && summary) {
318- const payload = worktreeBranch
319- ? { ...summary, worktreeBranch }
320- : summary;
321- const json = `${JSON.stringify(payload)}\n`;
263+ const json = `${JSON.stringify(summary)}\n`;
322264 writeSync(args.outputFd, Buffer.from(json));
323265 }
324266 } catch (err) {
325- await cleanupWorktree();
326267 if (args.outputFd !== null) {
327268 const json = `${JSON.stringify({ error: String(err) })}\n`;
328269 writeSync(args.outputFd, Buffer.from(json));
src/tools/subagent.ts+2−18
@@ -17,23 +17,12 @@ export interface SubagentSummary {
1717 result: string;
1818 inputTokens: number;
1919 outputTokens: number;
20- worktreeBranch?: string;
2120 }
2221
2322 export interface SubagentOutput {
2423 result: string;
2524 inputTokens: number;
2625 outputTokens: number;
27- mergeConflicts?: string[];
28-}
29-
30-export function assertSubagentMerged(output: SubagentOutput): void {
31- if (output.mergeConflicts?.length) {
32- const files = output.mergeConflicts.map((f) => ` - ${f}`).join("\n");
33- throw new Error(
34- `⚠ Merge conflict: subagent changes have conflicts in these files:\n${files}\n\nResolve the conflicts (remove <<<<, ====, >>>> markers), stage the files with \`git add <file>\`, then run \`git merge --continue\` to complete the merge.`,
35- );
36- }
3726 }
3827
3928 /**
@@ -43,13 +32,8 @@ export function assertSubagentMerged(output: SubagentOutput): void {
4332 * the agent without creating a circular import.
4433 */
4534 export function createSubagentTool(
46- runSubagent: (
47- prompt: string,
48- agentName?: string,
49- parentLabel?: string,
50- ) => Promise<SubagentOutput>,
35+ runSubagent: (prompt: string, agentName?: string) => Promise<SubagentOutput>,
5136 availableAgents: ReadonlyMap<string, { description: string }>,
52- parentLabel?: string,
5337 ): ToolDef<SubagentInput, SubagentOutput> {
5438 const agentSection =
5539 availableAgents.size > 0
@@ -60,7 +44,7 @@ export function createSubagentTool(
6044 description: `Spawn a sub-agent to handle a focused subtask.${agentSection}`,
6145 schema: SubagentInput,
6246 execute: async (input) => {
63- return runSubagent(input.prompt, input.agentName, parentLabel);
47+ return runSubagent(input.prompt, input.agentName);
6448 },
6549 };
6650 }
src/tools/worktree.test.ts+0−288
@@ -1,288 +0,0 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import {
3- existsSync,
4- lstatSync,
5- mkdirSync,
6- realpathSync,
7- rmSync,
8- writeFileSync,
9-} from "node:fs";
10-import { tmpdir } from "node:os";
11-import { join } from "node:path";
12-import {
13- applyParentChanges,
14- cleanupBranch,
15- createWorktree,
16- hasDirtyWorkingTree,
17- initializeWorktree,
18- isGitRepo,
19- MergeInProgressError,
20- mergeWorktree,
21- removeWorktree,
22-} from "./worktree.ts";
23-
24-function git(cwd: string, args: string[]): string {
25- const proc = Bun.spawnSync(["git", ...args], {
26- cwd,
27- stdout: "pipe",
28- stderr: "pipe",
29- });
30- if (proc.exitCode !== 0) {
31- throw new Error(`git ${args.join(" ")} failed: ${proc.stderr.toString()}`);
32- }
33- return proc.stdout.toString().trim();
34-}
35-
36-function makeRepo(): string {
37- const dir = join(
38- tmpdir(),
39- `mc-worktree-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
40- );
41- mkdirSync(dir, { recursive: true });
42- git(dir, ["init"]);
43- git(dir, ["config", "user.email", "test@example.com"]);
44- git(dir, ["config", "user.name", "Test"]);
45- writeFileSync(join(dir, "README.md"), "hello\n");
46- git(dir, ["add", "README.md"]);
47- git(dir, ["commit", "-m", "init"]);
48- return dir;
49-}
50-
51-describe("worktree helpers", () => {
52- let repoDir = "";
53- const extraDirs: string[] = [];
54-
55- beforeEach(() => {
56- repoDir = makeRepo();
57- });
58-
59- afterEach(() => {
60- for (const dir of extraDirs.splice(0)) {
61- rmSync(dir, { recursive: true, force: true });
62- }
63- rmSync(repoDir, { recursive: true, force: true });
64- });
65-
66- function makeWorktreeDir(name: string) {
67- const branch = `mc-sub-${name}-${Date.now()}`;
68- const wtPath = join(
69- tmpdir(),
70- `mc-wt-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
71- );
72- extraDirs.push(wtPath);
73- return { branch, wtPath };
74- }
75-
76- test("detects git and non-git directories", async () => {
77- expect(await isGitRepo(repoDir)).toBe(true);
78-
79- const nonGit = join(
80- tmpdir(),
81- `mc-worktree-nongit-${Date.now()}-${Math.random().toString(36).slice(2)}`,
82- );
83- extraDirs.push(nonGit);
84- mkdirSync(nonGit, { recursive: true });
85- expect(await isGitRepo(nonGit)).toBe(false);
86- });
87-
88- test("detects dirty working tree state", async () => {
89- expect(await hasDirtyWorkingTree(repoDir)).toBe(false);
90-
91- writeFileSync(join(repoDir, "untracked.txt"), "dirty\n");
92- expect(await hasDirtyWorkingTree(repoDir)).toBe(true);
93- });
94-
95- test("initializes bun dependencies in worktree", async () => {
96- const { branch, wtPath } = makeWorktreeDir("init");
97-
98- writeFileSync(join(repoDir, "package.json"), "{}\n");
99- writeFileSync(join(repoDir, "bun.lock"), "lock\n");
100- mkdirSync(join(repoDir, "node_modules", "bun-types"), { recursive: true });
101- writeFileSync(
102- join(repoDir, "node_modules", "bun-types", "index.d.ts"),
103- "\n",
104- );
105-
106- await createWorktree(repoDir, branch, wtPath);
107- await initializeWorktree(repoDir, wtPath);
108-
109- expect(await Bun.file(join(wtPath, "bun.lock")).text()).toBe("lock\n");
110- expect(realpathSync(join(wtPath, "node_modules"))).toBe(
111- realpathSync(join(repoDir, "node_modules")),
112- );
113- expect(lstatSync(join(wtPath, "node_modules")).isSymbolicLink()).toBe(true);
114-
115- await removeWorktree(repoDir, wtPath);
116- await cleanupBranch(repoDir, branch);
117- });
118-
119- test("creates a worktree and merges successfully", async () => {
120- const { branch, wtPath } = makeWorktreeDir("1");
121-
122- await createWorktree(repoDir, branch, wtPath);
123- writeFileSync(join(wtPath, "feature.txt"), "from branch\n");
124- git(wtPath, ["add", "feature.txt"]);
125- git(wtPath, ["commit", "-m", "feature"]);
126-
127- const merge = await mergeWorktree(repoDir, branch);
128- expect(merge).toEqual({ success: true });
129- expect(await Bun.file(join(repoDir, "feature.txt")).text()).toBe(
130- "from branch\n",
131- );
132-
133- await removeWorktree(repoDir, wtPath);
134- await cleanupBranch(repoDir, branch);
135- });
136-
137- test("returns conflict files when merge conflicts", async () => {
138- const { branch, wtPath } = makeWorktreeDir("2");
139-
140- await createWorktree(repoDir, branch, wtPath);
141-
142- writeFileSync(join(repoDir, "README.md"), "main change\n");
143- git(repoDir, ["commit", "-am", "main change"]);
144-
145- writeFileSync(join(wtPath, "README.md"), "branch change\n");
146- git(wtPath, ["commit", "-am", "branch change"]);
147-
148- const merge = await mergeWorktree(repoDir, branch);
149- expect(merge.success).toBe(false);
150- if (!merge.success) {
151- expect(merge.conflictFiles).toContain("README.md");
152- }
153-
154- git(repoDir, ["merge", "--abort"]);
155- await removeWorktree(repoDir, wtPath);
156- await cleanupBranch(repoDir, branch);
157- });
158-
159- test("throws MergeInProgressError when another merge is already in progress", async () => {
160- const { branch: branch1, wtPath: wtPath1 } = makeWorktreeDir("3");
161- const { branch: branch2, wtPath: wtPath2 } = makeWorktreeDir("4");
162-
163- await createWorktree(repoDir, branch1, wtPath1);
164- await createWorktree(repoDir, branch2, wtPath2);
165-
166- writeFileSync(join(repoDir, "README.md"), "main change\n");
167- git(repoDir, ["commit", "-am", "main change"]);
168-
169- writeFileSync(join(wtPath1, "README.md"), "branch one\n");
170- git(wtPath1, ["commit", "-am", "branch one"]);
171-
172- writeFileSync(join(wtPath2, "README.md"), "branch two\n");
173- git(wtPath2, ["commit", "-am", "branch two"]);
174-
175- const firstMerge = await mergeWorktree(repoDir, branch1);
176- expect(firstMerge.success).toBe(false);
177-
178- try {
179- await mergeWorktree(repoDir, branch2);
180- throw new Error("expected mergeWorktree to throw");
181- } catch (error) {
182- expect(error).toBeInstanceOf(MergeInProgressError);
183- if (error instanceof MergeInProgressError) {
184- expect(error.conflictFiles).toContain("README.md");
185- }
186- }
187-
188- git(repoDir, ["merge", "--abort"]);
189- await removeWorktree(repoDir, wtPath1);
190- await removeWorktree(repoDir, wtPath2);
191- await cleanupBranch(repoDir, branch1);
192- await cleanupBranch(repoDir, branch2);
193- });
194-
195- test("applyParentChanges propagates unstaged tracked changes", async () => {
196- const { branch, wtPath } = makeWorktreeDir("apply-unstaged");
197- await createWorktree(repoDir, branch, wtPath);
198-
199- writeFileSync(join(repoDir, "README.md"), "unstaged change\n");
200-
201- await applyParentChanges(repoDir, wtPath);
202-
203- expect(await Bun.file(join(wtPath, "README.md")).text()).toBe(
204- "unstaged change\n",
205- );
206-
207- await removeWorktree(repoDir, wtPath);
208- await cleanupBranch(repoDir, branch);
209- });
210-
211- test("applyParentChanges propagates staged changes", async () => {
212- const { branch, wtPath } = makeWorktreeDir("apply-staged");
213- await createWorktree(repoDir, branch, wtPath);
214-
215- writeFileSync(join(repoDir, "README.md"), "staged change\n");
216- git(repoDir, ["add", "README.md"]);
217-
218- await applyParentChanges(repoDir, wtPath);
219-
220- expect(await Bun.file(join(wtPath, "README.md")).text()).toBe(
221- "staged change\n",
222- );
223-
224- await removeWorktree(repoDir, wtPath);
225- await cleanupBranch(repoDir, branch);
226- });
227-
228- test("applyParentChanges copies untracked new files", async () => {
229- const { branch, wtPath } = makeWorktreeDir("apply-untracked");
230- await createWorktree(repoDir, branch, wtPath);
231-
232- writeFileSync(join(repoDir, "new-file.ts"), "export const x = 1;\n");
233-
234- await applyParentChanges(repoDir, wtPath);
235-
236- expect(await Bun.file(join(wtPath, "new-file.ts")).text()).toBe(
237- "export const x = 1;\n",
238- );
239-
240- await removeWorktree(repoDir, wtPath);
241- await cleanupBranch(repoDir, branch);
242- });
243-
244- test("applyParentChanges propagates tracked renames", async () => {
245- const { branch, wtPath } = makeWorktreeDir("apply-rename");
246- await createWorktree(repoDir, branch, wtPath);
247-
248- git(repoDir, ["mv", "README.md", "GUIDE.md"]);
249-
250- await applyParentChanges(repoDir, wtPath);
251-
252- expect(await Bun.file(join(wtPath, "GUIDE.md")).text()).toBe("hello\n");
253- expect(existsSync(join(wtPath, "README.md"))).toBe(false);
254-
255- await removeWorktree(repoDir, wtPath);
256- await cleanupBranch(repoDir, branch);
257- });
258-
259- test("applyParentChanges skips untracked node_modules contents", async () => {
260- const { branch, wtPath } = makeWorktreeDir("apply-node-modules");
261- await createWorktree(repoDir, branch, wtPath);
262-
263- mkdirSync(join(repoDir, "node_modules", "fake"), { recursive: true });
264- writeFileSync(
265- join(repoDir, "node_modules", "fake", "index.js"),
266- "module.exports = 1;\n",
267- );
268-
269- await applyParentChanges(repoDir, wtPath);
270-
271- expect(existsSync(join(wtPath, "node_modules", "fake", "index.js"))).toBe(
272- false,
273- );
274-
275- await removeWorktree(repoDir, wtPath);
276- await cleanupBranch(repoDir, branch);
277- });
278-
279- test("applyParentChanges no-ops cleanly on a clean tree", async () => {
280- const { branch, wtPath } = makeWorktreeDir("apply-clean");
281- await createWorktree(repoDir, branch, wtPath);
282-
283- await expect(applyParentChanges(repoDir, wtPath)).resolves.toBeUndefined();
284-
285- await removeWorktree(repoDir, wtPath);
286- await cleanupBranch(repoDir, branch);
287- });
288-});
src/tools/worktree.ts+0−296
@@ -1,296 +0,0 @@
1-import {
2- copyFileSync,
3- existsSync,
4- mkdirSync,
5- rmSync,
6- symlinkSync,
7-} from "node:fs";
8-import { dirname, join } from "node:path";
9-
10-interface GitResult {
11- stdout: string;
12- stderr: string;
13- exitCode: number;
14-}
15-
16-async function runGit(cwd: string, args: string[]): Promise<GitResult> {
17- try {
18- const proc = Bun.spawn(["git", ...args], {
19- cwd,
20- stdout: "pipe",
21- stderr: "pipe",
22- });
23- const [stdout, stderr, exitCode] = await Promise.all([
24- new Response(proc.stdout).text(),
25- new Response(proc.stderr).text(),
26- proc.exited,
27- ]);
28- return { stdout, stderr, exitCode };
29- } catch {
30- return { stdout: "", stderr: "failed to execute git", exitCode: -1 };
31- }
32-}
33-
34-function gitError(action: string, detail: string): Error {
35- return new Error(`${action}: ${detail || "unknown git error"}`);
36-}
37-
38-function splitNonEmptyLines(text: string): string[] {
39- return text
40- .split("\n")
41- .map((line) => line.trim())
42- .filter((line) => line.length > 0);
43-}
44-
45-async function listUnmergedFiles(cwd: string): Promise<string[]> {
46- const conflictResult = await runGit(cwd, [
47- "diff",
48- "--name-only",
49- "--diff-filter=U",
50- ]);
51- if (conflictResult.exitCode !== 0) return [];
52- return splitNonEmptyLines(conflictResult.stdout);
53-}
54-
55-async function hasMergeInProgress(cwd: string): Promise<boolean> {
56- const mergeHead = await runGit(cwd, [
57- "rev-parse",
58- "-q",
59- "--verify",
60- "MERGE_HEAD",
61- ]);
62- return mergeHead.exitCode === 0;
63-}
64-
65-export async function isGitRepo(cwd: string): Promise<boolean> {
66- const result = await runGit(cwd, ["rev-parse", "--git-dir"]);
67- return result.exitCode === 0;
68-}
69-
70-export async function hasDirtyWorkingTree(cwd: string): Promise<boolean> {
71- const result = await runGit(cwd, ["status", "--porcelain", "-u"]);
72- if (result.exitCode !== 0) return true;
73- return result.stdout.trim().length > 0;
74-}
75-
76-async function getRepoRoot(cwd: string): Promise<string> {
77- const result = await runGit(cwd, ["rev-parse", "--show-toplevel"]);
78- if (result.exitCode !== 0) {
79- throw gitError(
80- "Failed to resolve repository root",
81- (result.stderr || result.stdout).trim(),
82- );
83- }
84- return result.stdout.trim();
85-}
86-function copyFileIfMissing(source: string, destination: string): void {
87- if (!existsSync(source) || existsSync(destination)) return;
88- mkdirSync(dirname(destination), { recursive: true });
89- copyFileSync(source, destination);
90-}
91-
92-function linkDirectoryIfMissing(source: string, destination: string): void {
93- if (!existsSync(source) || existsSync(destination)) return;
94- mkdirSync(dirname(destination), { recursive: true });
95- symlinkSync(
96- source,
97- destination,
98- process.platform === "win32" ? "junction" : "dir",
99- );
100-}
101-
102-export async function initializeWorktree(
103- mainCwd: string,
104- worktreeCwd: string,
105-): Promise<void> {
106- const [mainRoot, worktreeRoot] = await Promise.all([
107- getRepoRoot(mainCwd),
108- getRepoRoot(worktreeCwd),
109- ]);
110- if (!existsSync(join(mainRoot, "package.json"))) return;
111-
112- for (const lockfile of ["bun.lock", "bun.lockb"]) {
113- copyFileIfMissing(join(mainRoot, lockfile), join(worktreeRoot, lockfile));
114- }
115-
116- linkDirectoryIfMissing(
117- join(mainRoot, "node_modules"),
118- join(worktreeRoot, "node_modules"),
119- );
120-}
121-
122-export async function createWorktree(
123- mainCwd: string,
124- branch: string,
125- path: string,
126-): Promise<string> {
127- const result = await runGit(mainCwd, ["worktree", "add", path, "-b", branch]);
128- if (result.exitCode !== 0) {
129- throw gitError(
130- `Failed to create worktree for branch "${branch}"`,
131- (result.stderr || result.stdout).trim(),
132- );
133- }
134- return path;
135-}
136-
137-type MergeWorktreeResult =
138- | { success: true }
139- | { success: false; conflictFiles: string[] };
140-
141-export class MergeInProgressError extends Error {
142- readonly conflictFiles: string[];
143-
144- constructor(branch: string, conflictFiles: string[]) {
145- super(
146- `Cannot merge branch "${branch}" because another merge is already in progress. Resolve it first before merging this branch.`,
147- );
148- this.name = "MergeInProgressError";
149- this.conflictFiles = conflictFiles;
150- }
151-}
152-
153-export async function mergeWorktree(
154- mainCwd: string,
155- branch: string,
156-): Promise<MergeWorktreeResult> {
157- if (await hasMergeInProgress(mainCwd)) {
158- const conflictFiles = await listUnmergedFiles(mainCwd);
159- throw new MergeInProgressError(branch, conflictFiles);
160- }
161-
162- const merge = await runGit(mainCwd, ["merge", "--no-ff", branch]);
163- if (merge.exitCode === 0) return { success: true };
164-
165- const conflictFiles = await listUnmergedFiles(mainCwd);
166- if (conflictFiles.length > 0) {
167- return { success: false, conflictFiles };
168- }
169-
170- throw gitError(
171- `Failed to merge branch "${branch}"`,
172- (merge.stderr || merge.stdout).trim(),
173- );
174-}
175-
176-export async function removeWorktree(
177- mainCwd: string,
178- path: string,
179-): Promise<void> {
180- const result = await runGit(mainCwd, ["worktree", "remove", "--force", path]);
181- if (result.exitCode !== 0) {
182- throw gitError(
183- `Failed to remove worktree "${path}"`,
184- (result.stderr || result.stdout).trim(),
185- );
186- }
187-}
188-
189-export async function cleanupBranch(
190- mainCwd: string,
191- branch: string,
192-): Promise<void> {
193- const result = await runGit(mainCwd, ["branch", "-D", branch]);
194- if (result.exitCode !== 0) {
195- throw gitError(
196- `Failed to delete branch "${branch}"`,
197- (result.stderr || result.stdout).trim(),
198- );
199- }
200-}
201-
202-/**
203- * Copy all working-tree changes from the main repo into a freshly-created
204- * worktree so the subagent sees current unstaged/staged progress.
205- *
206- * Two classes of change are propagated:
207- * 1. Tracked modifications (staged + unstaged) — synced from `git diff --name-status HEAD`.
208- * 2. Untracked, non-ignored new files — copied verbatim.
209- *
210- * Errors are silently swallowed so a worktree setup failure never blocks the
211- * subagent; it will simply run without the parent's in-progress changes.
212- */
213-function shouldSkipUntrackedPath(path: string): boolean {
214- return path === "node_modules" || path.startsWith("node_modules/");
215-}
216-
217-async function syncTrackedChanges(
218- mainRoot: string,
219- worktreeRoot: string,
220-): Promise<void> {
221- const trackedResult = await runGit(mainRoot, [
222- "diff",
223- "--name-status",
224- "-M",
225- "HEAD",
226- ]);
227- if (trackedResult.exitCode !== 0) return;
228-
229- for (const line of splitNonEmptyLines(trackedResult.stdout)) {
230- const [statusToken, firstPath, secondPath] = line.split("\t");
231- const status = statusToken?.trim() ?? "";
232- if (!status || !firstPath) continue;
233-
234- if (status.startsWith("R") || status.startsWith("C")) {
235- if (!secondPath) continue;
236- const src = join(mainRoot, secondPath);
237- const dst = join(worktreeRoot, secondPath);
238- if (existsSync(src)) {
239- mkdirSync(dirname(dst), { recursive: true });
240- copyFileSync(src, dst);
241- }
242- if (status.startsWith("R")) {
243- rmSync(join(worktreeRoot, firstPath), { force: true });
244- }
245- continue;
246- }
247-
248- if (status.startsWith("D")) {
249- rmSync(join(worktreeRoot, firstPath), { force: true });
250- continue;
251- }
252-
253- const src = join(mainRoot, firstPath);
254- const dst = join(worktreeRoot, firstPath);
255- if (!existsSync(src)) continue;
256- mkdirSync(dirname(dst), { recursive: true });
257- copyFileSync(src, dst);
258- }
259-}
260-
261-export async function applyParentChanges(
262- mainCwd: string,
263- worktreeCwd: string,
264-): Promise<void> {
265- try {
266- const [mainRoot, worktreeRoot] = await Promise.all([
267- getRepoRoot(mainCwd),
268- getRepoRoot(worktreeCwd),
269- ]);
270-
271- // 1. Sync tracked changes (staged + unstaged) by status.
272- await syncTrackedChanges(mainRoot, worktreeRoot);
273-
274- // 2. Copy untracked, non-ignored files (e.g. new source files not yet staged).
275- const untrackedResult = await runGit(mainRoot, [
276- "ls-files",
277- "--others",
278- "--exclude-standard",
279- ]);
280- if (untrackedResult.exitCode === 0) {
281- for (const file of splitNonEmptyLines(untrackedResult.stdout)) {
282- if (shouldSkipUntrackedPath(file)) continue;
283- try {
284- const src = join(mainRoot, file);
285- const dst = join(worktreeRoot, file);
286- mkdirSync(dirname(dst), { recursive: true });
287- copyFileSync(src, dst);
288- } catch {
289- // Skip files that can't be copied (e.g. symlinks, permissions).
290- }
291- }
292- }
293- } catch {
294- // best-effort; subagent runs without parent's in-progress changes.
295- }
296-}