Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat: add --format=json to wt switch and CC worktree hooks (#1959)

Maximilian Roosd6e84ed25819
diff --git a/.claude-plugin/hooks/hooks.json b/.claude-plugin/hooks/hooks.json
index 4c1455b2e..029730e25 100644
--- a/.claude-plugin/hooks/hooks.json
+++ b/.claude-plugin/hooks/hooks.json
@@ -31,6 +31,26 @@
}
]
}
+ ],
+ "WorktreeCreate": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "jq -r '.worktree_name // .branch // empty' | xargs -I{} wt switch --create {} --no-cd --format=json | jq -r '.path'"
+ }
+ ]
+ }
+ ],
+ "WorktreeRemove": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "jq -r '.worktree_path' | xargs wt remove -D --foreground"
+ }
+ ]
+ }
]
}
}
diff --git a/docs/content/claude-code.md b/docs/content/claude-code.md
index e8a2b75d7..5edc080b7 100644
--- a/docs/content/claude-code.md
+++ b/docs/content/claude-code.md
@@ -1,16 +1,17 @@
+++
title = "Claude Code Integration"
-description = "Worktrunk plugin for Claude Code: configuration skill for setup help and activity tracking for wt list."
+description = "Worktrunk plugin for Claude Code: configuration skill, worktree isolation for agents, and activity tracking for wt list."
weight = 23
[extra]
group = "Reference"
+++
-The worktrunk Claude Code plugin provides two features:
+The worktrunk Claude Code plugin provides three features:
1. **Configuration skill** — Documentation Claude Code can read, so it can help set up LLM commits, hooks, and troubleshoot issues
-2. **Activity tracking** — Status markers in `wt list` showing which worktrees have active Claude sessions (🤖 working, 💬 waiting)
+2. **Worktree isolation** — When Claude Code agents create isolated worktrees, the plugin routes creation and removal through `wt` instead of raw `git`
+3. **Activity tracking** — Status markers in `wt list` showing which worktrees have active Claude sessions (🤖 working, 💬 waiting)
## Installation
@@ -59,6 +60,10 @@ Set status markers manually for any workflow:
<span class="cmd">git config worktrunk.state.feature.marker '{"marker":"💬","set_at":0}' # Direct</span>
{% end %}
+## Worktree isolation
+
+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.
+
## Statusline
`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. This may fetch CI status from the network when the cache is stale (often ~1–2 seconds), making it suitable for async statuslines but too slow for synchronous shell prompts. If a faster version would be helpful, please [open an issue](https://github.com/max-sixty/worktrunk/issues).
diff --git a/docs/content/switch.md b/docs/content/switch.md
index 96a67dd30..ae034c34f 100644
--- a/docs/content/switch.md
+++ b/docs/content/switch.md
@@ -196,6 +196,18 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=c>--no-hooks</span></b>
Skip hooks
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format
+
+ JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code
+ WorktreeCreate hooks).
+
+ Possible values:
+ - <b><span class=c>text</span></b>: Human-readable text output
+ - <b><span class=c>json</span></b>: JSON output
+
+ [default: text]
+
<b><span class=g>Global Options:</span></b>
<b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
Working directory for this command
diff --git a/skills/worktrunk/reference/claude-code.md b/skills/worktrunk/reference/claude-code.md
index 34d83adc5..d762b9e76 100644
--- a/skills/worktrunk/reference/claude-code.md
+++ b/skills/worktrunk/reference/claude-code.md
@@ -1,9 +1,10 @@
# Claude Code Integration
-The worktrunk Claude Code plugin provides two features:
+The worktrunk Claude Code plugin provides three features:
1. **Configuration skill** — Documentation Claude Code can read, so it can help set up LLM commits, hooks, and troubleshoot issues
-2. **Activity tracking** — Status markers in `wt list` showing which worktrees have active Claude sessions (🤖 working, 💬 waiting)
+2. **Worktree isolation** — When Claude Code agents create isolated worktrees, the plugin routes creation and removal through `wt` instead of raw `git`
+3. **Activity tracking** — Status markers in `wt list` showing which worktrees have active Claude sessions (🤖 working, 💬 waiting)
## Installation
@@ -51,6 +52,10 @@ $ wt config state marker set "✅" --branch feature # Specific branch
$ git config worktrunk.state.feature.marker '{"marker":"💬","set_at":0}' # Direct
```
+## Worktree isolation
+
+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.
+
## Statusline
`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. This may fetch CI status from the network when the cache is stale (often ~1–2 seconds), making it suitable for async statuslines but too slow for synchronous shell prompts. If a faster version would be helpful, please [open an issue](https://github.com/max-sixty/worktrunk/issues).
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index 70d122e0d..f1b020f08 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -187,6 +187,18 @@ Automation:
--no-hooks
Skip hooks
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code
+ WorktreeCreate hooks).
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 2907b52eb..0ff1d7275 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -188,6 +188,15 @@ pub(crate) fn version_str() -> &'static str {
})
}
+/// Output format for commands with text + JSON modes (e.g., `wt switch`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
+pub(crate) enum SwitchFormat {
+ /// Human-readable text output
+ Text,
+ /// JSON output
+ Json,
+}
+
// TODO: ClaudeCode is statusline-specific but lives in this shared enum, forcing
// unrelated codepaths to handle it. Consider a dedicated StatuslineFormat enum.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
@@ -351,6 +360,13 @@ pub(crate) struct SwitchArgs {
/// Skip hooks (deprecated alias for --no-hooks)
#[arg(long = "no-verify", hide = true)]
pub(crate) no_verify_deprecated: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout. Designed for tool
+ /// integration (e.g., Claude Code WorktreeCreate hooks).
+ #[arg(long, default_value = "text", requires = "branch", conflicts_with_all = ["branches", "remotes"], help_heading = "Automation")]
+ pub(crate) format: SwitchFormat,
}
#[derive(Args)]
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index 1b79fe321..be2dba414 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -1,14 +1,17 @@
//! Switch command handler.
use std::collections::HashMap;
-use std::path::Path;
+use std::path::{Path, PathBuf};
use anyhow::Context;
+use serde::Serialize;
use worktrunk::HookType;
use worktrunk::config::{UserConfig, expand_template, template_references_var, validate_template};
use worktrunk::git::{GitError, Repository, SwitchSuggestionCtx, current_or_recover};
use worktrunk::styling::{eprintln, info_message};
+use crate::cli::SwitchFormat;
+
use super::command_approval::approve_hooks;
use super::command_executor::{CommandContext, build_hook_context};
use super::hooks::{HookFailureStrategy, execute_hook};
@@ -21,6 +24,56 @@ use crate::output::{
prompt_shell_integration,
};
+/// Structured output for `wt switch --format=json`.
+#[derive(Serialize)]
+struct SwitchJsonOutput {
+ action: &'static str,
+ /// Branch name
+ #[serde(skip_serializing_if = "Option::is_none")]
+ branch: Option<String>,
+ /// Absolute worktree path
+ path: PathBuf,
+ /// True if branch was created (--create flag)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ created_branch: Option<bool>,
+ /// Base branch when creating (e.g., "main")
+ #[serde(skip_serializing_if = "Option::is_none")]
+ base_branch: Option<String>,
+ /// Remote tracking branch if auto-created
+ #[serde(skip_serializing_if = "Option::is_none")]
+ from_remote: Option<String>,
+}
+
+impl SwitchJsonOutput {
+ fn from_result(result: &SwitchResult, branch_info: &SwitchBranchInfo) -> Self {
+ let (action, path, created_branch, base_branch, from_remote) = match result {
+ SwitchResult::AlreadyAt(path) => ("already_at", path, None, None, None),
+ SwitchResult::Existing { path } => ("existing", path, None, None, None),
+ SwitchResult::Created {
+ path,
+ created_branch,
+ base_branch,
+ from_remote,
+ ..
+ } => (
+ "created",
+ path,
+ Some(*created_branch),
+ base_branch.clone(),
+ from_remote.clone(),
+ ),
+ };
+ Self {
+ action,
+ branch: branch_info.branch.clone(),
+ path: path.clone(),
+ created_branch,
+ base_branch,
+ from_remote,
+ }
+ }
+}
+
/// Options for the switch command
pub struct SwitchOptions<'a> {
pub branch: &'a str,
@@ -33,6 +86,7 @@ pub struct SwitchOptions<'a> {
/// Resolved from --cd/--no-cd flags: Some(true) = cd, Some(false) = no cd, None = use config
pub change_dir: Option<bool>,
pub verify: bool,
+ pub format: crate::cli::SwitchFormat,
}
/// Run pre-switch hooks before branch resolution or worktree creation.
@@ -222,6 +276,7 @@ pub fn handle_switch(
clobber,
change_dir: change_dir_flag,
verify,
+ format,
} = opts;
let (repo, is_recovered) = current_or_recover().context("Failed to switch worktree")?;
@@ -297,6 +352,14 @@ pub fn handle_switch(
// Execute the validated plan
let (result, branch_info) = execute_switch(&repo, plan, config, yes, hooks_approved)?;
+ // --format=json: write structured result to stdout. All behavior (hooks,
+ // --execute, shell integration) proceeds normally — format only affects output.
+ if format == SwitchFormat::Json {
+ let json = SwitchJsonOutput::from_result(&result, &branch_info);
+ let json = serde_json::to_string(&json).context("Failed to serialize to JSON")?;
+ println!("{json}");
+ }
+
// Early exit for benchmarking time-to-first-output
if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
return Ok(());
diff --git a/src/main.rs b/src/main.rs
index a747e69df..7fa3d9d75 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -582,6 +582,7 @@ fn handle_switch_command(args: SwitchArgs) -> anyhow::Result<()> {
clobber: args.clobber,
change_dir: change_dir_flag,
verify,
+ format: args.format,
},
&mut config,
&binary_name(),
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index a44e67b2a..8c2221ac8 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -40,6 +40,8 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &[
"step_commands.rs",
// --no-cd flag: branch name output for scripting
"picker/mod.rs",
+ // JSON output for wt switch --format=json
+ "handle_switch.rs",
];
/// Substrings that indicate the line is a special case (e.g., in a comment or test reference)
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index cc7b218d6..cb6c826d7 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -3659,6 +3659,103 @@ fn test_switch_with_relative_worktree_paths(repo: TestRepo) {
snapshot_switch("switch_to_relative_paths", &repo, &["relative-test"]);
}
+// -- JSON format tests --
+
+#[rstest]
+fn test_switch_format_json_create(repo: TestRepo) {
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "json-test",
+ "--no-cd",
+ "--yes",
+ "--format=json",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["action"], "created");
+ assert_eq!(json["branch"], "json-test");
+ assert!(json["path"].as_str().unwrap().contains("json-test"));
+ assert_eq!(json["created_branch"], true);
+}
+
+#[rstest]
+fn test_switch_format_json_existing(mut repo: TestRepo) {
+ // Create worktree first
+ repo.add_worktree("existing-json");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "existing-json",
+ "--no-cd",
+ "--yes",
+ "--format=json",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["action"], "existing");
+ assert_eq!(json["branch"], "existing-json");
+ // created_branch should be absent for existing switches
+ assert!(json.get("created_branch").is_none());
+}
+
+#[rstest]
+fn test_switch_format_json_already_at(mut repo: TestRepo) {
+ // Create worktree and switch to it
+ let path = repo.add_worktree("already-json");
+
+ let output = repo
+ .wt_command()
+ .current_dir(&path)
+ .args([
+ "switch",
+ "already-json",
+ "--no-cd",
+ "--yes",
+ "--format=json",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["action"], "already_at");
+ assert_eq!(json["branch"], "already-json");
+}
+
+#[rstest]
+fn test_switch_format_table_rejected_by_clap(repo: TestRepo) {
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "table-test",
+ "--no-cd",
+ "--yes",
+ "--format=table",
+ ])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("invalid value"), "stderr: {stderr}");
+}
+
/// Test that `[switch] cd = false` config is respected when no flags provided
#[rstest]
fn test_switch_no_cd_config_default(repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index 4ff585537..109f86ac8 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -99,6 +99,17 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
--no-hooks
Skip hooks
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code WorktreeCreate hooks).
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
index f50dd230e..f1eef70a4 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
@@ -53,8 +53,9 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
--remotes Include remote branches
Automation:
- -y, --yes Skip approval prompts
- --no-hooks Skip hooks
+ -y, --yes Skip approval prompts
+ --no-hooks Skip hooks
+ --format <FORMAT> Output format [default: text] [possible values: text, json]
Global Options:
-C <path> Working directory for this command