Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add `previous-branch` state key and `state clear` command (#181)
Maximilian Roos7c47e441c46f
diff --git a/docs/content/config.md b/docs/content/config.mdindex 6a75fd5b7..7c86ca8f2 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -571,12 +571,13 @@ Global Options:## wt config state-Runtime state is stored in git config, separate from configuration files.+State is stored in git config, separate from configuration files.Use `wt config show` to view file-based configuration.### Keys- **default-branch**: The repository's default branch (main, master, etc.)+- **previous-branch**: Previous branch for `wt switch -`- **ci-status**: CI/PR status for a branch (passed, running, failed, conflicts, noci)- **marker**: Custom status marker for a branch (shown in `wt list`)- **logs**: Background operation logs@@ -585,27 +586,32 @@ Use `wt config show` to view file-based configuration.Get the default branch:```bash-wt config state get default-branch+wt config state default-branch get```Set the default branch manually:```bash-wt config state set default-branch main+wt config state default-branch set main```Set a marker for current branch:```bash-wt config state set marker "π§ WIP"+wt config state marker set "π§ WIP"```Clear all CI status cache:```bash-wt config state clear ci-status --all+wt config state ci-status clear --all```-Show all cached state:+Show all stored state:```bash-wt config state show+wt config state get+```++Clear all stored state:+```bash+wt config state clear```---@@ -613,16 +619,18 @@ wt config state show### Command reference```-wt config state - Get, set, or clear runtime state (stored in git config)+wt config state - Get, set, or clear stored state (git config)Usage: wt config state [OPTIONS] <COMMAND>Commands:- default-branch Manage default branch setting- ci-status Manage CI status cache- marker Manage branch markers- logs Manage background operation logs- show Show all cached state+ default-branch Manage default branch setting+ previous-branch Manage previous branch (for wt switch -)+ ci-status Manage CI status cache+ marker Manage branch markers+ logs Manage background operation logs+ get Get all stored state+ clear Clear all stored stateOptions:-h, --help@@ -652,7 +660,7 @@ Commands:shell Shell integration setupcreate Create configuration fileshow Show configuration files & locations- state Get, set, or clear runtime state (stored in git config)+ state Get, set, or clear stored state (git config)Options:-h, --helpdiff --git a/src/cli.rs b/src/cli.rsindex 9ce74a0f7..1597a8f4c 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -388,14 +388,15 @@ commit messages."#full: bool,},- /// Get, set, or clear runtime state (stored in git config)+ /// Get, set, or clear stored state (git config)#[command(- after_long_help = r#"Runtime state is stored in git config, separate from configuration files.+ after_long_help = r#"State is stored in git config, separate from configuration files.Use `wt config show` to view file-based configuration.## Keys- **default-branch**: The repository's default branch (main, master, etc.)+- **previous-branch**: Previous branch for `wt switch -`- **ci-status**: CI/PR status for a branch (passed, running, failed, conflicts, noci)- **marker**: Custom status marker for a branch (shown in `wt list`)- **logs**: Background operation logs@@ -404,27 +405,32 @@ Use `wt config show` to view file-based configuration.Get the default branch:```console-wt config state get default-branch+wt config state default-branch get```Set the default branch manually:```console-wt config state set default-branch main+wt config state default-branch set main```Set a marker for current branch:```console-wt config state set marker "π§ WIP"+wt config state marker set "π§ WIP"```Clear all CI status cache:```console-wt config state clear ci-status --all+wt config state ci-status clear --all```-Show all cached state:+Show all stored state:```console-wt config state show+wt config state get+```++Clear all stored state:+```console+wt config state clear```"#)]State {@@ -442,6 +448,13 @@ pub enum StateCommand {action: DefaultBranchAction,},+ /// Manage previous branch (for `wt switch -`)+ #[command(name = "previous-branch")]+ PreviousBranch {+ #[command(subcommand)]+ action: PreviousBranchAction,+ },+/// Manage CI status cache#[command(name = "ci-status")]CiStatus {@@ -461,21 +474,34 @@ pub enum StateCommand {action: LogsAction,},- /// Show all cached state- #[command(after_long_help = r#"Shows all cached state including:+ /// Get all stored state+ #[command(after_long_help = r#"Shows all stored state including:- **Default branch**: Cached result of querying remote for default branch-- **Switch history**: Previous branch for `wt switch -`+- **Previous branch**: Previous branch for `wt switch -`- **Branch markers**: User-defined branch notes- **CI status**: Cached GitHub/GitLab CI status per branch (30s TTL)- **Log files**: Background operation logsCI cache entries show status, age, and the commit SHA they were fetched for."#)]- Show {+ Get {/// Output format (table, json)#[arg(long, value_enum, default_value = "table", hide_possible_values = true)]format: OutputFormat,},++ /// Clear all stored state+ #[command(after_long_help = r#"Clears all stored state:++- Default branch cache+- Previous branch+- All branch markers+- All CI status cache+- All log files++Use individual subcommands (`default-branch clear`, `ci-status clear --all`, etc.)+to clear specific state."#)]+ Clear,}#[derive(Subcommand)]@@ -515,6 +541,34 @@ wt config state default-branch set mainClear,}+#[derive(Subcommand)]+pub enum PreviousBranchAction {+ /// Get the previous branch+ #[command(after_long_help = r#"## Examples++Get the previous branch (used by `wt switch -`):+```console+wt config state previous-branch get+```"#)]+ Get,++ /// Set the previous branch+ #[command(after_long_help = r#"## Examples++Set the previous branch:+```console+wt config state previous-branch set feature+```"#)]+ Set {+ /// Branch name to set as previous+ #[arg(add = crate::completion::branch_value_completer())]+ branch: String,+ },++ /// Clear the previous branch+ Clear,+}+#[derive(Subcommand)]pub enum CiStatusAction {/// Get CI status for a branchdiff --git a/src/commands/config.rs b/src/commands/config.rsindex 96f3b47ea..8478a695b 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -600,6 +600,10 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any};crate::output::data(branch_name)?;}+ "previous-branch" => match repo.get_switch_previous() {+ Some(prev) => crate::output::data(prev)?,+ None => crate::output::data("")?,+ },"marker" => {let branch_name = match branch {Some(b) => b,@@ -713,7 +717,9 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> anycrate::output::table(rendered.trim_end())?;}_ => {- anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, ci-status, marker, logs")+ anyhow::bail!(+ "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"+ )}}@@ -731,6 +737,12 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any"Set default branch to <bold>{value}</>")))?;}+ "previous-branch" => {+ repo.record_switch_previous(Some(&value))?;+ crate::output::print(success_message(cformat!(+ "Set previous branch to <bold>{value}</>"+ )))?;+ }"marker" => {let branch_name = match branch {Some(b) => b,@@ -754,7 +766,9 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any"Set marker for <bold>{branch_name}</> to <bold>{value}</>")))?;}- _ => anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, marker"),+ _ => {+ anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, previous-branch, marker")+ }}Ok(())@@ -766,8 +780,21 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyhomatch key {"default-branch" => {- repo.clear_default_branch_cache()?;- crate::output::print(success_message("Cleared default branch cache"))?;+ if repo.clear_default_branch_cache()? {+ crate::output::print(success_message("Cleared default branch cache"))?;+ } else {+ crate::output::print(info_message("No default branch cache to clear"))?;+ }+ }+ "previous-branch" => {+ if repo+ .run_command(&["config", "--unset", "worktrunk.history"])+ .is_ok()+ {+ crate::output::print(success_message("Cleared previous branch"))?;+ } else {+ crate::output::print(info_message("No previous branch to clear"))?;+ }}"ci-status" => {if all {@@ -833,12 +860,18 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho};let config_key = format!("worktrunk.marker.{}", branch_name);- repo.run_command(&["config", "--unset", &config_key])- .context("Failed to clear marker (may not be set)")?;-- crate::output::print(success_message(cformat!(- "Cleared marker for <bold>{branch_name}</>"- )))?;+ if repo+ .run_command(&["config", "--unset", &config_key])+ .is_ok()+ {+ crate::output::print(success_message(cformat!(+ "Cleared marker for <bold>{branch_name}</>"+ )))?;+ } else {+ crate::output::print(info_message(cformat!(+ "No marker set for <bold>{branch_name}</>"+ )))?;+ }}}"logs" => {@@ -853,14 +886,66 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho}}_ => {- anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, ci-status, marker, logs")+ anyhow::bail!(+ "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"+ )+ }+ }++ Ok(())+}++/// Handle the state clear all command+pub fn handle_state_clear_all() -> anyhow::Result<()> {+ let repo = Repository::current();+ let mut cleared_any = false;++ // Clear default branch cache+ if matches!(repo.clear_default_branch_cache(), Ok(true)) {+ cleared_any = true;+ }++ // Clear previous branch+ if repo+ .run_command(&["config", "--unset", "worktrunk.history"])+ .is_ok()+ {+ cleared_any = true;+ }++ // Clear all markers+ let markers_output = repo+ .run_command(&["config", "--get-regexp", "^worktrunk\\.marker\\."])+ .unwrap_or_default();+ for line in markers_output.lines() {+ if let Some(config_key) = line.split_whitespace().next() {+ let _ = repo.run_command(&["config", "--unset", config_key]);+ cleared_any = true;}}+ // Clear all CI status cache+ let ci_cleared = CachedCiStatus::clear_all(&repo);+ if ci_cleared > 0 {+ cleared_any = true;+ }++ // Clear all logs+ let logs_cleared = clear_logs(&repo)?;+ if logs_cleared > 0 {+ cleared_any = true;+ }++ if cleared_any {+ crate::output::print(success_message("Cleared all stored state"))?;+ } else {+ crate::output::print(info_message("No stored state to clear"))?;+ }+Ok(())}-/// Handle the state show command+/// Handle the state get command (shows all state)pub fn handle_state_show(format: crate::cli::OutputFormat) -> anyhow::Result<()> {use crate::cli::OutputFormat;@@ -877,8 +962,8 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {// Get default branchlet default_branch = repo.default_branch().ok();- // Get switch history- let switch_previous = repo.get_switch_previous();+ // Get previous branch+ let previous_branch = repo.get_switch_previous();// Get markerslet markers: Vec<serde_json::Value> = get_all_markers(repo)@@ -960,7 +1045,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {let output = serde_json::json!({"default_branch": default_branch,- "switch_previous": switch_previous,+ "previous_branch": previous_branch,"markers": markers,"ci_status": ci_status,"logs": logs@@ -983,8 +1068,8 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {}writeln!(out)?;- // Show switch history (for `wt switch -`)- writeln!(out, "{}", cformat!("<cyan>SWITCH HISTORY</>"))?;+ // Show previous branch (for `wt switch -`)+ writeln!(out, "{}", cformat!("<cyan>PREVIOUS BRANCH</>"))?;match repo.get_switch_previous() {Some(prev) => write!(out, "{}", format_with_gutter(&prev, "", None))?,None => write!(out, "{}", format_with_gutter("(none)", "", None))?,diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex b76c6d00b..ca7d480d0 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -20,8 +20,8 @@ pub mod worktree;pub use command_approval::approve_hooks;pub use config::{- handle_config_create, handle_config_show, handle_state_clear, handle_state_get,- handle_state_set, handle_state_show,+ handle_config_create, handle_config_show, handle_state_clear, handle_state_clear_all,+ handle_state_get, handle_state_set, handle_state_show,};pub use configure_shell::{ConfigAction, handle_configure_shell, handle_show_theme, handle_unconfigure_shell,diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 1c34f8992..1700765a0 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1289,10 +1289,16 @@ impl Repository {////// Removes `refs/remotes/<remote>/HEAD` so the next call to `default_branch()`/// will re-query the remote.- pub fn clear_default_branch_cache(&self) -> anyhow::Result<()> {+ ///+ /// Returns `true` if cache was cleared, `false` if no cache existed.+ pub fn clear_default_branch_cache(&self) -> anyhow::Result<bool> {let remote = self.primary_remote()?;- self.run_command(&["remote", "set-head", "-d", &remote])?;- Ok(())+ if self.get_local_default_branch(&remote).is_ok() {+ self.run_command(&["remote", "set-head", "-d", &remote])?;+ Ok(true)+ } else {+ Ok(false)+ }}/// Check if two refs have identical tree content (same files/directories).diff --git a/src/main.rs b/src/main.rsindex e6421dd7a..e3d97eb71 100644--- a/src/main.rs+++ b/src/main.rs@@ -30,15 +30,16 @@ use commands::{compute_worktree_path, handle_config_create, handle_config_show, handle_configure_shell,handle_hook_show, handle_init, handle_list, handle_merge, handle_rebase, handle_remove,handle_remove_by_path, handle_remove_current, handle_show_theme, handle_squash,- handle_state_clear, handle_state_get, handle_state_set, handle_state_show, handle_switch,- handle_unconfigure_shell, resolve_worktree_path_first, run_hook, step_commit, step_for_each,+ handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,+ handle_state_show, handle_switch, handle_unconfigure_shell, resolve_worktree_path_first,+ run_hook, step_commit, step_for_each,};use output::{execute_user_command, handle_remove_output, handle_switch_output};use cli::{ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigCommand, ConfigShellCommand,- DefaultBranchAction, HookCommand, ListSubcommand, LogsAction, MarkerAction, StateCommand,- StepCommand,+ DefaultBranchAction, HookCommand, ListSubcommand, LogsAction, MarkerAction,+ PreviousBranchAction, StateCommand, StepCommand,};use worktrunk::HookType;@@ -908,6 +909,15 @@ fn main() {}DefaultBranchAction::Clear => handle_state_clear("default-branch", None, false),},+ StateCommand::PreviousBranch { action } => match action {+ PreviousBranchAction::Get => handle_state_get("previous-branch", false, None),+ PreviousBranchAction::Set { branch } => {+ handle_state_set("previous-branch", branch, None)+ }+ PreviousBranchAction::Clear => {+ handle_state_clear("previous-branch", None, false)+ }+ },StateCommand::CiStatus { action } => match action {CiStatusAction::Get { refresh, branch } => {handle_state_get("ci-status", refresh, branch)@@ -929,7 +939,8 @@ fn main() {LogsAction::Get => handle_state_get("logs", false, None),LogsAction::Clear => handle_state_clear("logs", None, false),},- StateCommand::Show { format } => handle_state_show(format),+ StateCommand::Get { format } => handle_state_show(format),+ StateCommand::Clear => handle_state_clear_all(),},},Commands::Step { action } => match action {diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 06401ce86..85bff1598 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -13,18 +13,18 @@ fn wt_state_cmd(repo: &TestRepo, key: &str, action: &str, args: &[&str]) -> Commcmd}-fn wt_state_show_cmd(repo: &TestRepo) -> Command {+fn wt_state_get_cmd(repo: &TestRepo) -> Command {let mut cmd = wt_command();repo.clean_cli_env(&mut cmd);- cmd.args(["config", "state", "show"]);+ cmd.args(["config", "state", "get"]);cmd.current_dir(repo.root_path());cmd}-fn wt_state_show_json_cmd(repo: &TestRepo) -> Command {+fn wt_state_get_json_cmd(repo: &TestRepo) -> Command {let mut cmd = wt_command();repo.clean_cli_env(&mut cmd);- cmd.args(["config", "state", "show", "--format=json"]);+ cmd.args(["config", "state", "get", "--format=json"]);cmd.current_dir(repo.root_path());cmd}@@ -104,6 +104,81 @@ fn test_state_clear_default_branch(mut repo: TestRepo) {assert!(!output.status.success());}+#[rstest]+fn test_state_clear_default_branch_empty(repo: TestRepo) {+ // Set up remote but don't set default branch cache+ repo.git_command(&["remote", "add", "origin", "https://example.com/repo.git"])+ .output()+ .unwrap();++ let output = wt_state_cmd(&repo, "default-branch", "clear", &[])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"βͺ No default branch cache to clear");+}++// ============================================================================+// previous-branch+// ============================================================================++#[rstest]+fn test_state_get_previous_branch(repo: TestRepo) {+ // Without any previous branch set, should return empty+ let output = wt_state_cmd(&repo, "previous-branch", "get", &[])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "");+}++#[rstest]+fn test_state_set_previous_branch(repo: TestRepo) {+ let output = wt_state_cmd(&repo, "previous-branch", "set", &["feature"])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"β [32mSet previous branch to [1mfeature[22m[39m");++ // Verify it was set+ let output = wt_state_cmd(&repo, "previous-branch", "get", &[])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "feature");+}++#[rstest]+fn test_state_clear_previous_branch(repo: TestRepo) {+ // Set a previous branch first+ wt_state_cmd(&repo, "previous-branch", "set", &["feature"])+ .output()+ .unwrap();++ let output = wt_state_cmd(&repo, "previous-branch", "clear", &[])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"β [32mCleared previous branch[39m");++ // Verify it was cleared+ let output = wt_state_cmd(&repo, "previous-branch", "get", &[])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "");+}++#[rstest]+fn test_state_clear_previous_branch_empty(repo: TestRepo) {+ // Clear without any previous branch set+ let output = wt_state_cmd(&repo, "previous-branch", "clear", &[])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"βͺ No previous branch to clear");+}+// ============================================================================// ci-status// ============================================================================@@ -376,18 +451,109 @@ fn test_state_clear_logs_single_file(repo: TestRepo) {}// ============================================================================-// state show+// state clear (all)+// ============================================================================++fn wt_state_clear_all_cmd(repo: &TestRepo) -> std::process::Command {+ let mut cmd = wt_command();+ cmd.current_dir(repo.root_path());+ cmd.env("CLICOLOR_FORCE", "1");+ cmd.args(["config", "state", "clear"]);+ cmd+}++#[rstest]+fn test_state_clear_all_empty(repo: TestRepo) {+ // Clear when no state exists+ let output = wt_state_clear_all_cmd(&repo).output().unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"βͺ No stored state to clear");+}++#[rstest]+fn test_state_clear_all_comprehensive(repo: TestRepo) {+ // Set up various state+ // Previous branch+ repo.git_command(&["config", "worktrunk.history", "feature"])+ .status()+ .unwrap();++ // Marker+ repo.git_command(&["config", "worktrunk.marker.main", "π§"])+ .status()+ .unwrap();++ // CI cache+ repo.git_command(&[+ "config",+ "worktrunk.ci.feature",+ r#"{"checked_at":1704067200,"head":"abc123"}"#,+ ])+ .status()+ .unwrap();++ // Logs+ let git_dir = repo.root_path().join(".git");+ let log_dir = git_dir.join("wt-logs");+ std::fs::create_dir_all(&log_dir).unwrap();+ std::fs::write(log_dir.join("feature-remove.log"), "output").unwrap();++ let output = wt_state_clear_all_cmd(&repo).output().unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"β [32mCleared all stored state[39m");++ // Verify everything was cleared+ assert!(+ repo.git_command(&["config", "--get", "worktrunk.history"])+ .output()+ .unwrap()+ .status+ .code()+ == Some(1)+ ); // Not found+ assert!(+ repo.git_command(&["config", "--get", "worktrunk.marker.main"])+ .output()+ .unwrap()+ .status+ .code()+ == Some(1)+ );+ assert!(+ repo.git_command(&["config", "--get", "worktrunk.ci.feature"])+ .output()+ .unwrap()+ .status+ .code()+ == Some(1)+ );+ assert!(!log_dir.exists());+}++#[rstest]+fn test_state_clear_all_nothing_to_clear(repo: TestRepo) {+ // First clear to ensure nothing exists+ wt_state_clear_all_cmd(&repo).output().unwrap();++ // Clear again when nothing exists+ let output = wt_state_clear_all_cmd(&repo).output().unwrap();+ assert!(output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"βͺ No stored state to clear");+}++// ============================================================================+// state get// ============================================================================#[rstest]-fn test_state_show_empty(repo: TestRepo) {- let output = wt_state_show_cmd(&repo).output().unwrap();+fn test_state_get_empty(repo: TestRepo) {+ let output = wt_state_get_cmd(&repo).output().unwrap();assert!(output.status.success());assert_snapshot!(String::from_utf8_lossy(&output.stderr), @r"[36mDEFAULT BRANCH[39m[107m [0m main- [36mSWITCH HISTORY[39m+ [36mPREVIOUS BRANCH[39m[107m [0m (none)[36mBRANCH MARKERS[39m@@ -402,7 +568,7 @@ fn test_state_show_empty(repo: TestRepo) {}#[rstest]-fn test_state_show_with_ci_entries(repo: TestRepo) {+fn test_state_get_with_ci_entries(repo: TestRepo) {// Add CI cache entries - use TEST_EPOCH for deterministic age=0s in snapshotsrepo.git_command(&["config",@@ -428,14 +594,14 @@ fn test_state_show_with_ci_entries(repo: TestRepo) {.status().unwrap();- let output = wt_state_show_cmd(&repo).output().unwrap();+ let output = wt_state_get_cmd(&repo).output().unwrap();assert!(output.status.success());assert_snapshot!(String::from_utf8_lossy(&output.stderr));}#[rstest]-fn test_state_show_comprehensive(repo: TestRepo) {- // Set up switch history+fn test_state_get_comprehensive(repo: TestRepo) {+ // Set up previous branchrepo.git_command(&["config", "worktrunk.history", "feature"]).status().unwrap();@@ -472,29 +638,29 @@ fn test_state_show_comprehensive(repo: TestRepo) {std::fs::write(log_dir.join("feature-post-start-npm.log"), "npm output").unwrap();std::fs::write(log_dir.join("bugfix-remove.log"), "remove output").unwrap();- let output = wt_state_show_cmd(&repo).output().unwrap();+ let output = wt_state_get_cmd(&repo).output().unwrap();assert!(output.status.success());assert_snapshot!(String::from_utf8_lossy(&output.stderr));}#[rstest]-fn test_state_show_json_empty(repo: TestRepo) {- let output = wt_state_show_json_cmd(&repo).output().unwrap();+fn test_state_get_json_empty(repo: TestRepo) {+ let output = wt_state_get_json_cmd(&repo).output().unwrap();assert!(output.status.success());// JSON output goes to stdoutlet json_str = String::from_utf8_lossy(&output.stdout);let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();assert_eq!(json["default_branch"], "main");- assert_eq!(json["switch_previous"], serde_json::Value::Null);+ assert_eq!(json["previous_branch"], serde_json::Value::Null);assert_eq!(json["markers"], serde_json::json!([]));assert_eq!(json["ci_status"], serde_json::json!([]));assert_eq!(json["logs"], serde_json::json!([]));}#[rstest]-fn test_state_show_json_comprehensive(repo: TestRepo) {- // Set up switch history+fn test_state_get_json_comprehensive(repo: TestRepo) {+ // Set up previous branchrepo.git_command(&["config", "worktrunk.history", "feature"]).status().unwrap();@@ -517,14 +683,14 @@ fn test_state_show_json_comprehensive(repo: TestRepo) {.status().unwrap();- let output = wt_state_show_json_cmd(&repo).output().unwrap();+ let output = wt_state_get_json_cmd(&repo).output().unwrap();assert!(output.status.success());// JSON output goes to stdoutlet json_str = String::from_utf8_lossy(&output.stdout);let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();assert_eq!(json["default_branch"], "main");- assert_eq!(json["switch_previous"], "feature");+ assert_eq!(json["previous_branch"], "feature");// Check markerslet markers = json["markers"].as_array().unwrap();diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rsindex 07295b77b..8285a61f9 100644--- a/tests/integration_tests/help.rs+++ b/tests/integration_tests/help.rs@@ -56,10 +56,15 @@ fn snapshot_help(test_name: &str, args: &[&str]) {"help_config_state_default_branch","config state default-branch --help")]+#[case(+ "help_config_state_previous_branch",+ "config state previous-branch --help"+)]#[case("help_config_state_ci_status", "config state ci-status --help")]#[case("help_config_state_marker", "config state marker --help")]#[case("help_config_state_logs", "config state logs --help")]-#[case("help_config_state_show", "config state show --help")]+#[case("help_config_state_get", "config state get --help")]+#[case("help_config_state_clear", "config state clear --help")]#[case("help_hook_approvals", "hook approvals --help")]#[case("help_hook_approvals_add", "hook approvals add --help")]#[case("help_hook_approvals_clear", "hook approvals clear --help")]diff --git a/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_show_comprehensive.snap b/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snapsimilarity index 96%rename from tests/integration_tests/snapshots/integration__integration_tests__config_state__state_show_comprehensive.snaprename to tests/integration_tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snapindex 7d7f55fa1..372c2a085 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_show_comprehensive.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap@@ -5,7 +5,7 @@ expression: "String::from_utf8_lossy(&output.stderr)"[36mDEFAULT BRANCH[39m[107m [0m main-[36mSWITCH HISTORY[39m+[36mPREVIOUS BRANCH[39m[107m [0m feature[36mBRANCH MARKERS[39mdiff --git a/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_show_with_ci_entries.snap b/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snapsimilarity index 95%rename from tests/integration_tests/snapshots/integration__integration_tests__config_state__state_show_with_ci_entries.snaprename to tests/integration_tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snapindex 557ae1ff5..236d03c58 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_show_with_ci_entries.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap@@ -5,7 +5,7 @@ expression: "String::from_utf8_lossy(&output.stderr)"[36mDEFAULT BRANCH[39m[107m [0m main-[36mSWITCH HISTORY[39m+[36mPREVIOUS BRANCH[39m[107m [0m (none)[36mBRANCH MARKERS[39mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex cef91c772..040e025a0 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -25,7 +25,7 @@ Usage: [1m[36mwt config[0m [36m[OPTIONS][0m [36m<COMMAND>[1m[36mshell[0m Shell integration setup[1m[36mcreate[0m Create configuration file[1m[36mshow[0m Show configuration files & locations- [1m[36mstate[0m Get, set, or clear runtime state (stored in git config)+ [1m[36mstate[0m Get, set, or clear stored state (git config)[1m[32mOptions:[1m[36m-h[0m, [1m[36m--helpdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_short.snap b/tests/snapshots/integration__integration_tests__help__help_config_short.snapindex 3adcb1539..54a91f29b 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_short.snap@@ -25,7 +25,7 @@ Usage: [1m[36mwt config[0m [36m[OPTIONS][0m [36m<COMMAND>[1m[36mshell[0m Shell integration setup[1m[36mcreate[0m Create configuration file[1m[36mshow[0m Show configuration files & locations- [1m[36mstate[0m Get, set, or clear runtime state (stored in git config)+ [1m[36mstate[0m Get, set, or clear stored state (git config)[1m[32mOptions:[1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state.snap b/tests/snapshots/integration__integration_tests__help__help_config_state.snapindex 8417b7a53..96167ce3c 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state.snap@@ -18,16 +18,18 @@ exit_code: 0----- stdout ---------- stderr ------wt config state - Get, set, or clear runtime state (stored in git config)+wt config state - Get, set, or clear stored state (git config)Usage: [1m[36mwt config state[0m [36m[OPTIONS][0m [36m<COMMAND>[1m[32mCommands:- [1m[36mdefault-branch[0m Manage default branch setting- [1m[36mci-status[0m Manage CI status cache- [1m[36mmarker[0m Manage branch markers- [1m[36mlogs[0m Manage background operation logs- [1m[36mshow[0m Show all cached state+ [1m[36mdefault-branch[0m Manage default branch setting+ [1m[36mprevious-branch[0m Manage previous branch (for [1mwt switch -[0m)+ [1m[36mci-status[0m Manage CI status cache+ [1m[36mmarker[0m Manage branch markers+ [1m[36mlogs[0m Manage background operation logs+ [1m[36mget[0m Get all stored state+ [1m[36mclear[0m Clear all stored state[1m[32mOptions:[1m[36m-h[0m, [1m[36m--help@@ -43,12 +45,13 @@ Usage: [1m[36mwt config state[0m [36m[OPTIONS][0m [36m<COMMAND>[1m[36m-v[0m, [1m[36m--verboseShow commands and debug info-Runtime state is stored in git config, separate from configuration files.+State is stored in git config, separate from configuration files.Use [2mwt config show[0m to view file-based configuration.[32mKeys- [1mdefault-branch[0m: The repository's default branch (main, master, etc.)+- [1mprevious-branch[0m: Previous branch for [2mwt switch -- [1mci-status[0m: CI/PR status for a branch (passed, running, failed, conflicts, noci)- [1mmarker[0m: Custom status marker for a branch (shown in [2mwt list[0m)- [1mlogs[0m: Background operation logs@@ -56,16 +59,19 @@ Use [2mwt config show[0m to view file-based configuration.[32mExamplesGet the default branch:- [2mwt config state get default-branch+ [2mwt config state default-branch getSet the default branch manually:- [2mwt config state set default-branch main+ [2mwt config state default-branch set mainSet a marker for current branch:- [2mwt config state set marker "π§ WIP"+ [2mwt config state marker set "π§ WIP"Clear all CI status cache:- [2mwt config state clear ci-status --all+ [2mwt config state ci-status clear --all-Show all cached state:- [2mwt config state show+Show all stored state:+ [2mwt config state get++Clear all stored state:+ [2mwt config state cleardiff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snapnew file mode 100644index 000000000..b354930b8--- /dev/null+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap@@ -0,0 +1,49 @@+---+source: tests/integration_tests/help.rs+info:+ program: wt+ args:+ - config+ - state+ - clear+ - "--help"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_EDITOR: ""+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+wt config state clear - Clear all stored state++Usage: [1m[36mwt config state clear[0m [36m[OPTIONS]++[1m[32mOptions:+ [1m[36m-h[0m, [1m[36m--help+ Print help (see a summary with '-h')++[1m[32mGlobal Options:+ [1m[36m-C[0m[36m [0m[36m<path>+ Working directory for this command++ [1m[36m--config[0m[36m [0m[36m<path>+ User config file path++ [1m[36m-v[0m, [1m[36m--verbose+ Show commands and debug info++Clears all stored state:++- Default branch cache+- Previous branch+- All branch markers+- All CI status cache+- All log files++Use individual subcommands ([2mdefault-branch clear[0m, [2mci-status clear --all[0m, etc.)+to clear specific state.diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_show.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snapsimilarity index 84%rename from tests/snapshots/integration__integration_tests__help__help_config_state_show.snaprename to tests/snapshots/integration__integration_tests__help__help_config_state_get.snapindex b817f6e51..13578e50d 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state_show.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap@@ -5,7 +5,7 @@ info:args:- config- state- - show+ - get- "--help"env:CLICOLOR_FORCE: "1"@@ -19,9 +19,9 @@ exit_code: 0----- stdout ---------- stderr ------wt config state show - Show all cached state+wt config state get - Get all stored state-Usage: [1m[36mwt config state show[0m [36m[OPTIONS]+Usage: [1m[36mwt config state get[0m [36m[OPTIONS][1m[32mOptions:[1m[36m--format[0m[36m [0m[36m<FORMAT>@@ -42,10 +42,10 @@ Usage: [1m[36mwt config state show[0m [36m[OPTIONS][1m[36m-v[0m, [1m[36m--verboseShow commands and debug info-Shows all cached state including:+Shows all stored state including:- [1mDefault branch[0m: Cached result of querying remote for default branch-- [1mSwitch history[0m: Previous branch for [2mwt switch -+- [1mPrevious branch[0m: Previous branch for [2mwt switch -- [1mBranch markers[0m: User-defined branch notes- [1mCI status[0m: Cached GitHub/GitLab CI status per branch (30s TTL)- [1mLog files[0m: Background operation logsdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_previous_branch.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_previous_branch.snapnew file mode 100644index 000000000..bcb05a4d5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_previous_branch.snap@@ -0,0 +1,37 @@+---+source: tests/integration_tests/help.rs+info:+ program: wt+ args:+ - config+ - state+ - previous-branch+ - "--help"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_EDITOR: ""+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+wt config state previous-branch - Manage previous branch (for [1mwt switch -[0m)++Usage: [1m[36mwt config state previous-branch[0m [36m[OPTIONS][0m [36m<COMMAND>++[1m[32mCommands:+ [1m[36mget[0m Get the previous branch+ [1m[36mset[0m Set the previous branch+ [1m[36mclear[0m Clear the previous branch++[1m[32mOptions:+ [1m[36m-h[0m, [1m[36m--help[0m Print help++[1m[32mGlobal Options:+ [1m[36m-C[0m[36m [0m[36m<path>[0m Working directory for this command+ [1m[36m--config[0m[36m [0m[36m<path>[0m User config file path+ [1m[36m-v[0m, [1m[36m--verbose[0m Show commands and debug info