Skip to content

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

feat: add always-on command log for hooks and LLM commands (#1088)

Maximilian Roosdc83699b2ddb
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 82a380a29..2f69e203a 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -115,6 +115,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| `.git/config` keys under `worktrunk.*` | Cached default branch, switch history, branch markers | Various commands |
| `.git/wt-cache/ci-status/*.json` | CI status cache (~1KB each) | `wt list` when `gh` or `glab` CLI is installed |
| `.git/wt-logs/*.log` | Background command output | Hooks, background `wt remove` |
+| `.git/wt-logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
None of this is tracked by git or pushed to remotes.
@@ -189,6 +190,22 @@ User hooks don't require approval (you defined them). Commands from project hook
Use `--yes` to bypass prompts (useful for CI/automation).
+### Command log
+
+All hook executions and LLM commands are recorded in `.git/wt-logs/commands.jsonl` — one JSON object per line with timestamp, command, exit code, and duration. This provides a debugging trail without requiring `-vv` verbose output. The file rotates to `commands.jsonl.old` at 1MB, bounding storage to ~2MB.
+
+View the log with `wt config state logs get`, or query directly:
+
+```bash
+# Recent commands
+tail -5 .git/wt-logs/commands.jsonl | jq .
+
+# Failed commands
+jq 'select(.exit != 0 and .exit != null)' .git/wt-logs/commands.jsonl
+```
+
+Clear with `wt config state logs clear`.
+
## Does Worktrunk work on Windows?
Yes. Core commands, shell integration, and tab completion work in both Git Bash and PowerShell. See [installation](@/worktrunk.md#install) for setup details, including avoiding the Windows Terminal `wt` conflict.
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 892b22407..554ea818c 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -109,6 +109,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| `.git/config` keys under `worktrunk.*` | Cached default branch, switch history, branch markers | Various commands |
| `.git/wt-cache/ci-status/*.json` | CI status cache (~1KB each) | `wt list` when `gh` or `glab` CLI is installed |
| `.git/wt-logs/*.log` | Background command output | Hooks, background `wt remove` |
+| `.git/wt-logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
None of this is tracked by git or pushed to remotes.
@@ -179,6 +180,22 @@ User hooks don't require approval (you defined them). Commands from project hook
Use `--yes` to bypass prompts (useful for CI/automation).
+### Command log
+
+All hook executions and LLM commands are recorded in `.git/wt-logs/commands.jsonl` — one JSON object per line with timestamp, command, exit code, and duration. This provides a debugging trail without requiring `-vv` verbose output. The file rotates to `commands.jsonl.old` at 1MB, bounding storage to ~2MB.
+
+View the log with `wt config state logs get`, or query directly:
+
+```bash
+# Recent commands
+tail -5 .git/wt-logs/commands.jsonl | jq .
+
+# Failed commands
+jq 'select(.exit != 0 and .exit != null)' .git/wt-logs/commands.jsonl
+```
+
+Clear with `wt config state logs clear`.
+
## Does Worktrunk work on Windows?
Yes. Core commands, shell integration, and tab completion work in both Git Bash and PowerShell. See [installation](https://worktrunk.dev/worktrunk/#install) for setup details, including avoiding the Windows Terminal `wt` conflict.
diff --git a/src/command_log.rs b/src/command_log.rs
new file mode 100644
index 000000000..81242f376
--- /dev/null
+++ b/src/command_log.rs
@@ -0,0 +1,284 @@
+//! Always-on logging for configured external commands.
+//!
+//! Logs hook execution and LLM commands to `.git/wt-logs/commands.jsonl` as JSONL.
+//! Provides an audit trail for debugging without requiring `-vv`.
+//!
+//! # Growth control
+//!
+//! Before each write, the file size is checked. If >1MB, the current file is
+//! renamed to `commands.jsonl.old` and a fresh file is started. This bounds
+//! storage to ~2MB worst case.
+
+use std::fs::{self, File, OpenOptions};
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+/// Maximum log file size before rotation (1MB).
+const MAX_LOG_SIZE: u64 = 1_048_576;
+
+/// Maximum command string length in log entries.
+const MAX_CMD_LENGTH: usize = 2000;
+
+static COMMAND_LOG: OnceLock<Mutex<CommandLog>> = OnceLock::new();
+
+struct CommandLog {
+ log_path: PathBuf,
+ file: Option<File>,
+ wt_command: String,
+}
+
+impl CommandLog {
+ fn new(log_dir: &Path, wt_command: &str) -> Self {
+ Self {
+ log_path: log_dir.join("commands.jsonl"),
+ file: None,
+ wt_command: wt_command.to_string(),
+ }
+ }
+
+ fn write(
+ &mut self,
+ label: &str,
+ command: &str,
+ exit_code: Option<i32>,
+ duration: Option<Duration>,
+ ) {
+ // Rotate if needed
+ if let Ok(metadata) = fs::metadata(&self.log_path)
+ && metadata.len() > MAX_LOG_SIZE
+ {
+ let old_path = self.log_path.with_extension("jsonl.old");
+ let _ = fs::rename(&self.log_path, &old_path);
+ self.file = None; // Force re-open after rotation
+ }
+
+ // Lazily open the file on first write (or after rotation)
+ if self.file.is_none() {
+ if let Some(parent) = self.log_path.parent() {
+ let _ = fs::create_dir_all(parent);
+ }
+ self.file = OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&self.log_path)
+ .ok();
+ }
+
+ let cmd_display = truncate_cmd(command);
+ let ts = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
+ let entry = serde_json::json!({
+ "ts": ts,
+ "wt": self.wt_command,
+ "label": label,
+ "cmd": cmd_display,
+ "exit": exit_code,
+ "dur_ms": duration.map(|d| d.as_millis() as u64),
+ });
+
+ // Single write_all so each JSON line is written atomically
+ let mut buf = entry.to_string();
+ buf.push('\n');
+
+ let Some(file) = self.file.as_mut() else {
+ return;
+ };
+ let _ = file.write_all(buf.as_bytes());
+ }
+}
+
+/// Initialize the command log.
+///
+/// Call once at startup after determining the repository's log directory.
+/// The log file and directory are created lazily on first write.
+pub fn init(log_dir: &Path, wt_command: &str) {
+ let logger = CommandLog::new(log_dir, wt_command);
+
+ // OnceLock::set fails if already initialized — that's fine, ignore the error
+ let _ = COMMAND_LOG.set(Mutex::new(logger));
+}
+
+/// Log an external command execution.
+///
+/// - `label`: identifies what triggered this command (e.g., "pre-merge user:lint", "commit.generation")
+/// - `command`: the shell command that was executed (truncated to 2000 chars)
+/// - `exit_code`: `None` for background commands where outcome is unknown
+/// - `duration`: `None` for background commands
+pub fn log_command(label: &str, command: &str, exit_code: Option<i32>, duration: Option<Duration>) {
+ let mutex = match COMMAND_LOG.get() {
+ Some(m) => m,
+ None => return,
+ };
+
+ let Ok(mut logger) = mutex.lock() else {
+ return;
+ };
+
+ logger.write(label, command, exit_code, duration);
+}
+
+/// Truncate a command string to `MAX_CMD_LENGTH` characters, appending `…` if truncated.
+/// Uses char_indices to find the byte boundary in a single scan.
+fn truncate_cmd(command: &str) -> String {
+ match command.char_indices().nth(MAX_CMD_LENGTH) {
+ Some((byte_idx, _)) => {
+ let mut s = command[..byte_idx].to_string();
+ s.push('…');
+ s
+ }
+ None => command.to_string(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_command_truncation_ascii() {
+ let long_cmd = "x".repeat(MAX_CMD_LENGTH + 100);
+ let truncated = truncate_cmd(&long_cmd);
+ assert_eq!(truncated.chars().count(), MAX_CMD_LENGTH + 1);
+ assert!(truncated.ends_with('…'));
+ }
+
+ #[test]
+ fn test_command_truncation_multibyte() {
+ let long_cmd = "é".repeat(MAX_CMD_LENGTH + 100);
+ let truncated = truncate_cmd(&long_cmd);
+ assert_eq!(truncated.chars().count(), MAX_CMD_LENGTH + 1);
+ assert!(truncated.ends_with('…'));
+ }
+
+ #[test]
+ fn test_command_no_truncation_when_short() {
+ let short_cmd = "echo hello";
+ let result = truncate_cmd(short_cmd);
+ assert_eq!(result, "echo hello");
+ }
+
+ #[test]
+ fn test_log_command_without_init() {
+ // Should silently do nothing when not initialized
+ log_command(
+ "test",
+ "echo hello",
+ Some(0),
+ Some(Duration::from_millis(100)),
+ );
+ }
+
+ #[test]
+ fn test_json_format() {
+ let entry = serde_json::json!({
+ "ts": "2026-02-17T10:00:00Z",
+ "wt": "wt hook pre-merge --yes",
+ "label": "pre-merge user:lint",
+ "cmd": "pre-commit run --all-files",
+ "exit": 0,
+ "dur_ms": 12345_u64,
+ });
+
+ let line = entry.to_string();
+ let parsed: serde_json::Value = serde_json::from_str(&line).unwrap();
+ assert_eq!(parsed["label"], "pre-merge user:lint");
+ assert_eq!(parsed["cmd"], "pre-commit run --all-files");
+ assert_eq!(parsed["exit"], 0);
+ assert_eq!(parsed["dur_ms"], 12345);
+ }
+
+ #[test]
+ fn test_null_values_for_background() {
+ let entry = serde_json::json!({
+ "ts": "2026-02-17T10:00:00Z",
+ "wt": "wt switch",
+ "label": "post-start user:server",
+ "cmd": "npm run dev",
+ "exit": null,
+ "dur_ms": null,
+ });
+
+ let line = entry.to_string();
+ let parsed: serde_json::Value = serde_json::from_str(&line).unwrap();
+ assert!(parsed["exit"].is_null());
+ assert!(parsed["dur_ms"].is_null());
+ }
+
+ #[test]
+ fn test_special_chars_in_command() {
+ // serde_json handles escaping automatically
+ let entry = serde_json::json!({
+ "cmd": "echo \"hello\nworld\"",
+ });
+ let line = entry.to_string();
+ let parsed: serde_json::Value = serde_json::from_str(&line).unwrap();
+ assert_eq!(parsed["cmd"], "echo \"hello\nworld\"");
+ }
+
+ #[test]
+ fn test_write_creates_file_lazily() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut logger = CommandLog::new(dir.path(), "wt test");
+
+ assert!(!dir.path().join("commands.jsonl").exists());
+ logger.write("test", "echo hi", Some(0), Some(Duration::from_millis(10)));
+ assert!(dir.path().join("commands.jsonl").exists());
+
+ let content = fs::read_to_string(dir.path().join("commands.jsonl")).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
+ assert_eq!(parsed["label"], "test");
+ assert_eq!(parsed["cmd"], "echo hi");
+ assert_eq!(parsed["exit"], 0);
+ assert_eq!(parsed["wt"], "wt test");
+ }
+
+ #[test]
+ fn test_write_appends_multiple_entries() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut logger = CommandLog::new(dir.path(), "wt test");
+
+ logger.write("a", "cmd-a", Some(0), Some(Duration::from_millis(1)));
+ logger.write("b", "cmd-b", Some(1), Some(Duration::from_millis(2)));
+
+ let content = fs::read_to_string(dir.path().join("commands.jsonl")).unwrap();
+ let lines: Vec<&str> = content.trim().lines().collect();
+ assert_eq!(lines.len(), 2);
+
+ let first: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
+ let second: serde_json::Value = serde_json::from_str(lines[1]).unwrap();
+ assert_eq!(first["label"], "a");
+ assert_eq!(second["label"], "b");
+ }
+
+ #[test]
+ fn test_rotation_at_size_limit() {
+ let dir = tempfile::tempdir().unwrap();
+ let log_path = dir.path().join("commands.jsonl");
+
+ // Write a file just over MAX_LOG_SIZE
+ let filler = "x".repeat(MAX_LOG_SIZE as usize + 1);
+ fs::write(&log_path, &filler).unwrap();
+
+ let mut logger = CommandLog::new(dir.path(), "wt test");
+ // Open the existing oversized file so the logger has a handle
+ logger.file = OpenOptions::new().append(true).open(&log_path).ok();
+
+ logger.write(
+ "rotated",
+ "echo rotated",
+ Some(0),
+ Some(Duration::from_millis(5)),
+ );
+
+ // Old file should exist with the filler content
+ let old_path = dir.path().join("commands.jsonl.old");
+ assert!(old_path.exists());
+ assert_eq!(fs::read_to_string(&old_path).unwrap(), filler);
+
+ // New file should have just the one rotated entry
+ let content = fs::read_to_string(&log_path).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
+ assert_eq!(parsed["label"], "rotated");
+ }
+}
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 71a01d0bf..bd4cd6f9c 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -72,6 +72,16 @@ pub fn require_user_config_path() -> anyhow::Result<PathBuf> {
// ==================== Log Management ====================
+/// Check if a file in `.git/wt-logs/` is a worktrunk log file.
+///
+/// Matches `.log` (hook output), `.jsonl` (command audit log), and `.jsonl.old` (rotated).
+fn is_wt_log_file(path: &std::path::Path) -> bool {
+ let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
+ return false;
+ };
+ name.ends_with(".log") || name.ends_with(".jsonl") || name.ends_with(".jsonl.old")
+}
+
/// Clear all log files from the wt-logs directory
fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
let log_dir = repo.wt_logs_dir();
@@ -84,7 +94,7 @@ fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
for entry in std::fs::read_dir(&log_dir)? {
let entry = entry?;
let path = entry.path();
- if path.is_file() && path.extension().is_some_and(|ext| ext == "log") {
+ if path.is_file() && is_wt_log_file(&path) {
std::fs::remove_file(&path)?;
cleared += 1;
}
@@ -98,27 +108,13 @@ fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
Ok(cleared)
}
-/// Render the LOG FILES section (heading + table or "(none)") into the output buffer
-pub(super) fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
- let log_dir = repo.wt_logs_dir();
- let log_dir_display = format_path_for_display(&log_dir);
-
- writeln!(
- out,
- "{}",
- format_heading("LOG FILES", Some(&format!("@ {log_dir_display}")))
- )?;
-
- if !log_dir.exists() {
- writeln!(out, "{}", format_with_gutter("(none)", None))?;
- return Ok(());
- }
-
- let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
- .filter_map(|e| e.ok())
- .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "log"))
- .collect();
+/// Check if a filename belongs to the command audit log (`.jsonl` / `.jsonl.old`).
+fn is_command_log_file(name: &str) -> bool {
+ name.ends_with(".jsonl") || name.ends_with(".jsonl.old")
+}
+/// Render a table of log file entries, or "(none)" if empty.
+fn render_log_table(out: &mut String, entries: &mut [std::fs::DirEntry]) -> std::fmt::Result {
if entries.is_empty() {
writeln!(out, "{}", format_with_gutter("(none)", None))?;
return Ok(());
@@ -133,11 +129,10 @@ pub(super) fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::R
.then_with(|| a.file_name().cmp(&b.file_name()))
});
- // Build table
let mut table = String::from("| File | Size | Age |\n");
table.push_str("|------|------|-----|\n");
- for entry in entries {
+ for entry in entries.iter() {
let path = entry.path();
let name = path.file_name().unwrap_or_default().to_string_lossy();
let meta = entry.metadata().ok();
@@ -164,6 +159,62 @@ pub(super) fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::R
Ok(())
}
+/// Render the COMMAND LOG section into the output buffer.
+pub(super) fn render_command_log(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
+ let log_dir = repo.wt_logs_dir();
+ let log_dir_display = format_path_for_display(&log_dir);
+
+ writeln!(
+ out,
+ "{}",
+ format_heading("COMMAND LOG", Some(&format!("@ {log_dir_display}")))
+ )?;
+
+ if !log_dir.exists() {
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
+ return Ok(());
+ }
+
+ let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
+ .filter_map(|e| e.ok())
+ .filter(|e| {
+ let name = e.file_name().to_string_lossy().to_string();
+ e.path().is_file() && is_command_log_file(&name)
+ })
+ .collect();
+
+ render_log_table(out, &mut entries)?;
+ Ok(())
+}
+
+/// Render the HOOK OUTPUT section into the output buffer.
+pub(super) fn render_hook_output(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
+ let log_dir = repo.wt_logs_dir();
+ let log_dir_display = format_path_for_display(&log_dir);
+
+ writeln!(
+ out,
+ "{}",
+ format_heading("HOOK OUTPUT", Some(&format!("@ {log_dir_display}")))
+ )?;
+
+ if !log_dir.exists() {
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
+ return Ok(());
+ }
+
+ let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
+ .filter_map(|e| e.ok())
+ .filter(|e| {
+ let name = e.file_name().to_string_lossy().to_string();
+ e.path().is_file() && is_wt_log_file(&e.path()) && !is_command_log_file(&name)
+ })
+ .collect();
+
+ render_log_table(out, &mut entries)?;
+ Ok(())
+}
+
// ==================== Logs Get Command ====================
/// Handle the logs get command
@@ -180,9 +231,11 @@ pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::
match hook {
None => {
- // No hook specified, show all log files (existing behavior)
+ // No hook specified, show all log files
let mut out = String::new();
- render_log_files(&mut out, &repo)?;
+ render_command_log(&mut out, &repo)?;
+ writeln!(out)?;
+ render_hook_output(&mut out, &repo)?;
// Display through pager (fall back to stderr if pager unavailable)
if show_help_in_pager(&out, true).is_err() {
@@ -326,7 +379,9 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
// TODO: Consider simplifying to just print the path and let users run `ls -al` themselves
"logs" => {
let mut out = String::new();
- render_log_files(&mut out, &repo)?;
+ render_command_log(&mut out, &repo)?;
+ writeln!(out)?;
+ render_hook_output(&mut out, &repo)?;
// Display through pager (fall back to stderr if pager unavailable)
if show_help_in_pager(&out, true).is_err() {
@@ -642,23 +697,22 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
})
.collect();
- // Get log files
+ // Get log files, partitioned into command log and hook output
let log_dir = repo.wt_logs_dir();
- let logs: Vec<serde_json::Value> = if log_dir.exists() {
- let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
- .filter_map(|e| e.ok())
- .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "log"))
- .collect();
-
- entries.sort_by(|a, b| {
- let a_time = a.metadata().and_then(|m| m.modified()).ok();
- let b_time = b.metadata().and_then(|m| m.modified()).ok();
- b_time.cmp(&a_time)
- });
+ let (command_log, hook_output): (Vec<serde_json::Value>, Vec<serde_json::Value>) =
+ if log_dir.exists() {
+ let mut all_entries: Vec<_> = std::fs::read_dir(&log_dir)?
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().is_file() && is_wt_log_file(&e.path()))
+ .collect();
+
+ all_entries.sort_by(|a, b| {
+ let a_time = a.metadata().and_then(|m| m.modified()).ok();
+ let b_time = b.metadata().and_then(|m| m.modified()).ok();
+ b_time.cmp(&a_time)
+ });
- entries
- .into_iter()
- .map(|entry| {
+ let to_json = |entry: &std::fs::DirEntry| -> serde_json::Value {
let path = entry.path();
let name = path
.file_name()
@@ -677,11 +731,22 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
"size": size,
"modified_at": modified
})
- })
- .collect()
- } else {
- vec![]
- };
+ };
+
+ let mut cmd_log = Vec::new();
+ let mut hook_out = Vec::new();
+ for entry in &all_entries {
+ let name = entry.file_name().to_string_lossy().to_string();
+ if is_command_log_file(&name) {
+ cmd_log.push(to_json(entry));
+ } else {
+ hook_out.push(to_json(entry));
+ }
+ }
+ (cmd_log, hook_out)
+ } else {
+ (vec![], vec![])
+ };
// Get hints
let hints = repo.list_shown_hints();
@@ -691,7 +756,8 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
"previous_branch": previous_branch,
"markers": markers,
"ci_status": ci_status,
- "logs": logs,
+ "command_log": command_log,
+ "hook_output": hook_output,
"hints": hints
});
@@ -786,8 +852,12 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
}
writeln!(out)?;
- // Show log files
- render_log_files(&mut out, repo)?;
+ // Show command log
+ render_command_log(&mut out, repo)?;
+ writeln!(out)?;
+
+ // Show hook output logs
+ render_hook_output(&mut out, repo)?;
// Display through pager (fall back to stderr if pager unavailable)
if let Err(e) = show_help_in_pager(&out, true) {
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index ef7811163..7e01e357f 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -221,6 +221,7 @@ pub fn spawn_background_hooks(
// Use HookLog with the command's own hook_type for consistent log file naming
let hook_log = HookLog::hook(cmd.source, cmd.hook_type, &name);
+ let log_label = format!("{} {}", cmd.hook_type, cmd.summary_name());
if let Err(err) = spawn_detached(
ctx.repo,
ctx.worktree_path,
@@ -235,6 +236,9 @@ pub fn spawn_background_hooks(
None => format!("Failed to spawn command: {err_msg}"),
};
eprintln!("{}", warning_message(message));
+ } else {
+ // Background: outcome unknown, log with null exit/duration
+ worktrunk::command_log::log_command(&log_label, &cmd.prepared.expanded, None, None);
}
}
@@ -342,10 +346,12 @@ pub fn run_hook_with_filter(
for cmd in commands {
cmd.announce()?;
+ let log_label = format!("{} {}", cmd.hook_type, cmd.summary_name());
if let Err(err) = execute_command_in_worktree(
ctx.worktree_path,
&cmd.prepared.expanded,
Some(&cmd.prepared.context_json),
+ Some(&log_label),
) {
// Extract raw message and exit code from error
let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {
diff --git a/src/lib.rs b/src/lib.rs
index 0b744b8dd..8e866b5d8 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -7,6 +7,7 @@
//! with worktrunk, please [open an issue](https://github.com/max-sixty/worktrunk/issues)
//! to discuss your use case.
+pub mod command_log;
pub mod config;
pub mod git;
pub mod path;
diff --git a/src/llm.rs b/src/llm.rs
index 2f3f7b356..809d594a4 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -306,6 +306,7 @@ pub(crate) fn execute_llm_command(command: &str, prompt: &str) -> anyhow::Result
let output = Cmd::new(shell.executable.to_string_lossy())
.args(&shell.args)
.arg(command)
+ .external("commit.generation")
.stdin_bytes(prompt)
.env_remove("CLAUDECODE")
.run()
diff --git a/src/main.rs b/src/main.rs
index d5a8fe6c0..73bdf07a4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -150,6 +150,12 @@ fn main() {
let verbose_level = cli.verbose;
let command_line = std::env::args().collect::<Vec<_>>().join(" ");
+ // Initialize command log for always-on logging of hooks and LLM commands.
+ // Directory and file are created lazily on first log_command() call.
+ if let Ok(repo) = worktrunk::git::Repository::current() {
+ worktrunk::command_log::init(&repo.wt_logs_dir(), &command_line);
+ }
+
// Set global verbosity level for styled verbose output
output::set_verbosity(verbose_level);
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 43ef769cf..6602504c6 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1125,6 +1125,7 @@ pub fn execute_command_in_worktree(
worktree_path: &std::path::Path,
command: &str,
stdin_content: Option<&str>,
+ command_log_label: Option<&str>,
) -> anyhow::Result<()> {
// Flush stdout before executing command to ensure all our messages appear
// before the child process output
@@ -1142,6 +1143,10 @@ pub fn execute_command_in_worktree(
.stdout(Stdio::from(std::io::stderr()))
.forward_signals();
+ if let Some(label) = command_log_label {
+ cmd = cmd.external(label);
+ }
+
if let Some(content) = stdin_content {
cmd = cmd.stdin_bytes(content);
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index d3fcebacc..d3471d716 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -375,6 +375,9 @@ pub struct Cmd {
stdin_cfg: Option<std::process::Stdio>,
/// If true, forward signals to child process group (for stream(), Unix only)
forward_signals: bool,
+ /// When set, log this command to the command log after execution.
+ /// The label identifies what triggered the command (e.g., "pre-merge user:lint").
+ external_label: Option<String>,
}
impl Cmd {
@@ -396,6 +399,7 @@ impl Cmd {
stdout_cfg: None,
stdin_cfg: None,
forward_signals: false,
+ external_label: None,
}
}
@@ -419,6 +423,7 @@ impl Cmd {
stdout_cfg: None,
stdin_cfg: None,
forward_signals: false,
+ external_label: None,
}
}
@@ -515,6 +520,15 @@ impl Cmd {
self
}
+ /// Mark this command as an external (user-configured) command for logging.
+ ///
+ /// When set, the command execution is logged to `.git/wt-logs/commands.jsonl`
+ /// with the given label (e.g., "pre-merge user:lint", "commit.generation").
+ pub fn external(mut self, label: impl Into<String>) -> Self {
+ self.external_label = Some(label.into());
+ self
+ }
+
/// Execute the command and return its output.
///
/// Captures stdout/stderr and returns them in `Output`. For interactive
@@ -650,6 +664,15 @@ impl Cmd {
}
}
+ // Log to command log if this is an external command
+ if let Some(label) = &self.external_label {
+ let (exit_code, duration) = match &result {
+ Ok(output) => (output.status.code(), Some(t0.elapsed())),
+ Err(_) => (None, Some(t0.elapsed())),
+ };
+ crate::command_log::log_command(label, &cmd_str, exit_code, duration);
+ }
+
result
}
@@ -667,7 +690,7 @@ impl Cmd {
/// shell (`sh -c` on Unix, Git Bash on Windows).
///
/// Returns error if command exits with non-zero status.
- pub fn stream(self) -> anyhow::Result<()> {
+ pub fn stream(mut self) -> anyhow::Result<()> {
#[cfg(unix)]
use {
signal_hook::consts::{SIGINT, SIGTERM},
@@ -675,6 +698,11 @@ impl Cmd {
std::os::unix::process::CommandExt,
};
+ // Extract external label for command logging (must happen before self is consumed).
+ // t0 is Some iff external_label is Some — both initialized together so timing is accurate.
+ let external_label = self.external_label.take();
+ let t0 = external_label.as_ref().map(|_| Instant::now());
+
// Shell-wrapped commands don't use args (the command string is the full command)
assert!(
!self.shell_wrap || self.args.is_empty(),
@@ -705,6 +733,14 @@ impl Cmd {
format!("{} {}", self.program, self.args.join(" "))
};
+ // Closure for command log entries (deduplicates 4 exit-path logging blocks)
+ let log_external = |exit_code: Option<i32>| {
+ if let Some(label) = &external_label {
+ let duration = t0.map(|t| t.elapsed());
+ crate::command_log::log_command(label, &cmd_str, exit_code, duration);
+ }
+ };
+
// Log command for debugging (output goes to logger, not stdout/stderr)
match &self.context {
Some(ctx) => log::debug!("$ {} [{}] (streaming, {})", cmd_str, ctx, exec_mode),
@@ -814,6 +850,7 @@ impl Cmd {
// Handle signals (Unix only)
#[cfg(unix)]
if let Some(sig) = seen_signal {
+ log_external(Some(128 + sig));
return Err(WorktrunkError::ChildProcessExited {
code: 128 + sig,
message: format!("terminated by signal {}", sig),
@@ -823,6 +860,7 @@ impl Cmd {
#[cfg(unix)]
if let Some(sig) = std::os::unix::process::ExitStatusExt::signal(&status) {
+ log_external(Some(128 + sig));
return Err(WorktrunkError::ChildProcessExited {
code: 128 + sig,
message: format!("terminated by signal {}", sig),
@@ -832,6 +870,7 @@ impl Cmd {
if !status.success() {
let code = status.code().unwrap_or(1);
+ log_external(status.code());
return Err(WorktrunkError::ChildProcessExited {
code,
message: format!("exit status: {}", code),
@@ -839,6 +878,8 @@ impl Cmd {
.into());
}
+ log_external(Some(0));
+
Ok(())
}
}
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 5a4a168e6..83f19e859 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -24,8 +24,9 @@ fn internal_log_filename(branch: &str, op: &str) -> String {
/// Settings for `wt config state get` snapshots (normalizes log paths)
fn state_get_settings() -> insta::Settings {
let mut settings = insta::Settings::clone_current();
- // LOG FILES path varies per test (temp dir), normalize for stable snapshots
- settings.add_filter(r"(LOG FILES\x1b\[39m\s+@ )[^\n]+", "${1}<PATH>");
+ // COMMAND LOG / HOOK OUTPUT paths vary per test (temp dir), normalize for stable snapshots
+ settings.add_filter(r"(COMMAND LOG\x1b\[39m\s+@ )[^\n]+", "${1}<PATH>");
+ settings.add_filter(r"(HOOK OUTPUT\x1b\[39m\s+@ )[^\n]+", "${1}<PATH>");
settings
}
@@ -470,8 +471,12 @@ fn test_state_get_logs_empty(repo: TestRepo) {
// Path is dynamic (temp dir), so check pattern instead of exact snapshot
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- stderr.contains("LOG FILES"),
- "Expected LOG FILES heading: {stderr}"
+ stderr.contains("COMMAND LOG"),
+ "Expected COMMAND LOG heading: {stderr}"
+ );
+ assert!(
+ stderr.contains("HOOK OUTPUT"),
+ "Expected HOOK OUTPUT heading: {stderr}"
);
// Path separator varies by platform, so check for either / or \
assert!(
@@ -482,7 +487,7 @@ fn test_state_get_logs_empty(repo: TestRepo) {
#[rstest]
fn test_state_get_logs_with_files(repo: TestRepo) {
- // Create wt-logs directory with some log files
+ // Create wt-logs directory with hook output and command log files
let git_dir = repo.root_path().join(".git");
let log_dir = git_dir.join("wt-logs");
std::fs::create_dir_all(&log_dir).unwrap();
@@ -492,30 +497,30 @@ fn test_state_get_logs_with_files(repo: TestRepo) {
)
.unwrap();
std::fs::write(log_dir.join("bugfix-remove.log"), "remove output").unwrap();
+ std::fs::write(log_dir.join("commands.jsonl"), r#"{"ts":"2026-01-01"}"#).unwrap();
let output = wt_state_cmd(&repo, "logs", "get", &[]).output().unwrap();
assert!(output.status.success());
- // Verify we get a table with file info
let stderr = String::from_utf8_lossy(&output.stderr);
+ // Verify both sections are present
assert!(
- stderr.contains("LOG FILES"),
- "Expected LOG FILES heading: {stderr}"
+ stderr.contains("COMMAND LOG"),
+ "Expected COMMAND LOG heading: {stderr}"
);
- // Path separator varies by platform, so check for either / or \
assert!(
- stderr.contains(".git/wt-logs") || stderr.contains(".git\\wt-logs"),
- "Expected .git/wt-logs or .git\\wt-logs in output: {stderr}"
+ stderr.contains("HOOK OUTPUT"),
+ "Expected HOOK OUTPUT heading: {stderr}"
);
- assert!(stderr.contains("File"));
- assert!(stderr.contains("Size"));
- assert!(stderr.contains("Age"));
+ // Command log section shows jsonl file
+ assert!(stderr.contains("commands.jsonl"));
+ // Hook output section shows .log files
assert!(stderr.contains("feature-post-start-npm.log"));
assert!(stderr.contains("bugfix-remove.log"));
}
#[rstest]
fn test_state_get_logs_dir_exists_no_log_files(repo: TestRepo) {
- // Create wt-logs directory with non-.log files (empty of actual log files)
+ // Create wt-logs directory with non-log files (empty of actual log files)
let git_dir = repo.root_path().join(".git");
let log_dir = git_dir.join("wt-logs");
std::fs::create_dir_all(&log_dir).unwrap();
@@ -524,16 +529,19 @@ fn test_state_get_logs_dir_exists_no_log_files(repo: TestRepo) {
let output = wt_state_cmd(&repo, "logs", "get", &[]).output().unwrap();
assert!(output.status.success());
- // Should show "(none)" since no .log files exist
+ // Both sections should show "(none)" since no log files exist
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- stderr.contains("LOG FILES"),
- "Expected LOG FILES heading: {stderr}"
+ stderr.contains("COMMAND LOG"),
+ "Expected COMMAND LOG heading: {stderr}"
);
assert!(
- stderr.contains("(none)"),
- "Expected (none) when log dir exists but has no .log files: {stderr}"
+ stderr.contains("HOOK OUTPUT"),
+ "Expected HOOK OUTPUT heading: {stderr}"
);
+ // Count "(none)" occurrences — should appear twice (once per section)
+ let none_count = stderr.matches("(none)").count();
+ assert_eq!(none_count, 2, "Expected two (none) entries: {stderr}");
}
#[rstest]
@@ -545,16 +553,17 @@ fn test_state_clear_logs_empty(repo: TestRepo) {
#[rstest]
fn test_state_clear_logs_with_files(repo: TestRepo) {
- // Create wt-logs directory with some log files
+ // Create wt-logs directory with hook output and command log files
let git_dir = repo.root_path().join(".git");
let log_dir = git_dir.join("wt-logs");
std::fs::create_dir_all(&log_dir).unwrap();
std::fs::write(log_dir.join("feature-post-start-npm.log"), "npm output").unwrap();
std::fs::write(log_dir.join("bugfix-remove.log"), "remove output").unwrap();
+ std::fs::write(log_dir.join("commands.jsonl"), "jsonl data").unwrap();
let output = wt_state_cmd(&repo, "logs", "clear", &[]).output().unwrap();
assert!(output.status.success());
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✓ Cleared 2 log files");
+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✓ Cleared 3 log files");
// Verify logs are gone
assert!(!log_dir.exists());
@@ -686,7 +695,10 @@ fn test_state_get_empty(repo: TestRepo) {
HINTS
  (none)
- LOG FILES @ <PATH>
+ COMMAND LOG @ <PATH>
+   (none)
+
+ HOOK OUTPUT @ <PATH>
  (none)
");
});
@@ -788,7 +800,8 @@ fn test_state_get_json_empty(repo: TestRepo) {
assert_eq!(json["markers"], serde_json::json!([]));
assert_eq!(json["ci_status"], serde_json::json!([]));
assert_eq!(json["hints"], serde_json::json!([]));
- assert_eq!(json["logs"], serde_json::json!([]));
+ assert_eq!(json["command_log"], serde_json::json!([]));
+ assert_eq!(json["hook_output"], serde_json::json!([]));
}
#[rstest]
@@ -845,12 +858,13 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {
#[rstest]
fn test_state_get_json_with_logs(repo: TestRepo) {
- // Create log files
+ // Create hook output and command log files
let git_dir = repo.root_path().join(".git");
let log_dir = git_dir.join("wt-logs");
std::fs::create_dir_all(&log_dir).unwrap();
std::fs::write(log_dir.join("feature-post-start-npm.log"), "npm output").unwrap();
std::fs::write(log_dir.join("bugfix-remove.log"), "remove log output").unwrap();
+ std::fs::write(log_dir.join("commands.jsonl"), r#"{"ts":"2026-01-01"}"#).unwrap();
let output = wt_state_get_json_cmd(&repo).output().unwrap();
assert!(output.status.success());
@@ -858,21 +872,26 @@ fn test_state_get_json_with_logs(repo: TestRepo) {
let json_str = String::from_utf8_lossy(&output.stdout);
let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();
- // Check logs - they should be present and have expected fields
- let logs = json["logs"].as_array().unwrap();
- assert_eq!(logs.len(), 2);
-
- // Logs are sorted by modified time (newest first), but in test both are same time
- // Just check that both log files are present with expected fields
- let log_files: Vec<&str> = logs.iter().map(|l| l["file"].as_str().unwrap()).collect();
+ // Check command_log — should contain the commands.jsonl file
+ let command_log = json["command_log"].as_array().unwrap();
+ assert_eq!(command_log.len(), 1);
+ assert_eq!(command_log[0]["file"], "commands.jsonl");
+
+ // Check hook_output — should contain the .log files
+ let hook_output = json["hook_output"].as_array().unwrap();
+ assert_eq!(hook_output.len(), 2);
+ let log_files: Vec<&str> = hook_output
+ .iter()
+ .map(|l| l["file"].as_str().unwrap())
+ .collect();
assert!(log_files.contains(&"feature-post-start-npm.log"));
assert!(log_files.contains(&"bugfix-remove.log"));
- // Each log entry should have file, size, and modified_at
- for log in logs {
- assert!(log.get("file").is_some());
- assert!(log.get("size").is_some());
- assert!(log.get("modified_at").is_some());
+ // Each entry should have file, size, and modified_at
+ for entry in command_log.iter().chain(hook_output.iter()) {
+ assert!(entry.get("file").is_some());
+ assert!(entry.get("size").is_some());
+ assert!(entry.get("modified_at").is_some());
}
}
diff --git a/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap b/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap
index 21f817db8..ec4a77f8f 100644
--- a/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap
+++ b/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap
@@ -22,7 +22,10 @@ expression: "String::from_utf8_lossy(&output.stderr)"
HINTS
  (none)
-LOG FILES @ <PATH>
+COMMAND LOG @ <PATH>
+  (none)
+
+HOOK OUTPUT @ <PATH>
File Size Age
────────────────────────── ──── ──────
bugfix-remove.log 13B future
diff --git a/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap b/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap
index 723d128b8..2acfe1b6e 100644
--- a/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap
+++ b/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap
@@ -21,5 +21,8 @@ expression: "String::from_utf8_lossy(&output.stderr)"
HINTS
  (none)
-LOG FILES @ <PATH>
+COMMAND LOG @ <PATH>
+  (none)
+
+HOOK OUTPUT @ <PATH>
  (none)