Skip to content

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

refactor(config-state): structured JSON for logs; drop --hook/--branch filters (#2161)

Maximilian Roos50f9b82d2cd4
diff --git a/docs/content/config.md b/docs/content/config.md
index d96c0aec1..a393358a3 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -730,16 +730,23 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). All worktrees write to the same directory. Top-level files are shared logs (command audit + diagnostics); top-level directories are per-branch log trees.
+### Structured output
+
+`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.
+
### Examples
List all log files:
-{{ terminal(cmd="wt config state logs get") }}
+{{ terminal(cmd="wt config state logs") }}
Query the command log:
{{ terminal(cmd="tail -5 .git/wt/logs/commands.jsonl | jq .") }}
-View a specific hook log:
-{{ terminal(cmd="cat __WT_QUOT__$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log__WT_QUOT__") }}
+Path to one hook log (e.g. the `post-start` `server` hook for the current branch):
+{{ terminal(cmd="wt config state logs --format=json | jq -r '.hook_output[] | select(.source == __WT_QUOT__user__WT_QUOT__ and .hook_type == __WT_QUOT__post-start__WT_QUOT__ and (.name | startswith(__WT_QUOT__server__WT_QUOT__))) | .path'") }}
+
+Logs for a specific branch:
+{{ terminal(cmd="wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith(__WT_QUOT__feature__WT_QUOT__))'") }}
Clear all logs:
{{ terminal(cmd="wt config state logs clear") }}
@@ -752,7 +759,7 @@ wt config state logs - Operation and debug logs
Usage: <b><span class=c>wt config state logs</span></b> <span class=c>[OPTIONS]</span> <span class=c>[COMMAND]</span>
<b><span class=g>Commands:</span></b>
- <b><span class=c>get</span></b> Get log file paths
+ <b><span class=c>get</span></b> List all log file paths
<b><span class=c>clear</span></b> Clear all log files
<b><span class=g>Options:</span></b>
diff --git a/docs/content/extending.md b/docs/content/extending.md
index d9d9af63c..6d46bb7fd 100644
--- a/docs/content/extending.md
+++ b/docs/content/extending.md
@@ -132,6 +132,19 @@ When both user and project config define the same alias name, both run — user
Alias names that collide with built-in step commands (`commit`, `squash`, `rebase`, etc.) are shadowed by the built-in.
+### Recipe: tail a specific hook log
+
+`wt config state logs --format=json` emits structured entries — `branch`, `source`, `hook_type`, `name`, `path`. Pipe through `jq` to resolve one entry, then wrap in an alias for quick access:
+
+```toml
+[aliases]
+# Tail the current worktree's post-start hook named {{ name }}:
+# wt step hook-log --name=server
+hook-log = '''tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name }}" '.hook_output[] | select(.branch == "{{ branch }}" and .hook_type == "post-start" and (.name == $name or (.name | startswith($name + "-")))) | .path' | head -1)"'''
+```
+
+The `startswith($name + "-")` branch matches the sanitized-with-hash form (`server-abc`) so the same alias works for hook names that required sanitization.
+
### Recipe: move or copy in-progress changes to a new worktree
Aliases compose existing commands into richer workflows. These three aliases wrap `wt switch --create` with git's stash and diff plumbing so staged, unstaged, and untracked changes can follow you into a new worktree:
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 6b3fd72e3..f16092794 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -751,11 +751,15 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). All worktrees write to the same directory. Top-level files are shared logs (command audit + diagnostics); top-level directories are per-branch log trees.
+### Structured output
+
+`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.
+
### Examples
List all log files:
```bash
-$ wt config state logs get
+$ wt config state logs
```
Query the command log:
@@ -763,9 +767,14 @@ Query the command log:
$ tail -5 .git/wt/logs/commands.jsonl | jq .
```
-View a specific hook log:
+Path to one hook log (e.g. the `post-start` `server` hook for the current branch):
+```bash
+$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+```
+
+Logs for a specific branch:
```bash
-$ cat "$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log"
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
```
Clear all logs:
@@ -781,7 +790,7 @@ wt config state logs - Operation and debug logs
Usage: wt config state logs [OPTIONS] [COMMAND]
Commands:
- get Get log file paths
+ get List all log file paths
clear Clear all log files
Options:
diff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.md
index f846b7b74..a2c4b472a 100644
--- a/skills/worktrunk/reference/extending.md
+++ b/skills/worktrunk/reference/extending.md
@@ -129,6 +129,19 @@ When both user and project config define the same alias name, both run — user
Alias names that collide with built-in step commands (`commit`, `squash`, `rebase`, etc.) are shadowed by the built-in.
+### Recipe: tail a specific hook log
+
+`wt config state logs --format=json` emits structured entries — `branch`, `source`, `hook_type`, `name`, `path`. Pipe through `jq` to resolve one entry, then wrap in an alias for quick access:
+
+```toml
+[aliases]
+# Tail the current worktree's post-start hook named {{ name }}:
+# wt step hook-log --name=server
+hook-log = '''tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name }}" '.hook_output[] | select(.branch == "{{ branch }}" and .hook_type == "post-start" and (.name == $name or (.name | startswith($name + "-")))) | .path' | head -1)"'''
+```
+
+The `startswith($name + "-")` branch matches the sanitized-with-hash form (`server-abc`) so the same alias works for hook names that required sanitization.
+
### Recipe: move or copy in-progress changes to a new worktree
Aliases compose existing commands into richer workflows. These three aliases wrap `wt switch --create` with git's stash and diff plumbing so staged, unstaged, and untracked changes can follow you into a new worktree:
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 1a7a5cbfb..e09606d3a 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -637,11 +637,15 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). All worktrees write to the same directory. Top-level files are shared logs (command audit + diagnostics); top-level directories are per-branch log trees.
+## Structured output
+
+`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.
+
## Examples
List all log files:
```console
-$ wt config state logs get
+$ wt config state logs
```
Query the command log:
@@ -649,9 +653,14 @@ Query the command log:
$ tail -5 .git/wt/logs/commands.jsonl | jq .
```
-View a specific hook log:
+Path to one hook log (e.g. the `post-start` `server` hook for the current branch):
+```console
+$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+```
+
+Logs for a specific branch:
```console
-$ cat "$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log"
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
```
Clear all logs:
@@ -1048,9 +1057,9 @@ $ wt config state marker clear --all
// Ordering: CRUD — get, clear.
#[derive(Subcommand)]
pub enum LogsAction {
- /// Get log file paths
+ /// List all log file paths
#[command(
- after_long_help = r#"Lists log files, or gets the path to a specific log.
+ after_long_help = r#"Lists every log file — command log, hook output, and diagnostics. Compose with `jq` to pick out a specific entry.
## Examples
@@ -1059,39 +1068,27 @@ List all log files:
$ wt config state logs
```
-Get path to a specific hook log:
+Get the absolute path of one post-start hook log for the current branch (use `jq` to filter):
```console
-$ wt config state logs get --hook=user:post-start:server
+$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
```
-Stream a hook's log output:
+Stream that log with `tail -f`:
```console
-$ tail -f "$(wt config state logs get --hook=user:post-start:server)"
+$ tail -f "$(wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path' | head -1)"
```
-Get log for background worktree removal:
+Logs for a background worktree removal (internal op):
```console
-$ wt config state logs get --hook=internal:remove
+$ wt config state logs --format=json | jq '.hook_output[] | select(.source == "internal" and .name == "remove")'
```
-Get log for a different branch:
+Logs for a specific branch:
```console
-$ wt config state logs get --hook=user:post-start:server --branch=feature
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
```"#
)]
- Get {
- /// Get path for a specific log file
- ///
- /// Format: source:hook-type:name (e.g., user:post-start:server) for
- /// hook commands, or internal:op (e.g., internal:remove) for internal
- /// operations.
- #[arg(long)]
- hook: Option<String>,
-
- /// Target branch (defaults to current)
- #[arg(long, add = crate::completion::branch_value_completer())]
- branch: Option<String>,
- },
+ Get,
/// Clear all log files
Clear,
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index 0d0617f64..c6590012b 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -19,7 +19,7 @@ pub use plugins::{
};
pub use show::handle_config_show;
pub use state::{
- handle_logs_get, handle_state_clear, handle_state_clear_all, handle_state_get,
+ handle_logs_list, handle_state_clear, handle_state_clear_all, handle_state_get,
handle_state_set, handle_state_show, handle_vars_clear, handle_vars_get, handle_vars_list,
handle_vars_set,
};
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index a82321679..81562c8c7 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -20,14 +20,13 @@ use color_print::cformat;
use path_slash::PathExt as _;
use worktrunk::config::config_path;
use worktrunk::git::Repository;
-use worktrunk::path::{format_path_for_display, sanitize_for_filename};
+use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
eprintln, format_heading, format_with_gutter, info_message, println, success_message,
warning_message,
};
use crate::cli::{OutputFormat, SwitchFormat};
-use crate::commands::process::HookLog;
use worktrunk::utils::epoch_now;
use super::super::list::ci_status::{CachedCiStatus, CiBranchName};
@@ -231,16 +230,49 @@ struct LogRow {
path: String,
size: u64,
modified_at: Option<u64>,
+ /// Structured hook-output segments — present for entries under branch subtrees,
+ /// absent for shared top-level files (command log, diagnostic).
+ hook_structure: Option<HookStructure>,
+}
+
+/// Structured view of a hook-output log path. Values are the on-disk (sanitized)
+/// names, so filters like `select(.source == "user")` work without splitting
+/// the relative path on `/`.
+struct HookStructure {
+ /// First path segment — sanitized branch directory (may include a short
+ /// collision-avoidance hash).
+ branch: String,
+ /// `"user"`, `"project"`, or `"internal"`.
+ source: String,
+ /// Hook type (`post-start`, `post-switch`, …) for user/project hooks;
+ /// `None` for internal operations.
+ hook_type: Option<String>,
+ /// Sanitized hook name for user/project hooks; internal op name
+ /// (e.g., `"remove"`) for internal entries.
+ name: String,
}
impl LogRow {
fn to_json(&self) -> serde_json::Value {
- serde_json::json!({
+ let mut obj = serde_json::json!({
"file": self.display_name,
"path": self.path,
"size": self.size,
"modified_at": self.modified_at,
- })
+ });
+ if let Some(s) = &self.hook_structure {
+ let map = obj.as_object_mut().expect("json! produced an object");
+ map.insert("branch".into(), s.branch.clone().into());
+ map.insert("source".into(), s.source.clone().into());
+ map.insert(
+ "hook_type".into(),
+ s.hook_type
+ .clone()
+ .map_or(serde_json::Value::Null, Into::into),
+ );
+ map.insert("name".into(), s.name.clone().into());
+ }
+ obj
}
}
@@ -259,6 +291,7 @@ fn top_level_log_row(entry: &std::fs::DirEntry) -> LogRow {
path,
size,
modified_at,
+ hook_structure: None,
}
}
@@ -280,6 +313,37 @@ fn hook_output_log_row(log_dir: &Path, entry: &HookOutputEntry) -> LogRow {
path,
size,
modified_at,
+ hook_structure: parse_hook_structure(&entry.relative_display),
+ }
+}
+
+/// Parse a hook-output relative path into its structured segments.
+///
+/// Expected layouts (enforced by the writers in `commands/process.rs`):
+/// - `{branch}/{source}/{hook_type}/{name}.log` — user/project hooks
+/// - `{branch}/internal/{op}.log` — internal operations
+///
+/// Unknown layouts (legacy flat logs, future shapes) return `None` so the
+/// entry still appears in the listing, just without structured filtering.
+fn parse_hook_structure(relative: &str) -> Option<HookStructure> {
+ let parts: Vec<&str> = relative.split('/').collect();
+ match parts.as_slice() {
+ [branch, "internal", op_log] => Some(HookStructure {
+ branch: (*branch).to_string(),
+ source: "internal".to_string(),
+ hook_type: None,
+ name: op_log.strip_suffix(".log").unwrap_or(op_log).to_string(),
+ }),
+ [branch, source, hook_type, name_log] => Some(HookStructure {
+ branch: (*branch).to_string(),
+ source: (*source).to_string(),
+ hook_type: Some((*hook_type).to_string()),
+ name: name_log
+ .strip_suffix(".log")
+ .unwrap_or(name_log)
+ .to_string(),
+ }),
+ _ => None,
}
}
@@ -430,117 +494,36 @@ pub(super) fn render_all_log_sections(out: &mut String, repo: &Repository) -> an
Ok(())
}
-// ==================== Logs Get Command ====================
+// ==================== Logs List Command ====================
-/// Handle the logs get command
-///
-/// When `hook` is None, lists all log files.
-/// When `hook` is Some, returns the path to the specific log file for that hook.
+/// List all log files — command log, hook output, and diagnostics.
///
-/// # Hook spec format
-///
-/// - `source:hook-type:name` for hook commands (e.g., `user:post-start:server`)
-/// - `internal:op` for internal operations (e.g., `internal:remove`)
-pub fn handle_logs_get(
- hook: Option<String>,
- branch: Option<String>,
- format: SwitchFormat,
-) -> anyhow::Result<()> {
+/// JSON output emits three arrays keyed by category, each entry carrying
+/// `file`, `path`, `size`, and `modified_at`. Hook-output entries additionally
+/// expose `branch`, `source`, `hook_type`, and `name` so consumers can filter
+/// with `jq` rather than parsing the slash-delimited `file` path.
+pub fn handle_logs_list(format: SwitchFormat) -> anyhow::Result<()> {
let repo = Repository::current()?;
- match hook {
- None if format == SwitchFormat::Json => {
- let (command_log, hook_output, diagnostic) = partition_log_files_json(&repo)?;
- let output = serde_json::json!({
- "command_log": command_log,
- "hook_output": hook_output,
- "diagnostic": diagnostic,
- });
- println!("{}", serde_json::to_string_pretty(&output)?);
- }
- None => {
- // No hook specified, show all log files
- let mut out = String::new();
- render_all_log_sections(&mut out, &repo)?;
-
- // Display through pager; fall back to direct stdout if pager unavailable
- if show_help_in_pager(&out, true).is_err() {
- println!("{}", out);
- }
- }
- Some(hook_spec) => {
- // Get the branch name
- let branch = match branch {
- Some(b) => b,
- None => repo.require_current_branch("get log for current branch")?,
- };
-
- let log_dir = repo.wt_logs_dir();
-
- // Parse the hook spec using HookLog
- let hook_log = HookLog::parse(&hook_spec).map_err(|e| anyhow::anyhow!("{}", e))?;
-
- // Check log directory exists
- if !log_dir.exists() {
- anyhow::bail!(
- "No log directory exists. Run a background hook first to create logs."
- );
- }
-
- // Get the expected log path
- let log_path = hook_log.path(&log_dir, &branch);
-
- if log_path.exists() {
- // Use to_slash_lossy() so Windows paths use forward slashes, consistent
- // with the relative paths in `logs list` output.
- let path_str = log_path.to_slash_lossy().into_owned();
- if format == SwitchFormat::Json {
- let output = serde_json::json!({ "path": path_str });
- println!("{}", serde_json::to_string_pretty(&output)?);
- } else {
- // Output just the path to stdout for easy piping.
- println!("{}", path_str);
- }
- return Ok(());
- }
+ if format == SwitchFormat::Json {
+ let (command_log, hook_output, diagnostic) = partition_log_files_json(&repo)?;
+ let output = serde_json::json!({
+ "command_log": command_log,
+ "hook_output": hook_output,
+ "diagnostic": diagnostic,
+ });
+ println!("{}", serde_json::to_string_pretty(&output)?);
+ return Ok(());
+ }
- // No match found — show the expected relative path and list any
- // logs that do exist for this branch.
- let expected_relative = log_path
- .strip_prefix(&log_dir)
- .unwrap_or(&log_path)
- .to_slash_lossy()
- .into_owned();
- let branch_dir = log_dir.join(sanitize_for_filename(&branch));
- let available: Vec<String> = if branch_dir.exists() {
- // Walk only the branch subtree, not every branch.
- let mut entries = Vec::new();
- walk_branch_dir(&log_dir, &branch_dir, &mut entries)?;
- entries.into_iter().map(|e| e.relative_display).collect()
- } else {
- Vec::new()
- };
+ let mut out = String::new();
+ render_all_log_sections(&mut out, &repo)?;
- if available.is_empty() {
- anyhow::bail!(cformat!(
- "No log files for branch <bold>{}</>. Run a background hook first.",
- branch
- ));
- } else {
- let details = format!(
- "Expected: {}\nAvailable: {}",
- expected_relative,
- available.join(", ")
- );
- return Err(anyhow::anyhow!(details).context(cformat!(
- "No log file matches <bold>{}</> for branch <bold>{}</>",
- hook_log.to_spec(),
- branch
- )));
- }
- }
+ // Display through pager; fall back to direct stdout if pager unavailable
+ // (matches #2155 routing --help output to stdout).
+ if show_help_in_pager(&out, true).is_err() {
+ println!("{}", out);
}
-
Ok(())
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 3ed3d8cbf..b0d0d1ee1 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -32,7 +32,7 @@ pub(crate) use alias::{AliasOptions, augment_step_help, step_alias};
pub(crate) use config::{
handle_claude_install, handle_claude_install_statusline, handle_claude_uninstall,
handle_config_create, handle_config_show, handle_config_update, handle_hints_clear,
- handle_hints_get, handle_logs_get, handle_opencode_install, handle_opencode_uninstall,
+ handle_hints_get, handle_logs_list, handle_opencode_install, handle_opencode_uninstall,
handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,
handle_state_show, handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set,
};
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 868270658..cecab0f5a 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -1,12 +1,9 @@
use anyhow::Context;
-use color_print::cformat;
use std::fs;
use std::path::{Path, PathBuf};
#[cfg(windows)]
use std::process::Command;
use std::process::Stdio;
-use std::str::FromStr;
-use strum::IntoEnumIterator;
use worktrunk::git::{HookType, Repository};
use worktrunk::path::{format_path_for_display, sanitize_for_filename};
use worktrunk::utils::epoch_now;
@@ -30,7 +27,7 @@ pub enum InternalOp {
/// Specification for a hook log file.
///
/// This is the single source of truth for hook log file paths.
-/// Used by both log creation (in `spawn_detached`) and log lookup (in `handle_logs_get`).
+/// Used by log creation in `spawn_detached` to place background hook output.
///
/// # Log file layout
///
@@ -44,13 +41,6 @@ pub enum InternalOp {
/// `sanitize_for_filename`. Already-safe names pass through unchanged; names
/// containing invalid characters have them replaced and a short
/// collision-avoidance hash appended.
-///
-/// # CLI format for lookup
-///
-/// The first segment determines the log type:
-/// - `user:hook-type:name` → User hook (e.g., `user:post-start:server`)
-/// - `project:hook-type:name` → Project hook (e.g., `project:post-create:build`)
-/// - `internal:op` → Internal operation (e.g., `internal:remove`)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookLog {
/// Hook command log: `{branch}/{source}/{hook-type}/{name}.log`
@@ -96,77 +86,6 @@ impl HookLog {
HookLog::Internal(op) => branch_dir.join("internal").join(format!("{op}.log")),
}
}
-
- /// Convert to CLI spec format (for error messages and roundtrip).
- ///
- /// Returns the format used by `parse()`: `source:hook-type:name` or `internal:op`.
- pub fn to_spec(&self) -> String {
- match self {
- HookLog::Hook {
- source,
- hook_type,
- name,
- } => format!("{}:{}:{}", source, hook_type, name),
- HookLog::Internal(op) => format!("internal:{}", op),
- }
- }
-
- /// Parse from CLI argument.
- ///
- /// # Formats
- ///
- /// The first segment determines the type:
- /// - `user:hook-type:name` → User hook log
- /// - `project:hook-type:name` → Project hook log
- /// - `internal:op` → Internal operation log
- ///
- /// # Errors
- ///
- /// Returns an error if the format is invalid or unrecognized.
- pub fn parse(s: &str) -> Result<Self, String> {
- let parts: Vec<&str> = s.split(':').collect();
-
- match parts.as_slice() {
- // internal:op
- ["internal", op_str] => {
- let op = InternalOp::from_str(op_str).map_err(|_| {
- let valid: Vec<_> = InternalOp::iter().map(|o| o.to_string()).collect();
- cformat!(
- "Unknown internal operation: <bold>{}</>. Valid: {}",
- op_str,
- valid.join(", ")
- )
- })?;
- Ok(Self::Internal(op))
- }
- // source:hook-type:name
- [source_str, hook_type_str, name] if !name.is_empty() => {
- let source = HookSource::from_str(source_str).map_err(|_| {
- cformat!(
- "Unknown source: <bold>{}</>. Valid: user, project",
- source_str
- )
- })?;
- let hook_type = HookType::from_str(hook_type_str).map_err(|_| {
- let valid: Vec<_> = HookType::iter().map(|h| h.to_string()).collect();
- cformat!(
- "Unknown hook type: <bold>{}</>. Valid: {}",
- hook_type_str,
- valid.join(", ")
- )
- })?;
- Ok(Self::Hook {
- source,
- hook_type,
- name: (*name).to_string(),
- })
- }
- _ => Err(cformat!(
- "Invalid log spec: <bold>{}</>. Format: source:hook-type:name or internal:op",
- s
- )),
- }
- }
}
/// Get the separator needed before closing brace in POSIX shell command grouping.
@@ -883,14 +802,6 @@ mod tests {
@"/repo/.git/wt/logs/main/project/pre-start/build.log"
);
- // Constructor and parse produce identical paths
- assert_eq!(
- HookLog::hook(HookSource::User, HookType::PostStart, "server").path(log_dir, "main"),
- HookLog::parse("user:post-start:server")
- .unwrap()
- .path(log_dir, "main"),
- );
-
// Internal operation path: {log_dir}/{sanitized-branch}/internal/{op}.log
assert_snapshot!(
HookLog::internal(InternalOp::Remove).path(log_dir, "main").to_slash_lossy(),
@@ -905,86 +816,6 @@ mod tests {
);
}
- #[test]
- fn test_hook_log_parse_internal() {
- let log = HookLog::parse("internal:remove").unwrap();
- assert_eq!(log, HookLog::Internal(InternalOp::Remove));
- }
-
- #[test]
- fn test_hook_log_parse_errors() {
- // Unknown source
- assert_snapshot!(HookLog::parse("invalid:post-start:server").unwrap_err(), @"Unknown source: invalid. Valid: user, project");
-
- // Unknown hook type
- assert_snapshot!(HookLog::parse("user:invalid-hook:server").unwrap_err(), @"Unknown hook type: invalid-hook. Valid: pre-switch, post-switch, pre-start, post-start, pre-commit, post-commit, pre-merge, post-merge, pre-remove, post-remove");
-
- // Unknown internal operation
- assert_snapshot!(HookLog::parse("internal:unknown").unwrap_err(), @"Unknown internal operation: unknown. Valid: remove, trash-sweep");
-
- // Invalid formats: single word, two non-internal parts, missing segment
- assert_snapshot!(HookLog::parse("remove").unwrap_err(), @"Invalid log spec: remove. Format: source:hook-type:name or internal:op");
- assert_snapshot!(HookLog::parse("foo:bar").unwrap_err(), @"Invalid log spec: foo:bar. Format: source:hook-type:name or internal:op");
- assert_snapshot!(HookLog::parse("user:").unwrap_err(), @"Invalid log spec: user:. Format: source:hook-type:name or internal:op");
-
- // Colons in hook names (ambiguous parsing)
- assert_snapshot!(HookLog::parse("user:post-start:my:server").unwrap_err(), @"Invalid log spec: user:post-start:my:server. Format: source:hook-type:name or internal:op");
-
- // Empty hook name
- assert_snapshot!(HookLog::parse("user:post-start:").unwrap_err(), @"Invalid log spec: user:post-start:. Format: source:hook-type:name or internal:op");
- }
-
- #[test]
- fn test_hook_log_roundtrip() {
- // What gets created should match what gets looked up
- use worktrunk::git::HookType;
-
- let log_dir = Path::new("/repo/.git/wt/logs");
-
- // Hook: create the same way hooks.rs does, parse the same way state.rs does
- let created = HookLog::hook(HookSource::User, HookType::PostStart, "server");
- let parsed = HookLog::parse("user:post-start:server").unwrap();
- assert_eq!(created.path(log_dir, "main"), parsed.path(log_dir, "main"));
-
- // Internal: create the same way handlers.rs does, parse from CLI
- let created = HookLog::internal(InternalOp::Remove);
- let parsed = HookLog::parse("internal:remove").unwrap();
- assert_eq!(created.path(log_dir, "main"), parsed.path(log_dir, "main"));
- }
-
- #[test]
- fn test_hook_log_to_spec_roundtrip() {
- use worktrunk::git::HookType;
-
- // Hook roundtrip: to_spec -> parse -> equals original
- let original = HookLog::hook(HookSource::User, HookType::PostStart, "server");
- let spec = original.to_spec();
- assert_eq!(spec, "user:post-start:server");
- let parsed = HookLog::parse(&spec).unwrap();
- assert_eq!(original, parsed);
-
- // Project hook
- let original = HookLog::hook(HookSource::Project, HookType::PreMerge, "lint");
- let spec = original.to_spec();
- assert_eq!(spec, "project:pre-merge:lint");
- let parsed = HookLog::parse(&spec).unwrap();
- assert_eq!(original, parsed);
-
- // Internal roundtrip
- let original = HookLog::internal(InternalOp::Remove);
- let spec = original.to_spec();
- assert_eq!(spec, "internal:remove");
- let parsed = HookLog::parse(&spec).unwrap();
- assert_eq!(original, parsed);
-
- // Trash sweep roundtrip
- let original = HookLog::internal(InternalOp::TrashSweep);
- let spec = original.to_spec();
- assert_eq!(spec, "internal:trash-sweep");
- let parsed = HookLog::parse(&spec).unwrap();
- assert_eq!(original, parsed);
- }
-
#[test]
fn test_parse_trash_entry_timestamp() {
// Simple name with trailing timestamp
diff --git a/src/main.rs b/src/main.rs
index ae62cf0e3..eafecdb18 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -50,7 +50,7 @@ use commands::{
add_approvals, clear_approvals, handle_claude_install, handle_claude_install_statusline,
handle_claude_uninstall, handle_completions, handle_config_create, handle_config_show,
handle_config_update, handle_configure_shell, handle_external_command, handle_hints_clear,
- handle_hints_get, handle_hook_show, handle_init, handle_list, handle_logs_get, handle_merge,
+ handle_hints_get, handle_hook_show, handle_init, handle_list, handle_logs_list, handle_merge,
handle_opencode_install, handle_opencode_uninstall, handle_promote, handle_rebase,
handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,
handle_state_set, handle_state_show, handle_switch, handle_unconfigure_shell,
@@ -372,8 +372,7 @@ fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {
Some(MarkerAction::Clear { branch, all }) => handle_state_clear("marker", branch, all),
},
StateCommand::Logs { action, format } => match action {
- Some(LogsAction::Get { hook, branch }) => handle_logs_get(hook, branch, format),
- None => handle_logs_get(None, None, format),
+ Some(LogsAction::Get) | None => handle_logs_list(format),
Some(LogsAction::Clear) => handle_state_clear("logs", None, false),
},
StateCommand::Hints { action, format } => match action {
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index b5c9a4b9b..15181ef52 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -1171,16 +1171,24 @@ fn test_state_get_json_with_logs(repo: TestRepo) {
"hints": [],
"hook_output": [
{
+ "branch": "bugfix",
"file": "bugfix/internal/remove.log",
+ "hook_type": null,
"modified_at": "<MTIME>",
+ "name": "remove",
"path": "_REPO_/.git/wt/logs/bugfix/internal/remove.log",
- "size": "<SIZE>"
+ "size": "<SIZE>",
+ "source": "internal"
},
{
+ "branch": "feature",
"file": "feature/user/post-start/npm.log",
+ "hook_type": "post-start",
"modified_at": "<MTIME>",
+ "name": "npm",
"path": "_REPO_/.git/wt/logs/feature/user/post-start/npm.log",
- "size": "<SIZE>"
+ "size": "<SIZE>",
+ "source": "user"
}
],
"markers": [],
@@ -1449,229 +1457,6 @@ fn test_state_hints_clear_specific_not_set(repo: TestRepo) {
assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"○ Hint nonexistent was not set");
}
-// ============================================================================
-// logs get --hook
-// ============================================================================
-
-#[rstest]
-fn test_state_logs_get_hook_returns_path(repo: TestRepo) {
- // Create wt/logs directory with a post-start log file
- let git_dir = repo.root_path().join(".git");
- let log_dir = git_dir.join("wt/logs");
- std::fs::create_dir_all(&log_dir).unwrap();
- let relative = hook_log_rel_path("main", "user", "post-start", "server");
- write_log_at(&log_dir, &relative, "server output here");
-
- // Use explicit format: source:hook-type:name
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
- .output()
- .unwrap();
- assert!(output.status.success());
- // The path should be printed to stdout for piping
- let stdout = String::from_utf8_lossy(&output.stdout);
- let expected = rel_display(&relative);
- assert!(
- stdout.contains(&expected),
- "Expected {expected} in stdout: {stdout}",
- );
-}
-
-#[rstest]
-fn test_state_logs_get_hook_format_json(repo: TestRepo) {
- // `--hook=...` combined with `--format=json` emits a JSON object
- // containing the absolute path, not a bare path line.
- let git_dir = repo.root_path().join(".git");
- let log_dir = git_dir.join("wt/logs");
- std::fs::create_dir_all(&log_dir).unwrap();
- let relative = hook_log_rel_path("main", "user", "post-start", "server");
- write_log_at(&log_dir, &relative, "server output");
-
- let output = wt_state_cmd(
- &repo,
- "logs",
- "get",
- &["--hook=user:post-start:server", "--format=json"],
- )
- .output()
- .unwrap();
- assert!(output.status.success());
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- let parsed: serde_json::Value =
- serde_json::from_str(&stdout).expect("stdout should be valid JSON");
- let path = parsed["path"].as_str().expect("path field missing");
- assert!(
- path.ends_with(&rel_display(&relative)),
- "path {path} should end with the relative log path"
- );
-}
-
-#[rstest]
-fn test_state_logs_get_hook_project_source(repo: TestRepo) {
- // Test that project source logs are found with explicit format
- let git_dir = repo.root_path().join(".git");
- let log_dir = git_dir.join("wt/logs");
- std::fs::create_dir_all(&log_dir).unwrap();
- let relative = hook_log_rel_path("main", "project", "post-start", "build");
- write_log_at(&log_dir, &relative, "build output here");
-
- // Use explicit format: source:hook-type:name
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=project:post-start:build"])
- .output()
- .unwrap();
- assert!(output.status.success());
- let stdout = String::from_utf8_lossy(&output.stdout);
- let expected = rel_display(&relative);
- assert!(
- stdout.contains(&expected),
- "Expected {expected} in stdout: {stdout}",
- );
-}
-
-#[rstest]
-fn test_state_logs_get_hook_internal_op(repo: TestRepo) {
- // Test finding an internal operation log (e.g., "internal:remove")
- let git_dir = repo.root_path().join(".git");
- let log_dir = git_dir.join("wt/logs");
- std::fs::create_dir_all(&log_dir).unwrap();
- let relative = internal_log_rel_path("main", "remove");
- write_log_at(&log_dir, &relative, "remove output");
-
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=internal:remove"])
- .output()
- .unwrap();
- assert!(output.status.success());
- let stdout = String::from_utf8_lossy(&output.stdout);
- let expected = rel_display(&relative);
- assert!(
- stdout.contains(&expected),
- "Expected {expected} in stdout: {stdout}",
- );
-}
-
-#[rstest]
-fn test_state_logs_get_hook_not_found(repo: TestRepo) {
- // Create wt/logs directory with some log files but not the requested one
- let git_dir = repo.root_path().join(".git");
- let log_dir = git_dir.join("wt/logs");
- std::fs::create_dir_all(&log_dir).unwrap();
- write_log_at(
- &log_dir,
- &hook_log_rel_path("main", "user", "post-start", "other"),
- "other output",
- );
-
- // Use explicit format: source:hook-type:name
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
- .output()
- .unwrap();
- assert!(!output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr));
-}
-
-#[rstest]
-fn test_state_logs_get_hook_no_logs_dir(repo: TestRepo) {
- // No log directory exists
- // Use explicit format: source:hook-type:name
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
- .output()
- .unwrap();
- assert!(!output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✗ No log directory exists. Run a background hook first to create logs.");
-}
-
-#[rstest]
-fn test_state_logs_get_hook_no_logs_for_branch(repo: TestRepo) {
- // Create wt/logs directory with logs for different branch
- let git_dir = repo.root_path().join(".git");
- let log_dir = git_dir.join("wt/logs");
- std::fs::create_dir_all(&log_dir).unwrap();
- write_log_at(
- &log_dir,
- &hook_log_rel_path("other-branch", "user", "post-start", "server"),
- "other output",
- );
-
- // Use explicit format: source:hook-type:name
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
- .output()
- .unwrap();
- assert!(!output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✗ No log files for branch main. Run a background hook first.");
-}
-
-#[rstest]
-fn test_state_logs_get_hook_with_branch_flag(repo: TestRepo) {
- // Create log file for a different branch
- repo.git_command()
- .args(["branch", "feature"])
- .run()
- .unwrap();
-
- let git_dir = repo.root_path().join(".git");
- let log_dir = git_dir.join("wt/logs");
- std::fs::create_dir_all(&log_dir).unwrap();
- let relative = hook_log_rel_path("feature", "user", "post-start", "dev");
- write_log_at(&log_dir, &relative, "dev output");
-
- // Use explicit format: source:hook-type:name
- let output = wt_state_cmd(
- &repo,
- "logs",
- "get",
- &["--hook=user:post-start:dev", "--branch=feature"],
- )
- .output()
- .unwrap();
- assert!(output.status.success());
- let stdout = String::from_utf8_lossy(&output.stdout);
- let expected = rel_display(&relative);
- assert!(
- stdout.contains(&expected),
- "Expected {expected} in stdout: {stdout}",
- );
-}
-
-#[rstest]
-fn test_state_logs_get_hook_invalid_format(repo: TestRepo) {
- // Test invalid hook spec format (missing required segments)
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user"])
- .output()
- .unwrap();
- assert!(!output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✗ Invalid log spec: user. Format: source:hook-type:name or internal:op");
-}
-
-#[rstest]
-fn test_state_logs_get_hook_rejects_colons_in_name(repo: TestRepo) {
- // Hook names cannot contain colons (makes parsing ambiguous)
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:my:server"])
- .output()
- .unwrap();
- assert!(!output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✗ Invalid log spec: user:post-start:my:server. Format: source:hook-type:name or internal:op");
-}
-
-#[rstest]
-fn test_state_logs_get_hook_invalid_source(repo: TestRepo) {
- // Test invalid source
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=invalid:post-start:server"])
- .output()
- .unwrap();
- assert!(!output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✗ Unknown source: invalid. Valid: user, project");
-}
-
-#[rstest]
-fn test_state_logs_get_hook_invalid_hook_type(repo: TestRepo) {
- // Test invalid hook type
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:invalid:server"])
- .output()
- .unwrap();
- assert!(!output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✗ Unknown hook type: invalid. Valid: pre-switch, post-switch, pre-start, post-start, pre-commit, post-commit, pre-merge, post-merge, pre-remove, post-remove");
-}
-
// ============================================================================
// vars
// ============================================================================
@@ -2122,6 +1907,60 @@ fn test_logs_get_json_with_files(repo: TestRepo) {
});
}
+/// Internal-op entries get `source: "internal"`, `hook_type: null`, and the
+/// op goes in `name` — so jq filters like `select(.source == "internal")`
+/// work the same as for user/project hooks.
+#[rstest]
+fn test_logs_get_json_internal_op_structure(repo: TestRepo) {
+ let log_dir = repo.root_path().join(".git/wt/logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ write_log_at(
+ &log_dir,
+ &internal_log_rel_path("feature", "remove"),
+ "remove output",
+ );
+
+ let output = wt_state_cmd(&repo, "logs", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let hook = &parsed["hook_output"][0];
+ assert_eq!(hook["source"], "internal");
+ assert_eq!(hook["hook_type"], serde_json::Value::Null);
+ assert_eq!(hook["name"], "remove");
+ assert!(hook["branch"].as_str().unwrap().starts_with("feature"));
+}
+
+/// Log files that don't match the expected branch subtree layout (`{branch}/{source}/{hook_type}/{name}.log`
+/// or `{branch}/internal/{op}.log`) still appear in the JSON listing — just
+/// without structured filter fields. Guards the defensive `_ => None` arm in
+/// `parse_hook_structure` against future path-layout regressions.
+#[rstest]
+fn test_logs_get_json_unknown_layout_has_no_structure(repo: TestRepo) {
+ let log_dir = repo.root_path().join(".git/wt/logs");
+ // 2-segment layout: branch/file.log (missing source & hook_type).
+ let relative = PathBuf::from("main").join("stray.log");
+ write_log_at(&log_dir, &relative, "stray output");
+
+ let output = wt_state_cmd(&repo, "logs", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let hook = &parsed["hook_output"][0];
+ // Entry appears with `file` and `path`, but structured fields are omitted.
+ assert_eq!(hook["file"], "main/stray.log");
+ assert!(hook["branch"].is_null());
+ assert!(hook["source"].is_null());
+ assert!(hook["hook_type"].is_null());
+ assert!(hook["name"].is_null());
+}
+
#[rstest]
fn test_ci_status_get_json(repo: TestRepo) {
let output = wt_state_cmd(&repo, "ci-status", "get", &["--format=json"])
diff --git a/tests/snapshots/integration__integration_tests__config_state__logs_get_json_with_files.snap b/tests/snapshots/integration__integration_tests__config_state__logs_get_json_with_files.snap
index 3eba082c2..801b6c615 100644
--- a/tests/snapshots/integration__integration_tests__config_state__logs_get_json_with_files.snap
+++ b/tests/snapshots/integration__integration_tests__config_state__logs_get_json_with_files.snap
@@ -21,10 +21,14 @@ expression: "String::from_utf8_lossy(&output.stdout)"
],
"hook_output": [
{
+ "branch": "main",
"file": "main/user/post-start/server.log",
+ "hook_type": "post-start",
"modified_at": "<TIMESTAMP>",
+ "name": "server",
"path": "_REPO_/.git/wt/logs/main/user/post-start/server.log",
- "size": "<SIZE>"
+ "size": "<SIZE>",
+ "source": "user"
}
]
}
diff --git a/tests/snapshots/integration__integration_tests__config_state__state_logs_get_hook_not_found.snap b/tests/snapshots/integration__integration_tests__config_state__state_logs_get_hook_not_found.snap
deleted file mode 100644
index 1ae005817..000000000
--- a/tests/snapshots/integration__integration_tests__config_state__state_logs_get_hook_not_found.snap
+++ /dev/null
@@ -1,7 +0,0 @@
----
-source: tests/integration_tests/config_state.rs
-expression: "String::from_utf8_lossy(&output.stderr)"
----
-✗ No log file matches user:post-start:server for branch main
-  Expected: main/user/post-start/server.log
-  Available: main/user/post-start/other.log
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
index 8acdcc6ed..58af6bc32 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
@@ -37,7 +37,7 @@ wt config state logs - Operation and debug logs
Usage: wt config state logs [OPTIONS] [COMMAND]
Commands:
- get Get log file paths
+ get List all log file paths
clear Clear all log files
Options:
@@ -103,16 +103,23 @@ All post-* hooks (post-start, post-switch, post-commit, post-merge) run
All logs are stored in .git/wt/logs/ (in the main worktree's git directory). All worktrees write to the same directory. Top-level files are shared logs (command audit + diagnostics); top-level directories are per-branch log trees.
+Structured output
+
+wt config state logs --format=json emits three arrays — command_log, hook_output, diagnostic. Each entry carries a file (relative), path (absolute), size, and modified_at (unix seconds). Hook-output entries additionally expose branch, source (user / project / internal), hook_type (the post-* kind, or null for internal ops), and name. Filter with jq to pick out a specific entry.
+
Examples
List all log files:
-  wt config state logs get
+  wt config state logs
Query the command log:
  tail -5 .git/wt/logs/commands.jsonl | jq .
-View a specific hook log:
-  cat "$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log"
+Path to one hook log (e.g. the post-start server hook for the current branch):
+  wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+
+Logs for a specific branch:
+  wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
Clear all logs:
  wt config state logs clear