Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: machine-readable approval state and branch-removal outcomes (#3710)
Maximilian Roos5c42c5b7d5d8
diff --git a/docs/content/config.md b/docs/content/config.mdindex 28165aaa7..b47caaeff 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -807,10 +807,32 @@ Clear only approvals for commands no longer in the project config:Clear global approvals:{{ terminal(cmd="wt config approvals clear --global") }}+Check whether an unattended run would stop for approval:+{{ terminal(cmd="wt config approvals list --format=json | jq -r .state") }}+### How approvals workApproved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.+### Reading approval state++`wt config approvals list` reads the state without prompting or writing it, so an orchestrator can find out whether a non-interactive run will stop for approval before scheduling one. `--format=json` emits:++```json+{+ "state": "approval_required",+ "commands": [+ {"phase": "post-start", "name": "dev", "template": "npm run dev", "approved": false},+ {"phase": "pre-merge", "template": "cargo test", "approved": true}+ ],+ "stale": ["some removed command"]+}+```++`state` is `no_commands` (the project declares none), `approval_required` (at least one is unapproved), or `approved`. `name` is absent for an unnamed command and for the commit-template fragment.++`stale` is separate rather than a fourth `state`, because it co-occurs with all three: these are approvals recorded earlier whose command has since been edited or removed from the project config. They are what `--yes` would silently re-approve, so an orchestrator preserving the approval model reads them before choosing that flag.+### Command reference{% terminal() %}diff --git a/docs/content/remove.md b/docs/content/remove.mdindex 68b078309..6b14753f4 100644--- a/docs/content/remove.md+++ b/docs/content/remove.md@@ -96,6 +96,22 @@ To avoid killing work the user did not mean to kill, two guards keep `--reap` coReaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.+## JSON output++`--format=json` prints one object per removal to stdout: `{kind, branch, path, branch_outcome, branch_checked_out_at}` for a worktree, with `pruned` in place of `path` for a branch-only removal.++`branch_outcome` names what happened to the branch, so a caller can tell a deletion the removal declined from one it was never asked to make:++| Value | Meaning |+|-------|---------|+| `deleted` | The branch is gone |+| `deferred` | Handed to the detached background process, whose result this run never sees. `--foreground` never reports it |+| `not_attempted` | No deletion was tried: a detached worktree, a sibling checkout, or `--no-delete-branch` |+| `retained_unmerged` | Declined: the branch was not integrated into the target |+| `retained_checked_out` | Declined: the final topology read found a live worktree with it checked out |+| `retained_raced` | Refused by the compare-and-swap — the branch moved between the integration check and the delete. Re-read the ref and retry |+| `retained_failed` | The delete command itself failed |+## Hooks`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](@/hook.md) for configuration.diff --git a/docs/content/step.md b/docs/content/step.mdindex c0db7351d..ab46cefef 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -929,6 +929,10 @@ Worktrees younger than `--min-age` (default: 1 day) are skipped. This prevents r{{ terminal(cmd="wt step prune --min-age=0s # no age guard|||wt step prune --min-age=2d # skip worktrees younger than 2 days") }}+### JSON output++`--format=json` prints one object per candidate to stdout. The two modes report different things, and name their fields accordingly: a live run reports `branch_outcome`, the executed outcome, using the vocabulary [`wt remove`](@/remove.md#json-output) documents; `--dry-run` reports `branch_deleted`, its prediction of whether the removal would take the branch, since it runs nothing to have an outcome. A dry run also carries `reason` and `target` (why the candidate qualifies, and what it was measured against).+### ExamplesPreview what would be removed:diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex e2529d6fb..83836512d 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -819,10 +819,34 @@ Clear global approvals:$ wt config approvals clear --global```+Check whether an unattended run would stop for approval:+```bash+$ wt config approvals list --format=json | jq -r .state+```+### How approvals workApproved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.+### Reading approval state++`wt config approvals list` reads the state without prompting or writing it, so an orchestrator can find out whether a non-interactive run will stop for approval before scheduling one. `--format=json` emits:++```json+{+ "state": "approval_required",+ "commands": [+ {"phase": "post-start", "name": "dev", "template": "npm run dev", "approved": false},+ {"phase": "pre-merge", "template": "cargo test", "approved": true}+ ],+ "stale": ["some removed command"]+}+```++`state` is `no_commands` (the project declares none), `approval_required` (at least one is unapproved), or `approved`. `name` is absent for an unnamed command and for the commit-template fragment.++`stale` is separate rather than a fourth `state`, because it co-occurs with all three: these are approvals recorded earlier whose command has since been edited or removed from the project config. They are what `--yes` would silently re-approve, so an orchestrator preserving the approval model reads them before choosing that flag.+### Command reference```diff --git a/plugins/worktrunk/skills/worktrunk/reference/remove.md b/plugins/worktrunk/skills/worktrunk/reference/remove.mdindex b13df326a..0eee006fd 100644--- a/plugins/worktrunk/skills/worktrunk/reference/remove.md+++ b/plugins/worktrunk/skills/worktrunk/reference/remove.md@@ -98,6 +98,22 @@ To avoid killing work the user did not mean to kill, two guards keep `--reap` coReaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.+## JSON output++`--format=json` prints one object per removal to stdout: `{kind, branch, path, branch_outcome, branch_checked_out_at}` for a worktree, with `pruned` in place of `path` for a branch-only removal.++`branch_outcome` names what happened to the branch, so a caller can tell a deletion the removal declined from one it was never asked to make:++| Value | Meaning |+|-------|---------|+| `deleted` | The branch is gone |+| `deferred` | Handed to the detached background process, whose result this run never sees. `--foreground` never reports it |+| `not_attempted` | No deletion was tried: a detached worktree, a sibling checkout, or `--no-delete-branch` |+| `retained_unmerged` | Declined: the branch was not integrated into the target |+| `retained_checked_out` | Declined: the final topology read found a live worktree with it checked out |+| `retained_raced` | Refused by the compare-and-swap — the branch moved between the integration check and the delete. Re-read the ref and retry |+| `retained_failed` | The delete command itself failed |+## Hooks`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](https://worktrunk.dev/hook/) for configuration.diff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.mdindex dea4e4d67..d2b35280c 100644--- a/plugins/worktrunk/skills/worktrunk/reference/step.md+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md@@ -972,6 +972,10 @@ $ wt step prune --min-age=0s # no age guard$ wt step prune --min-age=2d # skip worktrees younger than 2 days```+### JSON output++`--format=json` prints one object per candidate to stdout. The two modes report different things, and name their fields accordingly: a live run reports `branch_outcome`, the executed outcome, using the vocabulary [`wt remove`](https://worktrunk.dev/remove/#json-output) documents; `--dry-run` reports `branch_deleted`, its prediction of whether the removal would take the branch, since it runs nothing to have an outcome. A dry run also carries `reason` and `target` (why the candidate qualifies, and what it was measured against).+### ExamplesPreview what would be removed:diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex e2529d6fb..83836512d 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -819,10 +819,34 @@ Clear global approvals:$ wt config approvals clear --global```+Check whether an unattended run would stop for approval:+```bash+$ wt config approvals list --format=json | jq -r .state+```+### How approvals workApproved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.+### Reading approval state++`wt config approvals list` reads the state without prompting or writing it, so an orchestrator can find out whether a non-interactive run will stop for approval before scheduling one. `--format=json` emits:++```json+{+ "state": "approval_required",+ "commands": [+ {"phase": "post-start", "name": "dev", "template": "npm run dev", "approved": false},+ {"phase": "pre-merge", "template": "cargo test", "approved": true}+ ],+ "stale": ["some removed command"]+}+```++`state` is `no_commands` (the project declares none), `approval_required` (at least one is unapproved), or `approved`. `name` is absent for an unnamed command and for the commit-template fragment.++`stale` is separate rather than a fourth `state`, because it co-occurs with all three: these are approvals recorded earlier whose command has since been edited or removed from the project config. They are what `--yes` would silently re-approve, so an orchestrator preserving the approval model reads them before choosing that flag.+### Command reference```diff --git a/skills/worktrunk/reference/remove.md b/skills/worktrunk/reference/remove.mdindex b13df326a..0eee006fd 100644--- a/skills/worktrunk/reference/remove.md+++ b/skills/worktrunk/reference/remove.md@@ -98,6 +98,22 @@ To avoid killing work the user did not mean to kill, two guards keep `--reap` coReaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.+## JSON output++`--format=json` prints one object per removal to stdout: `{kind, branch, path, branch_outcome, branch_checked_out_at}` for a worktree, with `pruned` in place of `path` for a branch-only removal.++`branch_outcome` names what happened to the branch, so a caller can tell a deletion the removal declined from one it was never asked to make:++| Value | Meaning |+|-------|---------|+| `deleted` | The branch is gone |+| `deferred` | Handed to the detached background process, whose result this run never sees. `--foreground` never reports it |+| `not_attempted` | No deletion was tried: a detached worktree, a sibling checkout, or `--no-delete-branch` |+| `retained_unmerged` | Declined: the branch was not integrated into the target |+| `retained_checked_out` | Declined: the final topology read found a live worktree with it checked out |+| `retained_raced` | Refused by the compare-and-swap — the branch moved between the integration check and the delete. Re-read the ref and retry |+| `retained_failed` | The delete command itself failed |+## Hooks`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](https://worktrunk.dev/hook/) for configuration.diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex dea4e4d67..d2b35280c 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -972,6 +972,10 @@ $ wt step prune --min-age=0s # no age guard$ wt step prune --min-age=2d # skip worktrees younger than 2 days```+### JSON output++`--format=json` prints one object per candidate to stdout. The two modes report different things, and name their fields accordingly: a live run reports `branch_outcome`, the executed outcome, using the vocabulary [`wt remove`](https://worktrunk.dev/remove/#json-output) documents; `--dry-run` reports `branch_deleted`, its prediction of whether the removal would take the branch, since it runs nothing to have an outcome. A dry run also carries `reason` and `target` (why the candidate qualifies, and what it was measured against).+### ExamplesPreview what would be removed:diff --git a/src/cli/config.rs b/src/cli/config.rsindex d793e5ae1..dc1466637 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -237,13 +237,24 @@ pub enum ApprovalsCommand {#[command(after_long_help = r#"Shows every command the project config declares — hooks, aliases, and commit-message guidance — grouped into APPROVED and UNAPPROVED sections. Approvals recorded for commands no longer in the project config (edited or removed since approval) are listed separately.+Reading is all it does: no prompt, no write. `--format=json` emits the same four distinctions as a structured payload — see [Reading approval state](@/config.md#reading-approval-state).+## Examples```console$ wt config approvals list+```++Check whether an unattended run would stop for approval:+```console+$ wt config approvals list --format=json | jq -r .state```"#)]- List,+ List {+ /// Output format+ #[arg(long, default_value = "text", help_heading = "Output")]+ format: SwitchFormat,+ },/// Store approvals in approvals.toml#[command(@@ -575,9 +586,33 @@ Clear global approvals:$ wt config approvals clear --global```+Check whether an unattended run would stop for approval:+```console+$ wt config approvals list --format=json | jq -r .state+```+## How approvals work-Approved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI."#+Approved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.++## Reading approval state++`wt config approvals list` reads the state without prompting or writing it, so an orchestrator can find out whether a non-interactive run will stop for approval before scheduling one. `--format=json` emits:++```json+{+ "state": "approval_required",+ "commands": [+ {"phase": "post-start", "name": "dev", "template": "npm run dev", "approved": false},+ {"phase": "pre-merge", "template": "cargo test", "approved": true}+ ],+ "stale": ["some removed command"]+}+```++`state` is `no_commands` (the project declares none), `approval_required` (at least one is unapproved), or `approved`. `name` is absent for an unnamed command and for the commit-template fragment.++`stale` is separate rather than a fourth `state`, because it co-occurs with all three: these are approvals recorded earlier whose command has since been edited or removed from the project config. They are what `--yes` would silently re-approve, so an orchestrator preserving the approval model reads them before choosing that flag."#)]Approvals {#[command(subcommand)]diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 22de2a66e..862799a12 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1324,6 +1324,22 @@ To avoid killing work the user did not mean to kill, two guards keep `--reap` coReaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.+## JSON output++`--format=json` prints one object per removal to stdout: `{kind, branch, path, branch_outcome, branch_checked_out_at}` for a worktree, with `pruned` in place of `path` for a branch-only removal.++`branch_outcome` names what happened to the branch, so a caller can tell a deletion the removal declined from one it was never asked to make:++| Value | Meaning |+|-------|---------|+| `deleted` | The branch is gone |+| `deferred` | Handed to the detached background process, whose result this run never sees. `--foreground` never reports it |+| `not_attempted` | No deletion was tried: a detached worktree, a sibling checkout, or `--no-delete-branch` |+| `retained_unmerged` | Declined: the branch was not integrated into the target |+| `retained_checked_out` | Declined: the final topology read found a live worktree with it checked out |+| `retained_raced` | Refused by the compare-and-swap — the branch moved between the integration check and the delete. Re-read the ref and retry |+| `retained_failed` | The delete command itself failed |+## Hooks`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](@/hook.md) for configuration.diff --git a/src/cli/step.rs b/src/cli/step.rsindex de8783190..9ffb75752 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -618,6 +618,10 @@ $ wt step prune --min-age=0s # no age guard$ wt step prune --min-age=2d # skip worktrees younger than 2 days```+## JSON output++`--format=json` prints one object per candidate to stdout. The two modes report different things, and name their fields accordingly: a live run reports `branch_outcome`, the executed outcome, using the vocabulary [`wt remove`](@/remove.md#json-output) documents; `--dry-run` reports `branch_deleted`, its prediction of whether the removal would take the branch, since it runs nothing to have an outcome. A dry run also carries `reason` and `target` (why the candidate qualifies, and what it was measured against).+## ExamplesPreview what would be removed:diff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rsindex 12f508df8..9526d2774 100644--- a/src/commands/config/approvals.rs+++ b/src/commands/config/approvals.rs@@ -18,6 +18,7 @@ use worktrunk::styling::{info_message, success_message, warning_message,};+use crate::cli::SwitchFormat;use crate::commands::command_approval::approve_command_batch;use crate::commands::project_config::{ApprovableCommand, collect_commands_for_aliases, collect_commands_for_hooks,@@ -50,8 +51,38 @@ fn require_project_config(repo: &Repository) -> anyhow::Result<ProjectConfig> {.ok_or(GitError::ProjectConfigNotFound { config_path })?)}+/// One project command and whether its template is currently approved.+#[derive(serde::Serialize)]+struct JsonApprovalCommand<'a> {+ /// `post-start`, `pre-merge`, `alias`, `commit-template-append`, …+ phase: String,+ /// The command's name within its phase; absent for an unnamed command+ /// and for the commit-template fragment.+ #[serde(skip_serializing_if = "Option::is_none")]+ name: Option<&'a str>,+ template: &'a str,+ approved: bool,+}++/// Structured form of `wt config approvals list`.+///+/// `state` is the single field a caller branches on before scheduling a+/// non-interactive run; `commands` and `stale` say which commands produced it.+/// Stale approvals are their own list rather than a `state`, because they+/// co-occur with any of the three — and they are what `--yes` would silently+/// re-approve, so an orchestrator preserving the approval model has to see+/// them separately.+#[derive(serde::Serialize)]+struct JsonApprovals<'a> {+ state: &'static str,+ commands: Vec<JsonApprovalCommand<'a>>,+ /// Templates approved earlier but since edited or removed from the+ /// project config.+ stale: Vec<&'a str>,+}+/// Handle `wt config approvals list` - show approval status for all project commands-pub fn list_approvals() -> anyhow::Result<()> {+pub fn list_approvals(format: SwitchFormat) -> anyhow::Result<()> {let repo = Repository::current()?;let project_id = repo.project_identifier()?;let approvals = Approvals::load().context("Failed to load approvals")?;@@ -69,6 +100,32 @@ pub fn list_approvals() -> anyhow::Result<()> {.collect();let stale = approvals.stale_approvals(&project_id, &templates);+ if format == SwitchFormat::Json {+ let json_commands: Vec<_> = commands+ .iter()+ .map(|cmd| JsonApprovalCommand {+ phase: cmd.phase.to_string(),+ name: cmd.command.name.as_deref(),+ template: &cmd.command.template,+ approved: approvals.is_command_approved(&project_id, &cmd.command.template),+ })+ .collect();+ // An empty command set is not the same answer as an approved one, so+ // the three states aren't derivable from `commands` alone.+ let state = if json_commands.is_empty() {+ "no_commands"+ } else if json_commands.iter().any(|cmd| !cmd.approved) {+ "approval_required"+ } else {+ "approved"+ };+ return crate::commands::list::print_json(&JsonApprovals {+ state,+ commands: json_commands,+ stale,+ });+ }+if commands.is_empty() && stale.is_empty() {eprintln!("{}", info_message("No commands configured in project"));return Ok(());diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 9e13818c5..8575eda39 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -43,7 +43,7 @@ use worktrunk::trace::Span;use super::super::hook_plan::{ApprovedHookPlan, HookPlan, HookPlanBuilder};use super::super::hooks::HookAnnouncer;use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};-use super::super::worktree::RemovalPlan;+use super::super::worktree::{BranchFate, RemovalPlan};use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output};/// A candidate worktree or branch selected for removal.@@ -66,13 +66,26 @@ struct Candidate {/// reports a branch the run deliberately kept.////// Starts as the scan's prediction (what the dry run prints); on the live- /// path [`try_remove`] overwrites it with the executed- /// [`BranchFate`](crate::commands::worktree::BranchFate), so a deletion- /// the CAS refused mid-run is counted as retained, not as the plan hoped.+ /// path [`record_fate`](Self::record_fate) replaces it with the executed+ /// [`BranchFate`], so a deletion the CAS refused mid-run is counted as+ /// retained, not as the plan hoped.deletes_branch: bool,+ /// The executed fate, kept whole for `--format=json`'s `branch_outcome`.+ /// `None` on the dry-run path, which runs no removal to have an outcome —+ /// that path reports `branch_deleted`, its prediction, instead.+ fate: Option<BranchFate>,}impl Candidate {+ /// Record what a removal actually did to the branch, replacing the scan's+ /// prediction. Both fields move together — `deletes_branch` is what the+ /// summary counts, `fate` what `--format=json` names — so they are set+ /// here rather than at each call site.+ fn record_fate(&mut self, fate: BranchFate) {+ self.deletes_branch = fate.deleted();+ self.fate = Some(fate);+ }+/// Error context for `try_remove` failures: distinguishes branch-only/// removals (no worktree exists) from worktree removals.fn removal_context(&self) -> String {@@ -328,22 +341,23 @@ fn removal_mutates_registry(plan: &RemovalPlan) -> bool {}}-/// Try to remove a candidate immediately. Returns `Ok(Some(branch_deleted))`-/// if removed — the executed outcome the summary counts — `Ok(None)` if the-/// removal turned out to be a no-op, `Err` on execution error.+/// Try to remove a candidate immediately. Returns `Ok(Some(fate))` if removed+/// — the executed outcome the summary counts and `--format=json` names —+/// `Ok(None)` if the removal turned out to be a no-op, `Err` on execution+/// error.////// `plan` is the scan-time `prepare_worktree_removal` result from/// [`check_one`]; only `StaleDetached` candidates arrive without one (their/// entry is pruned directly here — there is nothing to plan). Scan-time plans/// may be stale by execution; the pre-rename `ensure_clean` and the/// branch-delete CAS re-validate what matters — and the returned-/// [`BranchFate`](crate::commands::worktree::BranchFate) is how a CAS+/// [`BranchFate`] is how a CAS/// refusal reaches the summary.fn try_remove(candidate: &Candidate,plan: Option<RemovalPlan>,ctx: &RemovalContext<'_>,-) -> anyhow::Result<Option<bool>> {+) -> anyhow::Result<Option<BranchFate>> {let _span = Span::new(format!("prune-remove:{}", candidate.label));if matches!(candidate.kind, CandidateKind::StaleDetached) {@@ -366,7 +380,7 @@ fn try_remove(.context("stale detached candidate has no worktree path")?;ctx.repo.prune_worktree_entry(path)?;// A stale detached entry has no branch to delete.- return Ok(Some(false));+ return Ok(Some(BranchFate::NotAttempted));}let plan = plan.context("candidate arrived without a removal plan")?;@@ -429,7 +443,7 @@ fn try_remove({return Ok(None);}- Ok(Some(branch_deleted))+ Ok(Some(fate))}/// One candidate skipped because its project hooks aren't yet approved.@@ -1023,6 +1037,7 @@ pub fn step_prune(path,kind,deletes_branch: outcome.deletes_branch,+ fate: None,},DryRunInfo {reason_desc: reason.description().to_string(),@@ -1180,7 +1195,8 @@ pub fn step_prune(// closes once every worker has drained the job queue and exited,// so draining it below also waits out all in-flight printing.let (job_tx, job_rx) = chan::unbounded::<RemovalJob>();- let (done_tx, done_rx) = chan::unbounded::<(Candidate, anyhow::Result<Option<bool>>)>();+ let (done_tx, done_rx) =+ chan::unbounded::<(Candidate, anyhow::Result<Option<BranchFate>>)>();let abort_ref = &abort;let removal_ctx_ref = &removal_ctx;// Empty check_items → zero workers, correctly: no jobs can queue.@@ -1287,6 +1303,7 @@ pub fn step_prune(path,kind,deletes_branch: outcome.deletes_branch,+ fate: None,};if matches!(candidate.kind, CandidateKind::Current) {deferred_current = Some((candidate, outcome.plan));@@ -1305,8 +1322,8 @@ pub fn step_prune(match result {// Record the executed outcome, not the scan's prediction —// what the summary and `--format=json` report.- Ok(Some(branch_deleted)) => {- candidate.deletes_branch = branch_deleted;+ Ok(Some(fate)) => {+ candidate.record_fate(fate);removed.push(candidate);}Ok(None) => {}@@ -1338,10 +1355,10 @@ pub fn step_prune(removed.sort_by_key(|c| c.check_idx);// Remove deferred current worktree last (cd-to-primary happens here)if let Some((mut current, plan)) = deferred_current- && let Some(branch_deleted) =+ && let Some(fate) =try_remove(¤t, plan, &removal_ctx).with_context(|| current.removal_context())?{- current.deletes_branch = branch_deleted;+ current.record_fate(fate);removed.push(current);}@@ -1353,7 +1370,7 @@ pub fn step_prune("branch": c.branch,"path": c.path,"kind": c.kind.as_str(),- "branch_deleted": c.deletes_branch,+ "branch_outcome": c.fate.map(|f| f.json_outcome()),})}).collect();@@ -1459,6 +1476,7 @@ mod tests {path: None,kind,deletes_branch: !matches!(kind, CandidateKind::StaleDetached),+ fate: None,}}diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex ea0e19430..2ea621aa3 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -96,5 +96,6 @@ pub use resolve::{compute_worktree_path, is_worktree_at_expected_path, worktree_pub(crate) use switch::SwitchPipeline;pub use switch::handle_switch_command;pub use types::{- BranchFate, MergeOperations, RemovalPlan, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,+ BranchFate, MergeOperations, RemovalPlan, RetainedReason, SharedBranchCheckout,+ SwitchBranchInfo, SwitchResult,};diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex ee4238c3b..47815cd02 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -188,11 +188,8 @@ pub enum BranchFate {NotAttempted,/// The deletion ran and the branch is gone.Deleted,- /// The deletion ran and the branch survives: SafeDelete declined an- /// unmerged branch, a final topology check found a checkout, the CAS refused- /// a moved ref, or the delete command itself failed (already narrated at- /// the site that observed it).- Retained,+ /// The deletion ran and the branch survives, for the carried reason.+ Retained(RetainedReason),/// The deletion was handed to a detached background process (the legacy/// `git worktree remove` fallback) whose outcome this process never sees.///@@ -203,21 +200,53 @@ pub enum BranchFate {Deferred,}+/// Why a deletion attempt left the branch in place.+///+/// The distinctions matter to whoever is told about them: `Raced` is the one+/// an automated caller retries (re-read the ref and try again), `Unmerged` the+/// one a user resolves with `-D`, and the other two report state that has to+/// change elsewhere first. Collapsing them loses the retry signal: the+/// fail-closed compare-and-swap in `delete_branch_if_safe` detects a moved ref+/// precisely so the caller can act on it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RetainedReason {+ /// Not integrated into the target, and deletion wasn't forced.+ Unmerged,+ /// The final topology read found a live worktree with it checked out.+ CheckedOut,+ /// The compare-and-swap was refused: the ref moved between the integration+ /// check and the delete.+ Raced,+ /// The delete command itself failed (already narrated at the site that+ /// observed it).+ Failed,+}+impl BranchFate {/// Map a synchronous deletion attempt's result. `None` means no attempt/// was made.pub fn from_result(result: Option<&anyhow::Result<BranchDeletionResult>>) -> Self {match result {None => Self::NotAttempted,- Some(Ok(r)) => match r.outcome {- BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => {- Self::Deleted- }- BranchDeletionOutcome::NotDeleted- | BranchDeletionOutcome::RetainedCheckedOut { .. }- | BranchDeletionOutcome::RetainedRaced => Self::Retained,- },- Some(Err(_)) => Self::Retained,+ Some(Ok(r)) => Self::from_outcome(&r.outcome),+ Some(Err(_)) => Self::Retained(RetainedReason::Failed),+ }+ }++ /// Map a completed deletion's outcome. The one place the mapping lives, so+ /// the paths that hold an outcome without a `Result` around it+ /// (the background fast path's post-execution read) can't classify it+ /// differently from [`from_result`](Self::from_result).+ pub fn from_outcome(outcome: &BranchDeletionOutcome) -> Self {+ match outcome {+ BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => {+ Self::Deleted+ }+ BranchDeletionOutcome::NotDeleted => Self::Retained(RetainedReason::Unmerged),+ BranchDeletionOutcome::RetainedCheckedOut { .. } => {+ Self::Retained(RetainedReason::CheckedOut)+ }+ BranchDeletionOutcome::RetainedRaced => Self::Retained(RetainedReason::Raced),}}@@ -227,6 +256,23 @@ impl BranchFate {pub fn deleted(&self) -> bool {matches!(self, Self::Deleted | Self::Deferred)}++ /// The `branch_outcome` value in `--format=json`.+ ///+ /// Names the observed outcome rather than summarising it as a boolean, so+ /// a caller can tell a race it should retry from a retention it asked for,+ /// and can tell a detached deletion nobody watched from a confirmed one.+ pub fn json_outcome(&self) -> &'static str {+ match self {+ Self::NotAttempted => "not_attempted",+ Self::Deleted => "deleted",+ Self::Deferred => "deferred",+ Self::Retained(RetainedReason::Unmerged) => "retained_unmerged",+ Self::Retained(RetainedReason::CheckedOut) => "retained_checked_out",+ Self::Retained(RetainedReason::Raced) => "retained_raced",+ Self::Retained(RetainedReason::Failed) => "retained_failed",+ }+ }}/// A validated, planned removal — what `prepare_worktree_removal` decided to@@ -354,11 +400,14 @@ impl RemovalPlan {/// Convert to a JSON value for structured output.///- /// `fate` is what execution reported back; `branch_deleted` is derived- /// from it (via [`BranchFate::deleted`]) so the payload states what- /// happened, not what the plan hoped.+ /// `fate` is what execution reported back, and `branch_outcome` names it+ /// directly (via [`BranchFate::json_outcome`]) so the payload states what+ /// happened rather than what the plan hoped. It replaced a+ /// `branch_deleted` boolean, which could not distinguish a CAS the ref+ /// moved under from a retention the caller asked for, and reported a+ /// detached deletion nobody watched as an accomplished one.pub fn to_json(&self, fate: BranchFate) -> serde_json::Value {- let branch_deleted = fate.deleted();+ let branch_outcome = fate.json_outcome();match self {RemovalPlan::Worktree {worktree_path,@@ -369,7 +418,7 @@ impl RemovalPlan {"kind": "worktree","branch": branch_name,"path": worktree_path,- "branch_deleted": branch_deleted,+ "branch_outcome": branch_outcome,"branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),RemovalPlan::BranchOnly {@@ -381,7 +430,7 @@ impl RemovalPlan {"kind": "branch_only","branch": branch_name,"pruned": prune_entry.is_some(),- "branch_deleted": branch_deleted,+ "branch_outcome": branch_outcome,"branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),}@@ -430,7 +479,7 @@ mod tests {let cases = [(BranchFate::Deleted, true),(BranchFate::Deferred, true),- (BranchFate::Retained, false),+ (BranchFate::Retained(RetainedReason::Raced), false),(BranchFate::NotAttempted, false),];for (fate, deleted) in cases {@@ -438,8 +487,43 @@ mod tests {}}- /// Synchronous deletion results map onto fates: deletions count, refusals- /// and errors read as the branch surviving, absence as never attempted.+ /// The `--format=json` vocabulary, which external callers branch on. Every+ /// fate gets its own value: a race the caller should retry never reads as+ /// a retention it asked for, and a detached deletion nobody watched never+ /// reads as a confirmed one.+ #[test]+ fn branch_fate_json_outcome_is_distinct_per_fate() {+ let cases = [+ (BranchFate::NotAttempted, "not_attempted"),+ (BranchFate::Deleted, "deleted"),+ (BranchFate::Deferred, "deferred"),+ (+ BranchFate::Retained(RetainedReason::Unmerged),+ "retained_unmerged",+ ),+ (+ BranchFate::Retained(RetainedReason::CheckedOut),+ "retained_checked_out",+ ),+ (+ BranchFate::Retained(RetainedReason::Raced),+ "retained_raced",+ ),+ (+ BranchFate::Retained(RetainedReason::Failed),+ "retained_failed",+ ),+ ];+ for (fate, expected) in cases {+ assert_eq!(fate.json_outcome(), expected, "{fate:?}");+ }+ let names: std::collections::BTreeSet<_> = cases.iter().map(|(_, name)| *name).collect();+ assert_eq!(names.len(), cases.len(), "outcome names must be distinct");+ }++ /// Synchronous deletion results map onto fates: deletions count, each+ /// refusal keeps the reason that distinguishes it, an error reads as the+ /// delete having failed, and absence as never attempted.#[test]fn branch_fate_from_result_mapping() {use worktrunk::git::IntegrationReason;@@ -462,21 +546,21 @@ mod tests {);assert_eq!(fate(BranchDeletionOutcome::NotDeleted),- BranchFate::Retained+ BranchFate::Retained(RetainedReason::Unmerged));assert_eq!(fate(BranchDeletionOutcome::RetainedCheckedOut {path: PathBuf::from("/tmp/feature"),}),- BranchFate::Retained+ BranchFate::Retained(RetainedReason::CheckedOut));assert_eq!(fate(BranchDeletionOutcome::RetainedRaced),- BranchFate::Retained+ BranchFate::Retained(RetainedReason::Raced));assert_eq!(BranchFate::from_result(Some(&Err(anyhow::anyhow!("boom")))),- BranchFate::Retained+ BranchFate::Retained(RetainedReason::Failed));assert_eq!(BranchFate::from_result(None), BranchFate::NotAttempted);}diff --git a/src/main.rs b/src/main.rsindex e36f21ce1..7edb20669 100644--- a/src/main.rs+++ b/src/main.rs@@ -157,7 +157,7 @@ fn handle_hook_command(action: HookCommand, yes: bool) -> anyhow::Result<()> {)));match action {- ApprovalsCommand::List => list_approvals(),+ ApprovalsCommand::List { format } => list_approvals(format),ApprovalsCommand::Add { all } => add_approvals(all),ApprovalsCommand::Clear { global, stale } => clear_approvals(global, stale),}@@ -633,7 +633,7 @@ fn handle_config_command(action: ConfigCommand, yes: bool) -> anyhow::Result<()>ConfigCommand::Show { full, format } => handle_config_show(full, format),ConfigCommand::Update { print } => handle_config_update(yes, print),ConfigCommand::Approvals { action } => match action {- ApprovalsCommand::List => list_approvals(),+ ApprovalsCommand::List { format } => list_approvals(format),ApprovalsCommand::Add { all } => add_approvals(all),ApprovalsCommand::Clear { global, stale } => clear_approvals(global, stale),},diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 288319c3c..595ef5a9f 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -18,7 +18,7 @@ use crate::commands::process::{};use crate::commands::worktree::hooks::PostRemoveContext;use crate::commands::worktree::{- BranchFate, RemovalPlan, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,+ BranchFate, RemovalPlan, RetainedReason, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,};use worktrunk::config::UserConfig;use worktrunk::git::ErrorExt;@@ -317,7 +317,10 @@ fn execute_instant_removal_or_fallback(}),planner_expected_retention,);- BranchFate::Retained+ // Same `NotDeleted` the warning was built from: the+ // foreground check declined, so the branch survives+ // unmerged as far as anything downstream can tell.+ BranchFate::Retained(RetainedReason::Unmerged)}};(@@ -1344,14 +1347,7 @@ fn handle_branch_only_output(}stderr().flush()?;- Ok(match deletion.result.outcome {- BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => {- BranchFate::Deleted- }- BranchDeletionOutcome::NotDeleted- | BranchDeletionOutcome::RetainedCheckedOut { .. }- | BranchDeletionOutcome::RetainedRaced => BranchFate::Retained,- })+ Ok(BranchFate::from_outcome(&deletion.result.outcome))}/// Register post-remove and post-switch hooks after worktree removal onto thediff --git a/tests/integration_tests/approvals.rs b/tests/integration_tests/approvals.rsindex a8271a772..7294af970 100644--- a/tests/integration_tests/approvals.rs+++ b/tests/integration_tests/approvals.rs@@ -31,13 +31,19 @@ fn snapshot_clear_approvals(test_name: &str, repo: &TestRepo, args: &[&str]) {});}-/// Helper to snapshot the list command+/// Snapshot the list command in both formats from one setup. The sections and+/// the JSON payload answer the same question about the same state, so every+/// scenario below covers both without restating its config.fn snapshot_list_approvals(test_name: &str, repo: &TestRepo) {let settings = setup_snapshot_settings(repo);settings.bind(|| {let mut cmd = make_snapshot_cmd(repo, "config", &[], None);cmd.arg("approvals").arg("list");assert_cmd_snapshot!(test_name, cmd);++ let mut cmd = make_snapshot_cmd(repo, "config", &[], None);+ cmd.arg("approvals").arg("list").arg("--format=json");+ assert_cmd_snapshot!(format!("{test_name}_json"), cmd);});}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 07ea2381e..ecc085a6d 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -3868,15 +3868,17 @@ fn test_remove_json_multi_with_current(mut repo: TestRepo) {assert_eq!(items[1]["kind"], "worktree");}-/// `branch_deleted` reports what execution did, not what the plan intended.+/// `branch_outcome` reports what execution did, not what the plan intended,+/// and names *why* the branch survived.////// The planner sees `feature` at main's tip and intends to delete it. A/// `pre-remove` hook then commits on the branch, so the SafeDelete's re-check/// against fresh refs finds it unmerged and declines — the worktree goes, the/// branch stays. Reporting the plan here would tell a script the branch was-/// deleted while it is still on disk.+/// deleted while it is still on disk, and reporting a bare `false` would leave+/// it unable to tell this from a retention it asked for.#[rstest]-fn test_remove_json_branch_deleted_reflects_execution(mut repo: TestRepo) {+fn test_remove_json_branch_outcome_reflects_execution(mut repo: TestRepo) {use crate::common::wait_for_worktree_removed;repo.commit("initial");@@ -3906,8 +3908,8 @@ fn test_remove_json_branch_deleted_reflects_execution(mut repo: TestRepo) {assert_eq!(items.len(), 1);assert_eq!(items[0]["branch"], "feature");assert_eq!(- items[0]["branch_deleted"], false,- "branch_deleted must report the declined deletion, not the plan's intent:\n{stderr}",+ items[0]["branch_outcome"], "retained_unmerged",+ "branch_outcome must report the declined deletion and its reason, not the plan's intent:\n{stderr}",);wait_for_worktree_removed(&feature_wt);@@ -3924,6 +3926,48 @@ fn test_remove_json_branch_deleted_reflects_execution(mut repo: TestRepo) {);}+/// A retention the caller asked for reads differently from one a guard forced.+///+/// This is the contrast the old `branch_deleted` boolean could not draw: both+/// this run and the declined deletion above left the branch standing and+/// reported `false`, so an orchestrator could not tell "I asked you to keep+/// it" from "I could not safely delete it". `--no-delete-branch` never+/// attempts a deletion, so nothing is retained — there is no outcome to name.+#[rstest]+fn test_remove_json_branch_outcome_distinguishes_requested_retention(mut repo: TestRepo) {+ repo.commit("initial");+ repo.add_worktree("feature");++ let output = repo+ .wt_command()+ .args([+ "remove",+ "feature",+ "--no-delete-branch",+ "--format=json",+ "--yes",+ "--foreground",+ ])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "remove should succeed:\n{stderr}");++ let json: serde_json::Value =+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();+ let items = json.as_array().unwrap();+ assert_eq!(items.len(), 1);+ assert_eq!(items[0]["branch"], "feature");+ assert_eq!(+ items[0]["branch_outcome"], "not_attempted",+ "a retention the caller asked for is not a deletion that was refused:\n{stderr}",+ );++ repo.run_git(&["rev-parse", "--verify", "refs/heads/feature"]);+}+/// The detached legacy fallback also corrects a broken deletion promise.////// When the rename-into-trash fast path fails, the removal falls back to a@@ -3978,8 +4022,8 @@ fn test_remove_fallback_warns_when_no_cas_tail(mut repo: TestRepo) {let json: serde_json::Value =serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();assert_eq!(- json.as_array().unwrap()[0]["branch_deleted"],- false,+ json.as_array().unwrap()[0]["branch_outcome"],+ "retained_unmerged","a survival known in the foreground is not a deferral:\n{stderr}",);// The branch survives with the hook's commit as its tip; the worktreediff --git a/tests/snapshots/integration__integration_tests__approvals__list_approvals_after_clear_stale_json.snap b/tests/snapshots/integration__integration_tests__approvals__list_approvals_after_clear_stale_json.snapnew file mode 100644index 000000000..0d78c7ecf--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approvals__list_approvals_after_clear_stale_json.snap@@ -0,0 +1,73 @@+---+source: tests/integration_tests/approvals.rs+info:+ program: wt+ args:+ - config+ - approvals+ - list+ - "--format=json"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+{+ "state": "approved",+ "commands": [+ {+ "phase": "pre-merge",+ "template": "cargo test",+ "approved": true+ }+ ],+ "stale": []+}++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approvals__list_approvals_all_approved_json.snap b/tests/snapshots/integration__integration_tests__approvals__list_approvals_all_approved_json.snapnew file mode 100644index 000000000..0d78c7ecf--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approvals__list_approvals_all_approved_json.snap@@ -0,0 +1,73 @@+---+source: tests/integration_tests/approvals.rs+info:+ program: wt+ args:+ - config+ - approvals+ - list+ - "--format=json"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+{+ "state": "approved",+ "commands": [+ {+ "phase": "pre-merge",+ "template": "cargo test",+ "approved": true+ }+ ],+ "stale": []+}++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approvals__list_approvals_mixed_json.snap b/tests/snapshots/integration__integration_tests__approvals__list_approvals_mixed_json.snapnew file mode 100644index 000000000..1496e121e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approvals__list_approvals_mixed_json.snap@@ -0,0 +1,92 @@+---+source: tests/integration_tests/approvals.rs+info:+ program: wt+ args:+ - config+ - approvals+ - list+ - "--format=json"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+{+ "state": "approval_required",+ "commands": [+ {+ "phase": "post-start",+ "name": "dev",+ "template": "npm run dev",+ "approved": false+ },+ {+ "phase": "pre-merge",+ "template": "cargo test",+ "approved": true+ },+ {+ "phase": "alias",+ "name": "deploy",+ "template": "echo deploying {{ branch }}",+ "approved": true+ },+ {+ "phase": "commit-template-append",+ "template": "Use conventional commits.",+ "approved": false+ }+ ],+ "stale": [+ "some removed command"+ ]+}++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approvals__list_approvals_no_config_json.snap b/tests/snapshots/integration__integration_tests__approvals__list_approvals_no_config_json.snapnew file mode 100644index 000000000..a843c82d6--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approvals__list_approvals_no_config_json.snap@@ -0,0 +1,67 @@+---+source: tests/integration_tests/approvals.rs+info:+ program: wt+ args:+ - config+ - approvals+ - list+ - "--format=json"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+{+ "state": "no_commands",+ "commands": [],+ "stale": []+}++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__approvals__list_approvals_stale_only_json.snap b/tests/snapshots/integration__integration_tests__approvals__list_approvals_stale_only_json.snapnew file mode 100644index 000000000..69f0ed7e8--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approvals__list_approvals_stale_only_json.snap@@ -0,0 +1,69 @@+---+source: tests/integration_tests/approvals.rs+info:+ program: wt+ args:+ - config+ - approvals+ - list+ - "--format=json"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+{+ "state": "no_commands",+ "commands": [],+ "stale": [+ "orphan command"+ ]+}++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__help__help_config_approvals.snap b/tests/snapshots/integration__integration_tests__help__help_config_approvals.snapindex 6ea7a6520..2ec6232ff 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_approvals.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_approvals.snap@@ -9,6 +9,14 @@ info:env:CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"LANG: CLC_ALL: CLLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"@@ -25,6 +33,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -81,8 +90,28 @@ Clear only approvals for commands no longer in the project config:Clear global approvals:[107m [0m [2m[0m[2m[34mwt[0m[2m config approvals clear [0m[2m[36m--global[0m+Check whether an unattended run would stop for approval:+[107m [0m [2m[0m[2m[34mwt[0m[2m config approvals list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[36m-r[0m[2m .state[0m+[1m[32mHow approvals work[0mApproved commands are saved to [2m~/.config/worktrunk/approvals.toml[0m. Re-approval is required when the command template changes or the project moves. Use [2m--yes[0m to bypass prompts in CI.+[1m[32mReading approval state[0m++[2mwt config approvals list[0m reads the state without prompting or writing it, so an orchestrator can find out whether a non-interactive run will stop for approval before scheduling one. [2m--format=json[0m emits:++[107m [0m [2m{[0m+[107m [0m [2m "state": "approval_required",[0m+[107m [0m [2m "commands": [[0m+[107m [0m [2m {"phase": "post-start", "name": "dev", "template": "npm run dev", "approved": false},[0m+[107m [0m [2m {"phase": "pre-merge", "template": "cargo test", "approved": true}[0m+[107m [0m [2m ],[0m+[107m [0m [2m "stale": ["some removed command"][0m+[107m [0m [2m}[0m++[2mstate[0m is [2mno_commands[0m (the project declares none), [2mapproval_required[0m (at least one is unapproved), or [2mapproved[0m. [2mname[0m is absent for an unnamed command and for the commit-template fragment.++[2mstale[0m is separate rather than a fourth [2mstate[0m, because it co-occurs with all three: these are approvals recorded earlier whose command has since been edited or removed from the project config. They are what [2m--yes[0m would silently re-approve, so an orchestrator preserving the approval model reads them before choosing that flag.+----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snapindex 9b225e1fa..0806c5764 100644--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap@@ -9,6 +9,13 @@ info:CLICOLOR_FORCE: "1"COLUMNS: "500"GIT_ALLOW_PROTOCOL: file+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"LANG: CLC_ALL: CLLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"@@ -179,6 +186,22 @@ To avoid killing work the user did not mean to kill, two guards keep [2m--reapReaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the [2m--force[0m flag. Unix only; on Windows [2m--reap[0m is rejected.+[1m[32mJSON output[0m++[2m--format=json[0m prints one object per removal to stdout: [2m{kind, branch, path, branch_outcome, branch_checked_out_at}[0m for a worktree, with [2mpruned[0m in place of [2mpath[0m for a branch-only removal.++[2mbranch_outcome[0m names what happened to the branch, so a caller can tell a deletion the removal declined from one it was never asked to make:++ Value Meaning+ ──────────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────+ [2mdeleted[0m The branch is gone+ [2mdeferred[0m Handed to the detached background process, whose result this run never sees. [2m--foreground[0m never reports it+ [2mnot_attempted[0m No deletion was tried: a detached worktree, a sibling checkout, or [2m--no-delete-branch[0m+ [2mretained_unmerged[0m Declined: the branch was not integrated into the target+ [2mretained_checked_out[0m Declined: the final topology read found a live worktree with it checked out+ [2mretained_raced[0m Refused by the compare-and-swap — the branch moved between the integration check and the delete. Re-read the ref and retry+ [2mretained_failed[0m The delete command itself failed+[1m[32mHooks[0m[2mpre-remove[0m hooks run before the worktree is deleted (with access to worktree files). [2mpost-remove[0m hooks run after removal. See [2mwt hook[0m for configuration.diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json.snap b/tests/snapshots/integration__integration_tests__remove__remove_json.snapindex ebbc67627..0537ba4ea 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_json.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_json.snap@@ -6,7 +6,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"{"branch": "feature","branch_checked_out_at": null,- "branch_deleted": true,+ "branch_outcome": "deleted","kind": "worktree","path": "<PATH>"}diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snapindex 717bb8fad..c060354f8 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap@@ -6,7 +6,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"{"branch": "orphan-branch","branch_checked_out_at": null,- "branch_deleted": true,+ "branch_outcome": "deleted","kind": "branch_only","pruned": false}diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snapindex 990c6b4e7..9a7eac0ea 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap@@ -6,14 +6,14 @@ expression: "String::from_utf8_lossy(&output.stdout)"{"branch": "wt-feature","branch_checked_out_at": null,- "branch_deleted": true,+ "branch_outcome": "deleted","kind": "worktree","path": "<PATH>"},{"branch": "orphan-branch","branch_checked_out_at": null,- "branch_deleted": true,+ "branch_outcome": "deleted","kind": "branch_only","pruned": false}diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snapindex f9238f141..33de888ed 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap@@ -5,7 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "merged-a",- "branch_deleted": true,+ "branch_outcome": "deleted","kind": "worktree","path": "<PATH>"}diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snapindex b8da16d58..2e8b558aa 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap@@ -5,7 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "current-merged",- "branch_deleted": true,+ "branch_outcome": "deleted","kind": "current","path": "<PATH>"}diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snapindex 9dd6fc097..db2312f73 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap@@ -5,7 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "orphan-integrated",- "branch_deleted": true,+ "branch_outcome": "deleted","kind": "branch_only","path": null}