Skip to content

Commit 23f7fef

Browse files
committed
feat: --worktree flag for isolated write-capable rescue tasks
Add a disposable-git-worktree mode so /opencode:rescue --write --worktree runs OpenCode inside .worktrees/opencode-<ts> on a fresh opencode/<ts> branch instead of editing the working tree in place. Useful for exploratory runs, parallel rescues, and running against a dirty tree. Pieces: - lib/git.mjs: createWorktree / removeWorktree / deleteWorktreeBranch / getWorktreeDiff / applyWorktreePatch. Adds .worktrees/ to .git/info/exclude on first use so the dir never shows in status. - lib/worktree.mjs: session wrapper — createWorktreeSession, diffWorktreeSession, cleanupWorktreeSession (keep applies patch back, discard just removes). - opencode-companion.mjs: handleTask threads --worktree + swaps cwd + stores session data on the job record + renders a keep/discard footer. New worktree-cleanup subcommand reads the stored session and runs the keep or discard path. - agents/opencode-rescue.md, commands/rescue.md, skills/opencode-runtime: propagate --worktree through the forwarding layer. - tests/worktree.test.mjs: create, diff, keep-applies, discard, no-change no-op. Closes #43. Port of openai/codex-plugin-cc#137.
1 parent 1c61980 commit 23f7fef

7 files changed

Lines changed: 478 additions & 6 deletions

File tree

‎plugins/opencode/agents/opencode-rescue.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Forwarding rules:
2929
- Leave `--agent` unset unless the user explicitly requests a specific agent (build or plan).
3030
- Leave model unset by default. Only add `--model` when the user explicitly asks for a specific model.
3131
- Treat `--agent <value>` and `--model <value>` as runtime controls and do not include them in the task text you pass through.
32+
- If the request includes `--worktree`, pass `--worktree` through to `task`. This runs OpenCode in an isolated git worktree instead of editing the working directory in-place.
3233
- Default to a write-capable OpenCode run by adding `--write` unless the user explicitly asks for read-only behavior or only wants review, diagnosis, or research without edits.
3334
- Treat `--resume` and `--fresh` as routing controls and do not include them in the task text you pass through.
3435
- `--resume` means add `--resume-last`.

‎plugins/opencode/commands/rescue.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
description: Delegate investigation, an explicit fix request, or follow-up rescue work to the OpenCode rescue subagent
3-
argument-hint: "[--background|--wait] [--resume|--fresh] [--model <provider/model>] [--agent <build|plan>] [what OpenCode should investigate, solve, or continue]"
3+
argument-hint: "[--background|--wait] [--worktree] [--resume|--fresh] [--model <provider/model>] [--agent <build|plan>] [what OpenCode should investigate, solve, or continue]"
44
context: fork
55
allowed-tools: Bash(node:*)
66
---
@@ -18,6 +18,7 @@ Execution mode:
1818
- If neither flag is present, default to foreground.
1919
- `--background` and `--wait` are execution flags for Claude Code. Do not forward them to `task`, and do not treat them as part of the natural-language task text.
2020
- `--model` and `--agent` are runtime-selection flags. Preserve them for the forwarded `task` call, but do not treat them as part of the natural-language task text.
21+
- `--worktree` is an isolation flag. Preserve it for the forwarded `task` call, but do not treat it as part of the natural-language task text. When present, OpenCode runs in an isolated git worktree instead of editing the working directory in-place.
2122
- If the request includes `--resume`, do not ask whether to continue. The user already chose.
2223
- If the request includes `--fresh`, do not ask whether to continue. The user already chose.
2324
- Otherwise, before starting OpenCode, check for a resumable rescue session from this Claude session by running:

‎plugins/opencode/scripts/lib/git.mjs‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
// `gh` instead of only local working-tree state. (Apache License 2.0 §4(b)
66
// modification notice.)
77

8+
import fs from "node:fs";
9+
import path from "node:path";
810
import { runCommand } from "./process.mjs";
911

