Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(statusline): add --format=json and --format=claude-code options (#875)
Maximilian Roos3ab31bd73fdb
diff --git a/.claude-plugin/skills/worktrunk/reference/claude-code.md b/.claude-plugin/skills/worktrunk/reference/claude-code.mdindex f692bf812..6373c3ac4 100644--- a/.claude-plugin/skills/worktrunk/reference/claude-code.md+++ b/.claude-plugin/skills/worktrunk/reference/claude-code.md@@ -51,7 +51,7 @@ $ git config worktrunk.state.feature.marker '{"marker":"💬","set_at":0}' # Di## Statusline-`wt list statusline --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).+`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).<code>~/w/myproject.feature-auth !🤖 @<span style='color:#0a0'>+42</span> <span style='color:#a00'>-8</span> <span style='color:#0a0'>↑3</span> <span style='color:#0a0'>⇡1</span> <span style='color:#0a0'>●</span> | Opus 🌔 65%</code>@@ -63,7 +63,7 @@ Add to `~/.claude/settings.json`:{"statusLine": {"type": "command",- "command": "wt list statusline --claude-code"+ "command": "wt list statusline --format=claude-code"}}```diff --git a/docs/content/claude-code.md b/docs/content/claude-code.mdindex 7c0378c2f..4bd003b9f 100644--- a/docs/content/claude-code.md+++ b/docs/content/claude-code.md@@ -63,7 +63,7 @@ $ git config worktrunk.state.feature.marker '{"marker":"💬","set_at":0}' # Di## Statusline-`wt list statusline --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).+`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).<code>~/w/myproject.feature-auth !🤖 @<span style='color:#0a0'>+42</span> <span style='color:#a00'>-8</span> <span style='color:#0a0'>↑3</span> <span style='color:#0a0'>⇡1</span> <span style='color:#0a0'>●</span> | Opus 🌔 65%</code>@@ -82,7 +82,7 @@ Add to `~/.claude/settings.json`:{"statusLine": {"type": "command",- "command": "wt list statusline --claude-code"+ "command": "wt list statusline --format=claude-code"}}```diff --git a/docs/demos/shared/lib.py b/docs/demos/shared/lib.pyindex 1ad582cad..ce867685d 100644--- a/docs/demos/shared/lib.py+++ b/docs/demos/shared/lib.py@@ -477,7 +477,7 @@ def setup_claude_code_config("model": "claude-opus-4-5-20251101","statusLine": {"type": "command",- "command": "wt list statusline --claude-code",+ "command": "wt list statusline --format=claude-code",},}(claude_dir / "settings.json").write_text(json.dumps(settings, indent=2))diff --git a/src/cli/list.rs b/src/cli/list.rsindex 3425245a7..3f6f9b934 100644--- a/src/cli/list.rs+++ b/src/cli/list.rs@@ -1,16 +1,34 @@use clap::Subcommand;+use super::OutputFormat;+/// Subcommands for `wt list`#[derive(Subcommand)]pub enum ListSubcommand {/// Single-line status for shell prompts- #[command(after_long_help = "Output format: `branch status ±working commits upstream ci`")]+ #[command(after_long_help = r#"## Output formats++- `table` (default): `branch status ±working commits upstream ci`+- `json`: Same structure as `wt list --format=json` but for the current worktree only+- `claude-code`: Reads context from stdin, adds directory and model segments++## Claude Code mode++With `--format=claude-code`, reads JSON context from stdin:+`dir branch status ±working commits upstream ci | model context`++Input fields (all optional):+- `.workspace.current_dir` — working directory+- `.model.display_name` — model name+- `.context_window.used_percentage` — context usage (0-100)+"#)]Statusline {- /// Claude Code mode: read context from stdin, add directory and model- ///- /// Reads JSON from stdin with `.workspace.current_dir` and `.model.display_name`.- /// Output: `dir branch status ±working commits upstream ci | model`- #[arg(long)]+ /// Output format (table, json, claude-code)+ #[arg(long, value_enum, default_value = "table")]+ format: OutputFormat,++ /// Deprecated: use --format=claude-code+ #[arg(long, hide = true)]claude_code: bool,},}diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex c34beace0..b3a3910ec 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -173,12 +173,17 @@ pub(crate) fn version_str() -> &'static str {})}+// 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)]pub(crate) enum OutputFormat {/// Human-readable table formatTable,/// JSON outputJson,+ /// Claude Code statusline mode (reads context from stdin)+ #[value(name = "claude-code")]+ ClaudeCode,}#[derive(Parser)]diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex b332aabe9..71a01d0bf 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -595,7 +595,7 @@ pub fn handle_state_show(format: OutputFormat) -> anyhow::Result<()> {match format {OutputFormat::Json => handle_state_show_json(&repo),- OutputFormat::Table => handle_state_show_table(&repo),+ OutputFormat::Table | OutputFormat::ClaudeCode => handle_state_show_table(&repo),}}diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex a8dd7000c..6a543b7a3 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -121,7 +121,7 @@pub mod ci_status;pub(crate) mod collect;pub(crate) mod columns;-mod json_output;+pub mod json_output;pub(crate) mod layout;pub mod model;pub mod progressive;@@ -173,12 +173,17 @@ pub fn handle_list(// Progressive rendering only for table format with Progressive modelet show_progress = match format {- crate::OutputFormat::Table => render_mode == RenderMode::Progressive,+ crate::OutputFormat::Table | crate::OutputFormat::ClaudeCode => {+ render_mode == RenderMode::Progressive+ }crate::OutputFormat::Json => false, // JSON never shows progress};// Render table in collect() for all table modes (progressive + buffered)- let render_table = matches!(format, crate::OutputFormat::Table);+ let render_table = matches!(+ format,+ crate::OutputFormat::Table | crate::OutputFormat::ClaudeCode+ );// For testing: allow enabling skip_expensive_for_stale via env varlet skip_expensive_for_stale = std::env::var("WORKTRUNK_TEST_SKIP_EXPENSIVE_THRESHOLD").is_ok();@@ -220,7 +225,7 @@ pub fn handle_list(serde_json::to_string_pretty(&json_items).context("Failed to serialize to JSON")?;println!("{}", json);}- crate::OutputFormat::Table => {+ crate::OutputFormat::Table | crate::OutputFormat::ClaudeCode => {// Table and summary already rendered in collect() for all modes// Nothing to do here - collect() handles the complete table rendering}diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 36e4d22dd..f1676c387 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -10,12 +10,15 @@ use std::env;use std::io::{self, IsTerminal, Read};use std::path::{Component, Path};+use dunce::canonicalize;+use ansi_str::AnsiStr;use anyhow::{Context, Result};use worktrunk::git::Repository;use worktrunk::styling::{fix_dim_after_color_reset, get_terminal_width, truncate_visible};-use super::list::{self, CollectOptions, StatuslineSegment};+use super::list::{self, CollectOptions, StatuslineSegment, json_output};+use crate::cli::OutputFormat;/// Claude Code context parsed from stdin JSONstruct ClaudeCodeContext {@@ -29,18 +32,14 @@ struct ClaudeCodeContext {impl ClaudeCodeContext {/// Parse Claude Code context from a JSON string.- /// Returns None if the string is empty or not valid JSON.+ /// Returns None if not valid JSON or missing required fields.fn parse(input: &str) -> Option<Self> {- if input.is_empty() {- return None;- }-let v: serde_json::Value = serde_json::from_str(input).ok()?;+ // current_dir is required - if missing, treat as invalid JSONlet current_dir = v.pointer("/workspace/current_dir")- .and_then(|v| v.as_str())- .unwrap_or(".")+ .and_then(|v| v.as_str())?.to_string();let model_name = v@@ -154,7 +153,14 @@ fn format_context_gauge(percentage: f64) -> String {////// Output uses `println!` for raw stdout (bypasses anstream color detection)./// Shell prompts (PS1) and Claude Code always expect ANSI codes.-pub fn run(claude_code: bool) -> Result<()> {+pub fn run(format: OutputFormat) -> Result<()> {+ // JSON format: output current worktree as JSON+ if matches!(format, OutputFormat::Json) {+ return run_json();+ }++ let claude_code = matches!(format, OutputFormat::ClaudeCode);+// Get context - either from stdin (claude-code mode) or current directorylet (cwd, model_name, context_used_percentage) = if claude_code {let ctx = ClaudeCodeContext::from_stdin();@@ -243,6 +249,69 @@ pub fn run(claude_code: bool) -> Result<()> {Ok(())}+/// Run statusline with JSON output format.+///+/// Outputs the current worktree as JSON, using the same structure as `wt list --format=json`.+fn run_json() -> Result<()> {+ let cwd = env::current_dir().context("Failed to get current directory")?;++ let repo = Repository::current().context("Not in a git repository")?;++ // Verify we're in a worktree+ if repo.worktree_at(&cwd).git_dir().is_err() {+ // Not in a worktree - return empty array (consistent with wt list)+ println!("[]");+ return Ok(());+ }++ // Get current worktree info+ // Use git rev-parse --show-toplevel (via current_worktree().root()) to correctly identify+ // the worktree containing cwd, rather than prefix matching which fails for nested worktrees.+ let worktrees = repo.list_worktrees()?;+ let worktree_root = repo.current_worktree().root()?;+ let current_worktree = worktrees.iter().find(|wt| {+ canonicalize(&wt.path)+ .map(|p| p == worktree_root)+ .unwrap_or(false)+ });++ let Some(wt) = current_worktree else {+ println!("[]");+ return Ok(());+ };++ // Determine if this is the primary worktree+ let is_home = repo+ .primary_worktree()+ .ok()+ .flatten()+ .is_some_and(|p| wt.path == p);++ // Build item with identity fields+ let mut item = list::build_worktree_item(wt, is_home, true, false);++ // Load URL template from project config (if configured)+ let url_template = repo.url_template();++ // Build collect options with URL template (compute everything for complete data)+ let options = CollectOptions {+ url_template,+ ..Default::default()+ };++ // Populate computed fields (parallel git operations)+ list::populate_item(&repo, &mut item, options)?;++ // Convert to JSON format+ let json_item = json_output::JsonItem::from_list_item(&item);++ // Output as JSON array (consistent with wt list --format=json)+ let output = serde_json::to_string_pretty(&[json_item])?;+ println!("{output}");++ Ok(())+}+/// Filter out branch segment if directory already shows it via worktrunk template.fn filter_redundant_branch(segments: Vec<StatuslineSegment>, dir: &str) -> Vec<StatuslineSegment> {use super::list::columns::ColumnKind;@@ -278,8 +347,15 @@ fn get_git_status_segments(use super::list::columns::ColumnKind;// Get current worktree info+ // Use git rev-parse --show-toplevel (via worktree_at().root()) to correctly identify+ // the worktree containing cwd, rather than prefix matching which fails for nested worktrees.let worktrees = repo.list_worktrees()?;- let current_worktree = worktrees.iter().find(|wt| cwd.starts_with(&wt.path));+ let worktree_root = repo.worktree_at(cwd).root()?;+ let current_worktree = worktrees.iter().find(|wt| {+ canonicalize(&wt.path)+ .map(|p| p == worktree_root)+ .unwrap_or(false)+ });let Some(wt) = current_worktree else {// Not in a worktree - just show branch name as a segment@@ -432,12 +508,13 @@ mod tests {#[test]fn test_claude_code_context_parse_missing_workspace() {- // Missing workspace defaults to "."+ // Missing current_dir makes the JSON invalid - returns Nonelet json = r#"{"model": {"display_name": "Sonnet"}}"#;- let ctx = ClaudeCodeContext::parse(json).expect("should parse");- assert_eq!(ctx.current_dir, ".");- assert_eq!(ctx.model_name, Some("Sonnet".to_string()));+ assert!(+ ClaudeCodeContext::parse(json).is_none(),+ "Missing current_dir should return None"+ );}#[test]diff --git a/src/main.rs b/src/main.rsindex 45824bfaf..b3f84c5ff 100644--- a/src/main.rs+++ b/src/main.rs@@ -703,8 +703,18 @@ fn main() {progressive,no_progressive,} => match subcommand {- Some(ListSubcommand::Statusline { claude_code }) => {- commands::statusline::run(claude_code)+ Some(ListSubcommand::Statusline {+ format,+ claude_code,+ }) => {+ // Hidden --claude-code flag only applies when format is default (Table)+ // Explicit --format=json takes precedence over --claude-code+ let effective_format = if claude_code && matches!(format, OutputFormat::Table) {+ OutputFormat::ClaudeCode+ } else {+ format+ };+ commands::statusline::run(effective_format)}None => {// Load config and merge with CLI flags (CLI flags take precedence)diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex a18ec95ba..f99626455 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -1853,7 +1853,7 @@ impl TestRepo {std::fs::create_dir_all(&claude_dir).unwrap();std::fs::write(claude_dir.join("settings.json"),- r#"{"statusLine":{"type":"command","command":"wt list statusline --claude-code"}}"#,+ r#"{"statusLine":{"type":"command","command":"wt list statusline --format=claude-code"}}"#,).unwrap();}diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rsindex 7fff88c9d..0a4fd21a1 100644--- a/tests/integration_tests/statusline.rs+++ b/tests/integration_tests/statusline.rs@@ -5,6 +5,7 @@use crate::common::{TestRepo, repo, wt_command};use insta::assert_snapshot;use rstest::rstest;+use serde_json::Value;use std::io::Write;use std::process::Stdio;@@ -168,7 +169,7 @@ fn test_statusline_claude_code_full_context(repo: TestRepo) {}}"#,);- let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));claude_code_snapshot_settings().bind(|| {assert_snapshot!(output, @"[PATH] main [36m?[0m[2m^[22m[2m|[22m | Opus");});@@ -179,7 +180,7 @@ fn test_statusline_claude_code_minimal(repo: TestRepo) {let escaped_path = escape_path_for_json(repo.root_path());let json = format!(r#"{{"workspace": {{"current_dir": "{escaped_path}"}}}}"#,);- let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));claude_code_snapshot_settings().bind(|| {assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m");});@@ -195,7 +196,7 @@ fn test_statusline_claude_code_with_model(repo: TestRepo) {}}"#,);- let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));claude_code_snapshot_settings().bind(|| {assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Haiku");});@@ -214,7 +215,7 @@ fn test_statusline_claude_code_with_context_gauge(repo: TestRepo) {}}"#,);- let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));claude_code_snapshot_settings().bind(|| {assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Opus 🌕 42%");});@@ -231,7 +232,7 @@ fn test_statusline_claude_code_context_gauge_low(repo: TestRepo) {}}"#,);- let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));claude_code_snapshot_settings().bind(|| {assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Opus 🌕 5%");});@@ -248,7 +249,7 @@ fn test_statusline_claude_code_context_gauge_high(repo: TestRepo) {}}"#,);- let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));claude_code_snapshot_settings().bind(|| {assert_snapshot!(output, @"[PATH] main [2m^[22m[2m|[22m | Opus 🌑 98%");});@@ -265,7 +266,7 @@ fn test_statusline_claude_code_missing_context_window(repo: TestRepo) {}}"#,);- let output = run_statusline(&repo, &["--claude-code"], Some(&json));+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));claude_code_snapshot_settings().bind(|| {// No gauge symbol (○◔◑◕●) should appearassert!(@@ -390,3 +391,162 @@ url = "http://{{ branch }}.localhost:3000"let output = run_statusline_from_dir(&repo, &[], None, &feature_path);assert_snapshot!(output, @"[0m feature [2m_[22m http://feature.localhost:3000");}++// --- JSON Format Tests ---++#[rstest]+fn test_statusline_json_basic(repo: TestRepo) {+ let output = run_statusline(&repo, &["--format=json"], None);+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");++ // Should be an array with one item+ let items = parsed.as_array().expect("should be an array");+ assert_eq!(+ items.len(),+ 1,+ "should have exactly one item (current worktree)"+ );++ let item = &items[0];++ // Check essential fields+ assert_eq!(item["branch"], "main");+ assert_eq!(item["kind"], "worktree");+ assert!(item["is_current"].as_bool().unwrap());+ assert!(item["is_main"].as_bool().unwrap());++ // commit object should exist with sha+ assert!(item["commit"]["sha"].is_string());+ assert!(item["commit"]["short_sha"].is_string());+}++#[rstest]+fn test_statusline_json_with_changes(repo: TestRepo) {+ // Create uncommitted changes+ std::fs::write(repo.root_path().join("modified.txt"), "modified content").unwrap();++ let output = run_statusline(&repo, &["--format=json"], None);+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");++ let item = &parsed[0];+ assert_eq!(item["branch"], "main");++ // Should have working_tree status+ let working_tree = &item["working_tree"];+ assert!(+ working_tree["untracked"].as_bool().unwrap(),+ "should show untracked file"+ );+}++#[rstest]+fn test_statusline_json_feature_branch(mut repo: TestRepo) {+ // Create feature worktree with commits+ let feature_path = repo.add_worktree("feature");++ std::fs::write(feature_path.join("feature.txt"), "content").unwrap();+ repo.git_command()+ .args(["add", "."])+ .current_dir(&feature_path)+ .output()+ .unwrap();+ repo.git_command()+ .args(["commit", "-m", "Feature commit"])+ .current_dir(&feature_path)+ .output()+ .unwrap();++ let output = run_statusline_from_dir(&repo, &["--format=json"], None, &feature_path);+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");++ let item = &parsed[0];+ assert_eq!(item["branch"], "feature");+ assert!(item["is_current"].as_bool().unwrap());+ assert!(!item["is_main"].as_bool().unwrap());++ // Should have ahead/behind counts (commits ahead of main)+ assert!(+ item["main"]["ahead"].as_u64().unwrap() >= 1,+ "should be ahead of main"+ );+}++#[rstest]+fn test_statusline_json_ignores_claude_code(repo: TestRepo) {+ // When --format=json is used, --claude-code should be ignored+ let escaped_path = escape_path_for_json(repo.root_path());+ let json = format!(+ r#"{{+ "workspace": {{"current_dir": "{escaped_path}"}},+ "model": {{"display_name": "Opus"}}+ }}"#,+ );++ let output = run_statusline(&repo, &["--format=json", "--claude-code"], Some(&json));+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");++ // Should still produce JSON output (not statusline format)+ assert!(parsed.is_array(), "should produce JSON array output");+ let item = &parsed[0];+ assert_eq!(item["branch"], "main");+}++/// Tests that statusline correctly identifies nested worktrees.+///+/// When worktrees are placed inside other worktrees (e.g., `.worktrees/` layout),+/// the detection must use git rev-parse --show-toplevel rather than prefix matching,+/// which would incorrectly match the parent worktree.+///+/// Regression test for: prefix matching with starts_with would incorrectly identify+/// the main worktree when running from a nested worktree.+#[rstest]+fn test_statusline_nested_worktree(mut repo: TestRepo) {+ // Create a worktree nested inside the main repo (like .worktrees/ layout)+ let nested_path = repo.root_path().join(".worktrees").join("feature");+ let nested_worktree = repo.add_worktree_at_path("feature", &nested_path);++ // Run statusline from inside the nested worktree - should show "feature", not "main"+ let output = repo+ .wt_command()+ .current_dir(&nested_worktree)+ .args(["list", "statusline"])+ .output()+ .expect("statusline should succeed");++ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("feature"),+ "Nested worktree should show 'feature' branch, got: {stdout}"+ );+ assert!(+ !stdout.contains("main"),+ "Nested worktree should NOT show 'main' branch, got: {stdout}"+ );+}++/// Tests that JSON output correctly identifies nested worktrees.+#[rstest]+fn test_statusline_json_nested_worktree(mut repo: TestRepo) {+ // Create a worktree nested inside the main repo+ let nested_path = repo.root_path().join(".worktrees").join("feature");+ let nested_worktree = repo.add_worktree_at_path("feature", &nested_path);++ // Run statusline --format=json from inside the nested worktree+ let output = repo+ .wt_command()+ .current_dir(&nested_worktree)+ .args(["list", "statusline", "--format=json"])+ .output()+ .expect("statusline should succeed");++ let stdout = String::from_utf8_lossy(&output.stdout);+ let parsed: Value = serde_json::from_str(&stdout).expect("should be valid JSON");++ assert!(parsed.is_array(), "should produce JSON array");+ let items = parsed.as_array().unwrap();+ assert_eq!(items.len(), 1, "should have exactly one item");+ assert_eq!(+ items[0]["branch"], "feature",+ "Nested worktree should report 'feature' branch, not parent"+ );+}