Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(plugin): route OpenCode 2 worktrees through wt switch and wt remove (#4489)
Worktrunk Botca0563dc8d6b
diff --git a/dev/opencode-plugin.ts b/dev/opencode-plugin.tsindex f95233bc0..e25d45ecb 100644--- a/dev/opencode-plugin.ts+++ b/dev/opencode-plugin.ts@@ -1,9 +1,12 @@-// Worktrunk activity tracking plugin for OpenCode.+// Worktrunk plugin for OpenCode.//// Tracks OpenCode session activity per branch, showing status markers in `wt list`:// π€ β agent is working// π¬ β agent is waiting for input//+// Under OpenCode 2 it also registers a worktree strategy, so worktrees OpenCode+// creates and removes go through `wt switch --create` and `wt remove`.+//// Installed globally via: wt config plugins opencode install// Or manually: copy to ~/.config/opencode/plugins/worktrunk.ts//@@ -20,6 +23,8 @@// versions, and a lone file in the config directory has no package to resolve.import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import { basename, join } from "node:path";import { promisify } from "node:util";const execute = promisify(execFile);@@ -50,12 +55,110 @@ type SessionEvent = {data?: { status?: { type?: string } };};+type Signal = { signal: AbortSignal };++type WorktreeDefinition = {+ id: string;+ create(+ input: { sourceDirectory: string; directory: string; branch?: string },+ context: Signal,+ ): Promise<{ directory: string }>;+ remove(input: { directory: string; force: boolean }, context: Signal): Promise<void>;+ list(+ sourceDirectory: string,+ context: Signal,+ ): Promise<{ directory: string; type: "root" | "worktree" }[]>;+};+type SetupContext = {location?: { directory: string };event?: { subscribe(options?: { signal?: AbortSignal }): AsyncIterable<SessionEvent> };+ worktree?: {+ transform(callback: (editor: { add(definition: WorktreeDefinition): void }) => void): Promise<unknown>;+ };};-function setup(context: SetupContext) {+/**+ * Run `wt` and return its stdout, surfacing its stderr as the error message.+ *+ * OpenCode reports a strategy's error to the user, and wt's own message (a+ * dirty worktree, a branch that already exists) says more than the exit code.+ */+async function wt(args: string[], { signal }: Signal): Promise<string> {+ try {+ const { stdout } = await execute("wt", args, { signal, maxBuffer: 16 * 1024 * 1024 });+ return stdout;+ } catch (error) {+ const stderr = (error as { stderr?: string }).stderr?.trim();+ throw new Error(stderr || (error instanceof Error ? error.message : String(error)));+ }+}++// OpenCode's own `git` strategy creates a detached checkout at a generated+// path. This one keeps worktrunk's model instead: each worktree gets a branch,+// named after the directory OpenCode suggests (the name the user typed, or a+// generated slug), at the path the `worktree-path` template picks. OpenCode+// accepts a strategy returning a different directory than it suggested.+//+// A dirty worktree fails removal with wt's message. OpenCode only offers to+// force when the error is its own `Worktree.OperationError` class, which a lone+// plugin file has no package to import from.+const strategy: WorktreeDefinition = {+ id: "worktrunk",+ async create({ sourceDirectory, directory, branch }, context) {+ const name = basename(directory);+ // `branch` is the starting ref, not the new branch's name. Reopen a branch+ // that already exists, as the Claude Code hook does, but refuse a starting+ // ref for one rather than silently ignore it.+ let exists = true;+ try {+ await execute("git", ["-C", sourceDirectory, "rev-parse", "--verify", "--quiet", `refs/heads/${name}`], context);+ } catch {+ exists = false;+ }+ if (exists && branch) {+ throw new Error(`Branch ${name} already exists, so it can't start from ${branch}`);+ }+ const args = ["-C", sourceDirectory, "switch", name, "--no-cd", "--format=json"];+ if (!exists) args.push("--create");+ if (branch) args.push("--base", branch);+ const { path } = JSON.parse(await wt(args, context)) as { path: string };+ return { directory: path };+ },+ async remove({ directory, force }, context) {+ // Already gone, whether removed by hand or by `wt remove` itself.+ if (!existsSync(join(directory, ".git"))) return;+ await wt(["-C", directory, "remove", "--foreground", ...(force ? ["--force"] : []), directory], context);+ },+ async list(sourceDirectory, context) {+ const { stdout } = await execute("git", ["-C", sourceDirectory, "worktree", "list", "--porcelain", "-z"], context);+ // Records are NUL-separated fields, each record ending in an empty field.+ // The first record is the main worktree, or the bare repository, which has+ // no checkout to report.+ const entries: { directory: string; type: "root" | "worktree" }[] = [];+ let fields: string[] = [];+ let first = true;+ for (const field of stdout.split("\0")) {+ if (field) {+ fields.push(field);+ continue;+ }+ if (fields.length === 0) continue;+ const path = fields[0].startsWith("worktree ") ? fields[0].slice("worktree ".length) : undefined;+ const skip = fields.some((f) => f === "bare" || f === "prunable" || f.startsWith("prunable "));+ if (path && !skip) entries.push({ directory: path, type: first ? "root" : "worktree" });+ first = false;+ fields = [];+ }+ return entries;+ },+};++async function setup(context: SetupContext) {+ // A host without worktree strategies passes no `worktree`, including the+ // OpenCode 1.18 loader noted below; activity tracking doesn't depend on it.+ await context.worktree?.transform((editor) => editor.add(strategy));+const directory = context.location?.directory;const events = context.event;// OpenCode 1.18 also calls `setup`, from a second loader that passes neitherdiff --git a/docs/public/llms.txt b/docs/public/llms.txtindex aefbeb30b..cd1214c96 100644--- a/docs/public/llms.txt+++ b/docs/public/llms.txt@@ -22,7 +22,7 @@ copy-on-write build caches.## Reference-- [Agent Integration](https://worktrunk.dev/claude-code.md): Worktrunk plugins for Claude Code, Codex, OpenCode, Pi, oh-my-pi, and Gemini CLI: a configuration skill, wt list activity tracking, and Claude-only worktree isolation.+- [Agent Integration](https://worktrunk.dev/claude-code.md): Worktrunk plugins for Claude Code, Codex, OpenCode, Pi, oh-my-pi, and Gemini CLI: a configuration skill, wt list activity tracking, and worktree isolation for Claude Code and OpenCode.- [Extending Worktrunk](https://worktrunk.dev/extending.md): Three ways to add custom behavior: hooks for lifecycle automation, aliases for reusable commands, and custom subcommands for standalone tools.- [LLM Commit Messages](https://worktrunk.dev/llm-commits.md): Generate commit messages from diffs using any LLM. Integrates with wt merge, wt step commit, and wt step squash.- [Tips & Patterns](https://worktrunk.dev/tips-patterns.md): Practical recipes for Worktrunk workflows: repo layout, aliases and hooks, per-worktree dev servers and databases, agent handoffs, and branch status.diff --git a/docs/src/content/docs/claude-code.md b/docs/src/content/docs/claude-code.mdindex a76cefd8c..bf37c9713 100644--- a/docs/src/content/docs/claude-code.md+++ b/docs/src/content/docs/claude-code.md@@ -1,6 +1,6 @@---title: "Agent Integration"-description: "Worktrunk plugins for Claude Code, Codex, OpenCode, Pi, oh-my-pi, and Gemini CLI: a configuration skill, wt list activity tracking, and Claude-only worktree isolation."+description: "Worktrunk plugins for Claude Code, Codex, OpenCode, Pi, oh-my-pi, and Gemini CLI: a configuration skill, wt list activity tracking, and worktree isolation for Claude Code and OpenCode."sidebar:order: 21---@@ -10,10 +10,10 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de|---|:-:|:-:|:-:|:-:|:-:|:-:|| Configuration skill | β | β | | | | β || Activity tracking (π€/π¬ in `wt list`) | β | β | β | β | β | β |-| Worktree isolation | β | | | | | |+| Worktree isolation | β | | β | | | || `/wt-switch-create` skill | β | | | | | |-The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code exposes, so Codex, OpenCode, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex tracks activity through its own `Stop` and `SessionEnd` hooks.+The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code and OpenCode 2 expose, so Codex, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex tracks activity through its own `Stop` and `SessionEnd` hooks.## Installation@@ -53,7 +53,7 @@ codex plugin add worktrunk@worktrunkwt config plugins opencode install```-This writes the activity-tracking plugin to OpenCode's global plugins directory, `~/.config/opencode/plugins/worktrunk.ts` (honoring `$OPENCODE_CONFIG_DIR` and `$XDG_CONFIG_HOME`). `wt config plugins opencode uninstall` removes it.+This writes the plugin to OpenCode's global plugins directory, `~/.config/opencode/plugins/worktrunk.ts` (honoring `$OPENCODE_CONFIG_DIR` and `$XDG_CONFIG_HOME`). `wt config plugins opencode uninstall` removes it.### Pi@@ -134,10 +134,12 @@ Activity tracking is not plugin-specific. The plugins above only call `wt` on th| Agent finishes a turn and waits for input | `wt config state marker set "π¬"` || Session ends | `wt config state marker clear` |-## Worktree isolation (Claude Code only)+## Worktree isolation (Claude Code and OpenCode)Claude Code agents can run in isolated worktrees (`isolation: "worktree"`). By default, Claude Code creates these with `git worktree add`. The plugin's `WorktreeCreate` and `WorktreeRemove` hooks route this through `wt switch --create` and `wt remove` instead, so worktrees created by agents get worktrunk's naming conventions, hooks, and lifecycle management.+Under OpenCode 2, the plugin registers a `worktrunk` worktree strategy, so worktrees OpenCode creates and removes go through the same commands. Each gets a branch named after the worktree name OpenCode chooses, at the path from `worktree-path`; OpenCode's `worktree.directory` setting no longer applies. A dirty worktree fails removal with worktrunk's message rather than an offer to force.+## `/wt-switch-create` skill (Claude Code only)`/wt-switch-create [<branch>] [<repo>] [-- <task>]` starts a task in a fresh worktree without leaving the session: it creates the worktree, switches into it, and runs the task (all arguments optional). The worktree shows up in `wt list`; merge or remove it with `wt merge` / `wt remove`.diff --git a/docs/src/content/docs/faq.md b/docs/src/content/docs/faq.mdindex 1e2bd94a4..fa87006cd 100644--- a/docs/src/content/docs/faq.md+++ b/docs/src/content/docs/faq.md@@ -161,7 +161,7 @@ Created by the `wt config plugins <agent>` install commands. Each writes outside| File | Created by | Purpose ||------|------------|---------|-| `~/.config/opencode/plugins/worktrunk.ts` | `wt config plugins opencode install` | Activity markers in `wt list` |+| `~/.config/opencode/plugins/worktrunk.ts` | `wt config plugins opencode install` | Activity markers in `wt list`; OpenCode 2 worktrees through `wt` || `~/.pi/agent/extensions/worktrunk.ts` | `wt config plugins pi install` | Activity markers in `wt list` || `~/.omp/agent/hooks/pre/worktrunk.ts` | `wt config plugins omp install` | Activity markers in `wt list` || `~/.claude/settings.json` | `wt config plugins claude install-statusline` | Adds a `statusLine` entry running `wt list statusline --format=claude-code` |diff --git a/plugins/worktrunk/skills/worktrunk/reference/claude-code.md b/plugins/worktrunk/skills/worktrunk/reference/claude-code.mdindex c334b5802..d06429e3f 100644--- a/plugins/worktrunk/skills/worktrunk/reference/claude-code.md+++ b/plugins/worktrunk/skills/worktrunk/reference/claude-code.md@@ -6,10 +6,10 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de|---|:-:|:-:|:-:|:-:|:-:|:-:|| Configuration skill | β | β | | | | β || Activity tracking (π€/π¬ in `wt list`) | β | β | β | β | β | β |-| Worktree isolation | β | | | | | |+| Worktree isolation | β | | β | | | || `/wt-switch-create` skill | β | | | | | |-The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code exposes, so Codex, OpenCode, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex tracks activity through its own `Stop` and `SessionEnd` hooks.+The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code and OpenCode 2 expose, so Codex, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex tracks activity through its own `Stop` and `SessionEnd` hooks.## Installation@@ -49,7 +49,7 @@ codex plugin add worktrunk@worktrunkwt config plugins opencode install```-This writes the activity-tracking plugin to OpenCode's global plugins directory, `~/.config/opencode/plugins/worktrunk.ts` (honoring `$OPENCODE_CONFIG_DIR` and `$XDG_CONFIG_HOME`). `wt config plugins opencode uninstall` removes it.+This writes the plugin to OpenCode's global plugins directory, `~/.config/opencode/plugins/worktrunk.ts` (honoring `$OPENCODE_CONFIG_DIR` and `$XDG_CONFIG_HOME`). `wt config plugins opencode uninstall` removes it.### Pi@@ -126,10 +126,12 @@ Activity tracking is not plugin-specific. The plugins above only call `wt` on th| Agent finishes a turn and waits for input | `wt config state marker set "π¬"` || Session ends | `wt config state marker clear` |-## Worktree isolation (Claude Code only)+## Worktree isolation (Claude Code and OpenCode)Claude Code agents can run in isolated worktrees (`isolation: "worktree"`). By default, Claude Code creates these with `git worktree add`. The plugin's `WorktreeCreate` and `WorktreeRemove` hooks route this through `wt switch --create` and `wt remove` instead, so worktrees created by agents get worktrunk's naming conventions, hooks, and lifecycle management.+Under OpenCode 2, the plugin registers a `worktrunk` worktree strategy, so worktrees OpenCode creates and removes go through the same commands. Each gets a branch named after the worktree name OpenCode chooses, at the path from `worktree-path`; OpenCode's `worktree.directory` setting no longer applies. A dirty worktree fails removal with worktrunk's message rather than an offer to force.+## `/wt-switch-create` skill (Claude Code only)`/wt-switch-create [<branch>] [<repo>] [-- <task>]` starts a task in a fresh worktree without leaving the session: it creates the worktree, switches into it, and runs the task (all arguments optional). The worktree shows up in `wt list`; merge or remove it with `wt merge` / `wt remove`.diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdindex e05686d08..e0d298cc2 100644--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -157,7 +157,7 @@ Created by the `wt config plugins <agent>` install commands. Each writes outside| File | Created by | Purpose ||------|------------|---------|-| `~/.config/opencode/plugins/worktrunk.ts` | `wt config plugins opencode install` | Activity markers in `wt list` |+| `~/.config/opencode/plugins/worktrunk.ts` | `wt config plugins opencode install` | Activity markers in `wt list`; OpenCode 2 worktrees through `wt` || `~/.pi/agent/extensions/worktrunk.ts` | `wt config plugins pi install` | Activity markers in `wt list` || `~/.omp/agent/hooks/pre/worktrunk.ts` | `wt config plugins omp install` | Activity markers in `wt list` || `~/.claude/settings.json` | `wt config plugins claude install-statusline` | Adds a `statusLine` entry running `wt list statusline --format=claude-code` |diff --git a/skills/worktrunk/reference/claude-code.md b/skills/worktrunk/reference/claude-code.mdindex c334b5802..d06429e3f 100644--- a/skills/worktrunk/reference/claude-code.md+++ b/skills/worktrunk/reference/claude-code.md@@ -6,10 +6,10 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de|---|:-:|:-:|:-:|:-:|:-:|:-:|| Configuration skill | β | β | | | | β || Activity tracking (π€/π¬ in `wt list`) | β | β | β | β | β | β |-| Worktree isolation | β | | | | | |+| Worktree isolation | β | | β | | | || `/wt-switch-create` skill | β | | | | | |-The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code exposes, so Codex, OpenCode, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex tracks activity through its own `Stop` and `SessionEnd` hooks.+The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks, which only Claude Code and OpenCode 2 expose, so Codex, Pi, oh-my-pi, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex tracks activity through its own `Stop` and `SessionEnd` hooks.## Installation@@ -49,7 +49,7 @@ codex plugin add worktrunk@worktrunkwt config plugins opencode install```-This writes the activity-tracking plugin to OpenCode's global plugins directory, `~/.config/opencode/plugins/worktrunk.ts` (honoring `$OPENCODE_CONFIG_DIR` and `$XDG_CONFIG_HOME`). `wt config plugins opencode uninstall` removes it.+This writes the plugin to OpenCode's global plugins directory, `~/.config/opencode/plugins/worktrunk.ts` (honoring `$OPENCODE_CONFIG_DIR` and `$XDG_CONFIG_HOME`). `wt config plugins opencode uninstall` removes it.### Pi@@ -126,10 +126,12 @@ Activity tracking is not plugin-specific. The plugins above only call `wt` on th| Agent finishes a turn and waits for input | `wt config state marker set "π¬"` || Session ends | `wt config state marker clear` |-## Worktree isolation (Claude Code only)+## Worktree isolation (Claude Code and OpenCode)Claude Code agents can run in isolated worktrees (`isolation: "worktree"`). By default, Claude Code creates these with `git worktree add`. The plugin's `WorktreeCreate` and `WorktreeRemove` hooks route this through `wt switch --create` and `wt remove` instead, so worktrees created by agents get worktrunk's naming conventions, hooks, and lifecycle management.+Under OpenCode 2, the plugin registers a `worktrunk` worktree strategy, so worktrees OpenCode creates and removes go through the same commands. Each gets a branch named after the worktree name OpenCode chooses, at the path from `worktree-path`; OpenCode's `worktree.directory` setting no longer applies. A dirty worktree fails removal with worktrunk's message rather than an offer to force.+## `/wt-switch-create` skill (Claude Code only)`/wt-switch-create [<branch>] [<repo>] [-- <task>]` starts a task in a fresh worktree without leaving the session: it creates the worktree, switches into it, and runs the task (all arguments optional). The worktree shows up in `wt list`; merge or remove it with `wt merge` / `wt remove`.diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex e05686d08..e0d298cc2 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -157,7 +157,7 @@ Created by the `wt config plugins <agent>` install commands. Each writes outside| File | Created by | Purpose ||------|------------|---------|-| `~/.config/opencode/plugins/worktrunk.ts` | `wt config plugins opencode install` | Activity markers in `wt list` |+| `~/.config/opencode/plugins/worktrunk.ts` | `wt config plugins opencode install` | Activity markers in `wt list`; OpenCode 2 worktrees through `wt` || `~/.pi/agent/extensions/worktrunk.ts` | `wt config plugins pi install` | Activity markers in `wt list` || `~/.omp/agent/hooks/pre/worktrunk.ts` | `wt config plugins omp install` | Activity markers in `wt list` || `~/.claude/settings.json` | `wt config plugins claude install-statusline` | Adds a `statusLine` entry running `wt list statusline --format=claude-code` |diff --git a/src/commands/config/opencode.rs b/src/commands/config/opencode.rsindex a22711006..127ddb8b0 100644--- a/src/commands/config/opencode.rs+++ b/src/commands/config/opencode.rs@@ -1,6 +1,7 @@//! OpenCode plugin installation.//!-//! Installs the worktrunk activity tracking plugin for OpenCode.+//! Installs the worktrunk plugin for OpenCode: activity tracking, and under+//! OpenCode 2 a worktree strategy.//! The plugin source (`dev/opencode-plugin.ts`) is embedded in the binary via//! `include_str!()` and written under the OpenCode global-config directory (see//! `opencode_plugins_dir` for the precedence rules) at `β¦/plugins/worktrunk.ts`.