1012
/**
@@ -189,3 +191,138 @@ export async function getPrDiff(cwd, prNumber) {
189191
}
190192
return stdout;
191193
}
194+
195+
// ------------------------------------------------------------------
196+
// Worktree helpers (for --worktree isolated rescue runs)
197+
// ------------------------------------------------------------------
198+
199+
/**
200+
* Create a disposable git worktree under `<repoRoot>/.worktrees/opencode-<ts>`
201+
* on a new `opencode/<ts>` branch. Also adds `.worktrees/` to the repo's
202+
* `.git/info/exclude` so the directory never shows up in `git status`.
203+
*
204+
* @param {string} repoRoot
205+
* @returns {Promise<{ worktreePath: string, branch: string, repoRoot: string, baseCommit: string, timestamp: number }>}
206+
*/
207+
export async function createWorktree(repoRoot) {
208+
const ts = Date.now();
209+
const worktreesDir = path.join(repoRoot, ".worktrees");
210+
fs.mkdirSync(worktreesDir, { recursive: true });
211+
212+
// Resolve the real git dir (handles linked worktrees where .git is a file).
213+
const gitDirResult = await runCommand("git", ["rev-parse", "--git-dir"], { cwd: repoRoot });
214+
const rawGitDir = gitDirResult.stdout.trim();
215+
const gitDir = path.resolve(repoRoot, rawGitDir);
216+
const excludePath = path.join(gitDir, "info", "exclude");
217+
const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, "utf8") : "";
218+
if (!existing.includes(".worktrees")) {
219+
fs.mkdirSync(path.dirname(excludePath), { recursive: true });
220+
const sep = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
221+
fs.appendFileSync(excludePath, `${sep}.worktrees/\n`);
222+
}
223+
224+
const worktreePath = path.join(worktreesDir, `opencode-${ts}`);
225+
const branch = `opencode/${ts}`;
226+
const baseCommitResult = await runCommand("git", ["rev-parse", "HEAD"], { cwd: repoRoot });
227+
if (baseCommitResult.exitCode !== 0) {
228+
throw new Error(`git rev-parse HEAD failed: ${baseCommitResult.stderr.trim()}`);
229+
}
230+
const baseCommit = baseCommitResult.stdout.trim();
231+
232+
const addResult = await runCommand(
233+
"git",
234+
["worktree", "add", worktreePath, "-b", branch],
235+
{ cwd: repoRoot }
236+
);
237+
if (addResult.exitCode !== 0) {
238+
throw new Error(`git worktree add failed: ${addResult.stderr.trim()}`);
239+
}
240+
241+
return { worktreePath, branch, repoRoot, baseCommit, timestamp: ts };
242+
}
243+
244+
/**
245+
* Remove a worktree (force). Swallows "not a working tree" so callers can
246+
* safely retry cleanup.
247+
* @param {string} repoRoot
248+
* @param {string} worktreePath
249+
*/
250+
export async function removeWorktree(repoRoot, worktreePath) {
251+
const { exitCode, stderr } = await runCommand(
252+
"git",
253+
["worktree", "remove", "--force", worktreePath],
254+
{ cwd: repoRoot }
255+
);
256+
if (exitCode !== 0 && !stderr.includes("is not a working tree")) {
257+
throw new Error(`git worktree remove failed: ${stderr.trim()}`);
258+
}
259+
}
260+
261+
/**
262+
* Delete a branch (force). Failures are swallowed — this is best-effort
263+
* cleanup after the worktree has already been removed.
264+
*/
265+
export async function deleteWorktreeBranch(repoRoot, branch) {
266+
await runCommand("git", ["branch", "-D", branch], { cwd: repoRoot });
267+
}
268+
269+
/**
270+
* Compute the diff the worktree made on top of the base commit. Stages
271+
* everything first so uncommitted edits (which is what OpenCode actually
272+
* produces) show up in the diff.
273+
* @returns {Promise<{ stat: string, patch: string }>}
274+
*/
275+
export async function getWorktreeDiff(worktreePath, baseCommit) {
276+
await runCommand("git", ["add", "-A"], { cwd: worktreePath });
277+
const statR = await runCommand(
278+
"git",
279+
["diff", "--cached", baseCommit, "--stat"],
280+
{ cwd: worktreePath }
281+
);
282+
if (statR.exitCode !== 0 || !statR.stdout.trim()) {
283+
return { stat: "", patch: "" };
284+
}
285+
const patchR = await runCommand(
286+
"git",
287+
["diff", "--cached", baseCommit],
288+
{ cwd: worktreePath }
289+
);
290+
return { stat: statR.stdout.trim(), patch: patchR.stdout };
291+
}
292+
293+
/**
294+
* Apply the worktree diff back to `repoRoot` as a staged patch. Returns
295+
* `{ applied, detail }` — detail includes any git error when apply fails.
296+
*/
297+
export async function applyWorktreePatch(repoRoot, worktreePath, baseCommit) {
298+
await runCommand("git", ["add", "-A"], { cwd: worktreePath });
299+
const patchR = await runCommand(
300+
"git",
301+
["diff", "--cached", baseCommit],
302+
{ cwd: worktreePath }
303+
);
304+
if (patchR.exitCode !== 0 || !patchR.stdout.trim()) {
305+
return { applied: false, detail: "No changes to apply." };
306+
}
307+
const patchPath = path.join(
308+
repoRoot,
309+
`.opencode-worktree-${Date.now()}-${Math.random().toString(16).slice(2)}.patch`
310+
);
311+
try {
312+
fs.writeFileSync(patchPath, patchR.stdout, "utf8");
313+
const applyR = await runCommand(
314+
"git",
315+
["apply", "--index", patchPath],
316+
{ cwd: repoRoot }
317+
);
318+
if (applyR.exitCode !== 0) {
319+
return {
320+
applied: false,
321+
detail: applyR.stderr.trim() || "Patch apply failed (conflicts?).",
322+
};
323+
}
324+
return { applied: true, detail: "Changes applied and staged." };
325+
} finally {
326+
fs.rmSync(patchPath, { force: true });
327+
}
328+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Disposable git-worktree sessions for isolated write-capable rescue runs.
2+
// Wraps the lower-level helpers in lib/git.mjs so handleTask can swap the
3+
// working directory transparently and offer the user a keep/discard choice
4+
// at the end.
5+
6+
import {
7+
getGitRoot,
8+
createWorktree,
9+
removeWorktree,
10+
deleteWorktreeBranch,
11+
getWorktreeDiff,
12+
applyWorktreePatch,
13+
} from "./git.mjs";
14+
15+
/**
16+
* Create a new worktree session rooted at `cwd`'s repo. Throws if cwd is
17+
* not inside a git repository.
18+
* @param {string} cwd
19+
* @returns {Promise<{ worktreePath: string, branch: string, repoRoot: string, baseCommit: string, timestamp: number }>}
20+
*/
21+
export async function createWorktreeSession(cwd) {
22+
const repoRoot = await getGitRoot(cwd);
23+
if (!repoRoot) {
24+
throw new Error("Not a git repository — --worktree requires one.");
25+
}
26+
return createWorktree(repoRoot);
27+
}
28+
29+
/**
30+
* Compute the diff produced inside a worktree session.
31+
* @param {{ worktreePath: string, baseCommit: string }} session
32+
* @returns {Promise<{ stat: string, patch: string }>}
33+
*/
34+
export async function diffWorktreeSession(session) {
35+
return getWorktreeDiff(session.worktreePath, session.baseCommit);
36+
}
37+
38+
/**
39+
* Tear down a worktree session. When `keep` is true, the diff is first
40+
* applied back to the repo as a staged patch; on success the worktree and
41+
* branch are removed. On apply failure the worktree is preserved so the
42+
* user can recover manually.
43+
*
44+
* @param {{ worktreePath: string, branch: string, repoRoot: string, baseCommit: string }} session
45+
* @param {{ keep?: boolean }} [opts]
46+
* @returns {Promise<{ applied: boolean, detail: string }>}
47+
*/
48+
export async function cleanupWorktreeSession(session, opts = {}) {
49+
const keep = Boolean(opts.keep);
50+
51+
if (keep) {
52+
const result = await applyWorktreePatch(
53+
session.repoRoot,
54+
session.worktreePath,
55+
session.baseCommit
56+
);
57+
// Only tear down when the apply succeeded or there was nothing to apply.
58+
// On a real apply failure we leave the worktree in place for recovery.
59+
if (!result.applied && result.detail !== "No changes to apply.") {
60+
return result;
61+
}
62+
await removeWorktree(session.repoRoot, session.worktreePath);
63+
await deleteWorktreeBranch(session.repoRoot, session.branch);
64+
return result;
65+
}
66+
67+
await removeWorktree(session.repoRoot, session.worktreePath);
68+
await deleteWorktreeBranch(session.repoRoot, session.branch);
69+
return { applied: false, detail: "Worktree discarded." };
70+
}

0 commit comments

Comments
 (0)