Skip to content

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

refactor(logs): nest hook output by branch/source/hook-type/name (#2041)

Maximilian Roosf8f291b37201
diff --git a/CLAUDE.md b/CLAUDE.md
index 67af7eff5..4e81c40c4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -240,10 +240,12 @@ When no structured alternative exists, document the fragility inline.
## Hook Output Logs
-Hook output logs are centralized in `.git/wt/logs/` (main worktree's git directory). Same operation on same branch overwrites the previous log.
+Hook output logs are centralized in `.git/wt/logs/` (main worktree's git directory). Per-branch logs live in subtrees; same operation on same branch overwrites the previous log.
-- **Background hooks**: `{branch}-{hash}-{source}-{hook-type}-{name}-{hash}.log` (source: `user` or `project`)
-- **Background removal**: `{branch}-{hash}-remove.log`
+- **Background hooks**: `{branch}/{source}/{hook-type}/{name}.log` (source: `user` or `project`)
+- **Background removal**: `{branch}/internal/remove.log`
+
+Top-level *files* are shared logs (`commands.jsonl*`, `verbose.log`, `diagnostic.md`); top-level *directories* are per-branch log trees. Branch and hook names are sanitized via `sanitize_for_filename` (invalid characters → `-`; short collision-avoidance hash appended).
## Coverage
diff --git a/docs/content/config.md b/docs/content/config.md
index 8afb79475..b6d012b94 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -908,12 +908,14 @@ The command log appends entries and is not branch-specific — it records all ac
#### Hook output logs
-| Operation | Log file |
+Hook output lives in per-branch subtrees under `.git/wt/logs/{branch}/`:
+
+| Operation | Log path |
|-----------|----------|
-| Background hooks | `{branch}-{hash}-{source}-{hook-type}-{name}-{hash}.log` |
-| Background removal | `{branch}-{hash}-remove.log` |
+| Background hooks | `{branch}/{source}/{hook-type}/{name}.log` |
+| Background removal | `{branch}/internal/remove.log` |
-All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is `user` or `project`. Hash suffixes are added by filename sanitization. Same operation on same branch overwrites the previous log. Logs from deleted branches remain until manually cleared.
+All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is `user` or `project`. Branch and hook names are sanitized for filesystem safety (invalid characters → `-`; short collision-avoidance hash appended). Same operation on same branch overwrites the previous log. Removing a branch clears its subtree; orphans from deleted branches can be swept with `wt config state logs clear`.
#### Diagnostic files
@@ -926,7 +928,7 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
### Location
-All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). All worktrees write to the same directory.
+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.
### Examples
@@ -937,7 +939,7 @@ 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-a1b-project-post-start-build-seq.log__WT_QUOT__") }}
+{{ terminal(cmd="cat __WT_QUOT__$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log__WT_QUOT__") }}
Clear all logs:
{{ terminal(cmd="wt config state logs clear") }}
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 350345154..6c01bc9f8 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -115,7 +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, custom variables | 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/{branch}-*.log` | Background hook output | Hooks, background `wt remove` |
+| `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
| `.git/wt/logs/verbose.log` | Debug log for issue reporting | Running with `-vv` |
| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` when warnings occur |
diff --git a/docs/content/remove.md b/docs/content/remove.md
index fc26b3591..583540202 100644
--- a/docs/content/remove.md
+++ b/docs/content/remove.md
@@ -61,9 +61,9 @@ Without `--force`, removal fails if the worktree contains untracked files. Witho
## Background removal
-Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}/internal/remove.log`. Use `--foreground` to run in the foreground.
-After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full). The sweep's log lives at `.git/wt/logs/wt-boj/internal/trash-sweep.log` (the `wt` pseudo-branch is sanitized via `sanitize_for_filename` like any other branch name).
## Hooks
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 00d5bd51b..7f6ea936a 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -933,12 +933,14 @@ The command log appends entries and is not branch-specific — it records all ac
#### Hook output logs
-| Operation | Log file |
+Hook output lives in per-branch subtrees under `.git/wt/logs/{branch}/`:
+
+| Operation | Log path |
|-----------|----------|
-| Background hooks | `{branch}-{hash}-{source}-{hook-type}-{name}-{hash}.log` |
-| Background removal | `{branch}-{hash}-remove.log` |
+| Background hooks | `{branch}/{source}/{hook-type}/{name}.log` |
+| Background removal | `{branch}/internal/remove.log` |
-All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is `user` or `project`. Hash suffixes are added by filename sanitization. Same operation on same branch overwrites the previous log. Logs from deleted branches remain until manually cleared.
+All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is `user` or `project`. Branch and hook names are sanitized for filesystem safety (invalid characters → `-`; short collision-avoidance hash appended). Same operation on same branch overwrites the previous log. Removing a branch clears its subtree; orphans from deleted branches can be swept with `wt config state logs clear`.
#### Diagnostic files
@@ -951,7 +953,7 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
### Location
-All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). All worktrees write to the same directory.
+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.
### Examples
@@ -967,7 +969,7 @@ $ tail -5 .git/wt/logs/commands.jsonl | jq .
View a specific hook log:
```bash
-$ cat "$(git rev-parse --git-dir)/wt/logs/feature-a1b-project-post-start-build-seq.log"
+$ cat "$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log"
```
Clear all logs:
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 988cc956f..569883ca6 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -108,7 +108,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, custom variables | 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/{branch}-*.log` | Background hook output | Hooks, background `wt remove` |
+| `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
| `.git/wt/logs/verbose.log` | Debug log for issue reporting | Running with `-vv` |
| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` when warnings occur |
diff --git a/skills/worktrunk/reference/remove.md b/skills/worktrunk/reference/remove.md
index a5cd3dd91..7ae4c8b69 100644
--- a/skills/worktrunk/reference/remove.md
+++ b/skills/worktrunk/reference/remove.md
@@ -65,9 +65,9 @@ Without `--force`, removal fails if the worktree contains untracked files. Witho
## Background removal
-Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}/internal/remove.log`. Use `--foreground` to run in the foreground.
-After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full). The sweep's log lives at `.git/wt/logs/wt-boj/internal/trash-sweep.log` (the `wt` pseudo-branch is sanitized via `sanitize_for_filename` like any other branch name).
## Hooks
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 5c83ce015..4e47e1cd3 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -629,12 +629,14 @@ The command log appends entries and is not branch-specific — it records all ac
### Hook output logs
-| Operation | Log file |
+Hook output lives in per-branch subtrees under `.git/wt/logs/{branch}/`:
+
+| Operation | Log path |
|-----------|----------|
-| Background hooks | `{branch}-{hash}-{source}-{hook-type}-{name}-{hash}.log` |
-| Background removal | `{branch}-{hash}-remove.log` |
+| Background hooks | `{branch}/{source}/{hook-type}/{name}.log` |
+| Background removal | `{branch}/internal/remove.log` |
-All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is `user` or `project`. Hash suffixes are added by filename sanitization. Same operation on same branch overwrites the previous log. Logs from deleted branches remain until manually cleared.
+All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is `user` or `project`. Branch and hook names are sanitized for filesystem safety (invalid characters → `-`; short collision-avoidance hash appended). Same operation on same branch overwrites the previous log. Removing a branch clears its subtree; orphans from deleted branches can be swept with `wt config state logs clear`.
### Diagnostic files
@@ -647,7 +649,7 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
## Location
-All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). All worktrees write to the same directory.
+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.
## Examples
@@ -663,7 +665,7 @@ $ tail -5 .git/wt/logs/commands.jsonl | jq .
View a specific hook log:
```console
-$ cat "$(git rev-parse --git-dir)/wt/logs/feature-a1b-project-post-start-build-seq.log"
+$ cat "$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log"
```
Clear all logs:
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index c87485058..49999f106 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -975,9 +975,9 @@ Without `--force`, removal fails if the worktree contains untracked files. Witho
## Background removal
-Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}/internal/remove.log`. Use `--foreground` to run in the foreground.
-After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full). The sweep's log lives at `.git/wt/logs/wt-boj/internal/trash-sweep.log` (the `wt` pseudo-branch is sanitized via `sanitize_for_filename` like any other branch name).
## Hooks
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 887e36fe5..33bc38fa6 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -2,12 +2,22 @@
//!
//! Commands for getting, setting, and clearing stored state like default branch,
//! previous branch, CI status, markers, and logs.
+//!
+//! # Log layout invariant
+//!
+//! Inside `wt_logs_dir()`, top-level *files* are shared logs (`commands.jsonl*`,
+//! `verbose.log`, `diagnostic.md`) and top-level *directories* are per-branch log
+//! trees (`{branch}/{source|internal}/{hook-type}/{name}.log`). Categorization
+//! relies on this file-vs-directory distinction: new top-level shared entries
+//! must remain files. If a future category needs multiple files, it should live
+//! under a single reserved subdirectory rather than adding sibling top-level dirs.
use std::fmt::Write as _;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use anyhow::Context;
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};
@@ -37,30 +47,83 @@ pub fn require_user_config_path() -> anyhow::Result<PathBuf> {
// ==================== Log Management ====================
-/// Check if a file in `.git/wt/logs/` is a worktrunk log file.
+/// Check if a top-level file is a diagnostic file (`verbose.log` or `diagnostic.md`).
///
-/// Matches `.log` (hook output + verbose), `.jsonl`/`.jsonl.old` (command audit log),
-/// and known diagnostic files.
-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")
- || is_diagnostic_file(name)
+/// These are created by `-vv` and live directly under `wt_logs_dir()`.
+fn is_diagnostic_file(name: &str) -> bool {
+ name == "verbose.log" || name == "diagnostic.md"
}
-/// Check if a file is a diagnostic file (`verbose.log` or `diagnostic.md`).
+/// Check if a top-level file 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")
+}
+
+/// A hook-output log file discovered by walking the per-branch subtree.
+struct HookOutputEntry {
+ /// Path relative to `wt_logs_dir()`, used for display and JSON output.
+ /// Always forward-slashed for cross-platform stability.
+ relative_display: String,
+ metadata: std::fs::Metadata,
+}
+
+/// Walk every per-branch log file under `log_dir`.
///
-/// These are created by `-vv` and are separate from hook output and the command audit log.
-fn is_diagnostic_file(name: &str) -> bool {
- name == "verbose.log" || name == "diagnostic.md"
+/// Top-level *directories* are treated as branch dirs; each is walked
+/// recursively for `.log` files. Non-directory top-level entries are ignored
+/// (those belong to command audit / diagnostic categories).
+///
+/// Returns entries sorted by modification time (newest first), with name as a
+/// tie-breaker for stable ordering.
+fn walk_hook_output_files(log_dir: &Path) -> anyhow::Result<Vec<HookOutputEntry>> {
+ let mut out = Vec::new();
+ if !log_dir.exists() {
+ return Ok(out);
+ }
+ for entry in std::fs::read_dir(log_dir)? {
+ let entry = entry?;
+ if !entry.file_type()?.is_dir() {
+ continue;
+ }
+ walk_branch_dir(log_dir, &entry.path(), &mut out)?;
+ }
+ sort_hook_entries(&mut out);
+ Ok(out)
}
-/// Check if a file is a hook output log (branch-specific `.log` files, not diagnostic).
-fn is_hook_output_file(name: &str) -> bool {
- name.ends_with(".log") && !is_diagnostic_file(name)
+/// Recursively collect `.log` files under a branch directory.
+fn walk_branch_dir(
+ log_dir: &Path,
+ current: &Path,
+ out: &mut Vec<HookOutputEntry>,
+) -> anyhow::Result<()> {
+ for entry in std::fs::read_dir(current)? {
+ let entry = entry?;
+ let file_type = entry.file_type()?;
+ let path = entry.path();
+ if file_type.is_dir() {
+ walk_branch_dir(log_dir, &path, out)?;
+ } else if file_type.is_file() && path.extension().and_then(|e| e.to_str()) == Some("log") {
+ let metadata = entry.metadata()?;
+ let relative = path.strip_prefix(log_dir).unwrap_or(&path);
+ out.push(HookOutputEntry {
+ relative_display: relative.to_slash_lossy().into_owned(),
+ metadata,
+ });
+ }
+ }
+ Ok(())
+}
+
+/// Sort hook entries by mtime (newest first), then by relative path for stability.
+fn sort_hook_entries(entries: &mut [HookOutputEntry]) {
+ entries.sort_by(|a, b| {
+ let a_time = a.metadata.modified().ok();
+ let b_time = b.metadata.modified().ok();
+ b_time
+ .cmp(&a_time)
+ .then_with(|| a.relative_display.cmp(&b.relative_display))
+ });
}
/// Clear stale entries from the wt/trash directory.
@@ -95,7 +158,34 @@ fn clear_trash(repo: &Repository) -> anyhow::Result<usize> {
Ok(cleared)
}
-/// Clear all log files from the wt/logs directory
+/// Count `.log` files recursively under `dir`.
+///
+/// Used by `clear_logs` to report how many logs are being swept when it
+/// removes a whole branch subtree with `remove_dir_all`.
+fn count_log_files_recursive(dir: &Path) -> anyhow::Result<usize> {
+ let mut count = 0;
+ for entry in std::fs::read_dir(dir)? {
+ let entry = entry?;
+ let file_type = entry.file_type()?;
+ let path = entry.path();
+ if file_type.is_dir() {
+ count += count_log_files_recursive(&path)?;
+ } else if file_type.is_file() && path.extension().and_then(|e| e.to_str()) == Some("log") {
+ count += 1;
+ }
+ }
+ Ok(count)
+}
+
+/// Clear all log files from the wt/logs directory.
+///
+/// Walks the two layers of log storage:
+///
+/// 1. **Top-level files**: `commands.jsonl*`, `verbose.log`, `diagnostic.md`.
+/// Also sweeps any legacy flat `.log` files left over from the pre-nested
+/// layout so the transition is self-healing (no explicit migrator).
+/// 2. **Top-level directories**: per-branch log trees — counted recursively
+/// and removed with `remove_dir_all`.
fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
let log_dir = repo.wt_logs_dir();
@@ -107,9 +197,20 @@ 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() && is_wt_log_file(&path) {
- std::fs::remove_file(&path)?;
- cleared += 1;
+ let file_type = entry.file_type()?;
+ if file_type.is_dir() {
+ // Branch subtree — count logs within, then nuke the whole subtree.
+ cleared += count_log_files_recursive(&path)?;
+ std::fs::remove_dir_all(&path)?;
+ } else if file_type.is_file() {
+ let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
+ continue;
+ };
+ // Known shared files + legacy flat `.log` files from the old layout.
+ if is_command_log_file(name) || is_diagnostic_file(name) || name.ends_with(".log") {
+ std::fs::remove_file(&path)?;
+ cleared += 1;
+ }
}
}
@@ -121,32 +222,60 @@ fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
Ok(cleared)
}
-/// 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")
+/// A row ready to render in the log listing table or emit as JSON.
+struct LogRow {
+ display_name: String,
+ size: u64,
+ modified_at: Option<u64>,
+}
+
+impl LogRow {
+ fn to_json(&self) -> serde_json::Value {
+ serde_json::json!({
+ "file": self.display_name,
+ "size": self.size,
+ "modified_at": self.modified_at,
+ })
+ }
}
-/// Convert a log directory entry to a JSON object with file, size, and modified_at.
-fn log_entry_to_json(entry: &std::fs::DirEntry) -> serde_json::Value {
- let path = entry.path();
- let name = path
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .to_string();
+/// Build a `LogRow` for a top-level shared file.
+fn top_level_log_row(entry: &std::fs::DirEntry) -> LogRow {
+ let name = entry.file_name().to_string_lossy().into_owned();
let meta = entry.metadata().ok();
let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
- let modified = meta
+ let modified_at = meta
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
- serde_json::json!({ "file": name, "size": size, "modified_at": modified })
+ LogRow {
+ display_name: name,
+ size,
+ modified_at,
+ }
+}
+
+/// Build a `LogRow` for a hook-output file (display uses relative path).
+fn hook_output_log_row(entry: &HookOutputEntry) -> LogRow {
+ let size = entry.metadata.len();
+ let modified_at = entry
+ .metadata
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_secs());
+ LogRow {
+ display_name: entry.relative_display.clone(),
+ size,
+ modified_at,
+ }
}
/// Read and partition log files into command log, hook output, and diagnostic categories.
///
-/// Reads all wt log files from the repository's log directory, sorts by modification
-/// time (newest first), and partitions into three categories as JSON values.
+/// Top-level files are classified by name; directories under `log_dir` are
+/// walked as branch subtrees to collect hook output. All three categories are
+/// sorted by modification time (newest first) with a stable tie-breaker.
fn partition_log_files_json(
repo: &Repository,
) -> anyhow::Result<(
@@ -159,122 +288,133 @@ fn partition_log_files_json(
return Ok((vec![], vec![], vec![]));
}
- let mut 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();
-
- 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)
- .then_with(|| a.file_name().cmp(&b.file_name()))
- });
-
- let mut cmd_log = Vec::new();
- let mut hook_out = Vec::new();
- let mut diagnostic = Vec::new();
- for entry in &entries {
- let name = entry.file_name().to_string_lossy().to_string();
+ let mut cmd_rows = Vec::new();
+ let mut diagnostic_rows = Vec::new();
+ for entry in std::fs::read_dir(&log_dir)? {
+ let entry = entry?;
+ if !entry.file_type()?.is_file() {
+ continue;
+ }
+ let name = entry.file_name().to_string_lossy().into_owned();
if is_command_log_file(&name) {
- cmd_log.push(log_entry_to_json(entry));
+ cmd_rows.push(top_level_log_row(&entry));
} else if is_diagnostic_file(&name) {
- diagnostic.push(log_entry_to_json(entry));
- } else {
- hook_out.push(log_entry_to_json(entry));
+ diagnostic_rows.push(top_level_log_row(&entry));
}
}
- Ok((cmd_log, hook_out, diagnostic))
+ sort_log_rows(&mut cmd_rows);
+ sort_log_rows(&mut diagnostic_rows);
+
+ // Hook output comes from walking the branch subtrees.
+ let hook_rows: Vec<LogRow> = walk_hook_output_files(&log_dir)?
+ .iter()
+ .map(hook_output_log_row)
+ .collect();
+
+ Ok((
+ cmd_rows.iter().map(LogRow::to_json).collect(),
+ hook_rows.iter().map(LogRow::to_json).collect(),
+ diagnostic_rows.iter().map(LogRow::to_json).collect(),
+ ))
}
-/// 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() {
+/// Sort log rows by mtime (newest first), stable on display name.
+fn sort_log_rows(rows: &mut [LogRow]) {
+ rows.sort_by(|a, b| {
+ b.modified_at
+ .cmp(&a.modified_at)
+ .then_with(|| a.display_name.cmp(&b.display_name))
+ });
+}
+
+/// Render a table of log rows, or "(none)" if empty.
+fn render_log_table(out: &mut String, rows: &[LogRow]) -> std::fmt::Result {
+ if rows.is_empty() {
writeln!(out, "{}", format_with_gutter("(none)", None))?;
return Ok(());
}
- // Sort by modification time (newest first), then by name for stability
- 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)
- .then_with(|| a.file_name().cmp(&b.file_name()))
- });
-
- let rows: Vec<Vec<String>> = entries
+ let table_rows: Vec<Vec<String>> = rows
.iter()
- .map(|entry| {
- let path = entry.path();
- let name = path
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .to_string();
- let meta = entry.metadata().ok();
-
- let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
- let size_str = if size < 1024 {
- format!("{size}B")
+ .map(|row| {
+ let size_str = if row.size < 1024 {
+ format!("{}B", row.size)
} else {
- format!("{}K", size / 1024)
+ format!("{}K", row.size / 1024)
};
-
- let age = meta
- .and_then(|m| m.modified().ok())
- .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
- .map(|d| format_relative_time_short(d.as_secs() as i64))
+ let age = row
+ .modified_at
+ .map(|secs| format_relative_time_short(secs as i64))
.unwrap_or_else(|| "?".to_string());
-
- vec![name, size_str, age]
+ vec![row.display_name.clone(), size_str, age]
})
.collect();
- let rendered = crate::md_help::render_data_table(&["File", "Size", "Age"], &rows);
+ let rendered = crate::md_help::render_data_table(&["File", "Size", "Age"], &table_rows);
writeln!(out, "{}", rendered.trim_end())?;
Ok(())
}
-/// Render a single log section: heading, then filtered entries from the logs directory.
-fn render_log_section(
+/// Render a section heading and the `(none)` placeholder if the log dir is missing.
+fn render_log_heading(out: &mut String, log_dir: &Path, heading: &str) -> std::fmt::Result {
+ let log_dir_display = format_path_for_display(log_dir);
+ writeln!(
+ out,
+ "{}",
+ format_heading(heading, Some(&format!("@ {log_dir_display}")))
+ )
+}
+
+/// Render the command-log or diagnostic section: top-level files filtered by name.
+fn render_top_level_section(
out: &mut String,
repo: &Repository,
heading: &str,
filter: impl Fn(&str) -> bool,
) -> anyhow::Result<()> {
let log_dir = repo.wt_logs_dir();
- let log_dir_display = format_path_for_display(&log_dir);
-
- writeln!(
- out,
- "{}",
- format_heading(heading, Some(&format!("@ {log_dir_display}")))
- )?;
-
+ render_log_heading(out, &log_dir, heading)?;
if !log_dir.exists() {
writeln!(out, "{}", format_with_gutter("(none)", None))?;
return Ok(());
}
- let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
+ let mut rows: Vec<LogRow> = std::fs::read_dir(&log_dir)?
.filter_map(|e| e.ok())
- .filter(|e| e.path().is_file() && filter(&e.file_name().to_string_lossy()))
+ .filter(|e| e.file_type().map(|ft| ft.is_file()).unwrap_or(false))
+ .filter(|e| filter(&e.file_name().to_string_lossy()))
+ .map(|e| top_level_log_row(&e))
.collect();
+ sort_log_rows(&mut rows);
+ render_log_table(out, &rows)?;
+ Ok(())
+}
+
+/// Render the hook-output section: walk per-branch subtrees.
+fn render_hook_output_section(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
+ let log_dir = repo.wt_logs_dir();
+ render_log_heading(out, &log_dir, "HOOK OUTPUT")?;
+ if !log_dir.exists() {
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
+ return Ok(());
+ }
- render_log_table(out, &mut entries)?;
+ let rows: Vec<LogRow> = walk_hook_output_files(&log_dir)?
+ .iter()
+ .map(hook_output_log_row)
+ .collect();
+ render_log_table(out, &rows)?;
Ok(())
}
/// Render all three log sections (command log, hook output, diagnostic) into a buffer.
pub(super) fn render_all_log_sections(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
- render_log_section(out, repo, "COMMAND LOG", is_command_log_file)?;
+ render_top_level_section(out, repo, "COMMAND LOG", is_command_log_file)?;
writeln!(out)?;
- render_log_section(out, repo, "HOOK OUTPUT", is_hook_output_file)?;
+ render_hook_output_section(out, repo)?;
writeln!(out)?;
- render_log_section(out, repo, "DIAGNOSTIC", is_diagnostic_file)?;
+ render_top_level_section(out, repo, "DIAGNOSTIC", is_diagnostic_file)?;
Ok(())
}
@@ -339,23 +479,29 @@ pub fn handle_logs_get(
let log_path = hook_log.path(&log_dir, &branch);
if log_path.exists() {
- // Output just the path to stdout for easy piping
- println!("{}", log_path.display());
+ // Output just the path to stdout for easy piping.
+ // Use to_slash_lossy() so Windows paths use forward slashes, consistent
+ // with the relative paths in `logs list` output.
+ println!("{}", log_path.to_slash_lossy());
return Ok(());
}
- // No match found - show expected filename and available files
- let expected_filename = hook_log.filename(&branch);
- let safe_branch = sanitize_for_filename(&branch);
- let mut available = Vec::new();
- if let Ok(entries) = std::fs::read_dir(&log_dir) {
- for entry in entries.filter_map(|e| e.ok()) {
- let name = entry.file_name().to_string_lossy().to_string();
- if name.starts_with(&format!("{}-", safe_branch)) && name.ends_with(".log") {
- available.push(name);
- }
- }
- }
+ // 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()
+ };
if available.is_empty() {
anyhow::bail!(cformat!(
@@ -363,10 +509,10 @@ pub fn handle_logs_get(
branch
));
} else {
- let available_list = available.join(", ");
let details = format!(
"Expected: {}\nAvailable: {}",
- expected_filename, available_list
+ expected_relative,
+ available.join(", ")
);
return Err(anyhow::anyhow!(details).context(cformat!(
"No log file matches <bold>{}</> for branch <bold>{}</>",
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 28669ff13..81338a8e1 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -28,16 +28,20 @@ pub enum InternalOp {
/// Specification for a hook log file.
///
-/// This is the single source of truth for hook log file naming.
+/// 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`).
///
-/// # Log file naming
+/// # Log file layout
///
-/// Hook commands produce logs named: `{branch}-{source}-{hook_type}-{name}.log`
-/// - Example: `feature-user-post-start-server.log`
+/// Hook commands produce logs at: `{branch}/{source}/{hook-type}/{name}.log`
+/// - Example: `feature/user/post-start/server.log`
///
-/// Internal operations produce logs named: `{branch}-{op}.log`
-/// - Example: `feature-remove.log`
+/// Internal operations produce logs at: `{branch}/internal/{op}.log`
+/// - Example: `feature/internal/remove.log`
+///
+/// Branch and hook names are sanitized for filesystem safety via
+/// `sanitize_for_filename`, which replaces invalid characters and appends a
+/// short collision-avoidance hash.
///
/// # CLI format for lookup
///
@@ -47,13 +51,13 @@ pub enum InternalOp {
/// - `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`
+ /// Hook command log: `{branch}/{source}/{hook-type}/{name}.log`
Hook {
source: HookSource,
hook_type: HookType,
name: String,
},
- /// Internal operation log: `{branch}-{op}.log`
+ /// Internal operation log: `{branch}/internal/{op}.log`
Internal(InternalOp),
}
@@ -72,34 +76,25 @@ impl HookLog {
Self::Internal(op)
}
- /// Generate the suffix (without branch) for the log filename.
+ /// Generate the full log path for a branch in the given log directory.
///
- /// This is what gets appended after `{branch}-` in the log filename.
- pub fn suffix(&self) -> String {
+ /// Builds the nested path under `{log_dir}/{sanitized-branch}/...`.
+ /// Parent directories must be created by the caller (see `create_detach_log`).
+ pub fn path(&self, log_dir: &Path, branch: &str) -> PathBuf {
+ let branch_dir = log_dir.join(sanitize_for_filename(branch));
match self {
HookLog::Hook {
source,
hook_type,
name,
- } => {
- // HookSource uses #[strum(serialize_all = "kebab-case")] which produces lowercase
- format!("{}-{}-{}", source, hook_type, sanitize_for_filename(name))
- }
- HookLog::Internal(op) => op.to_string(),
+ } => branch_dir
+ .join(source.to_string())
+ .join(hook_type.to_string())
+ .join(format!("{}.log", sanitize_for_filename(name))),
+ HookLog::Internal(op) => branch_dir.join("internal").join(format!("{op}.log")),
}
}
- /// Generate full log filename for a branch.
- pub fn filename(&self, branch: &str) -> String {
- let safe_branch = sanitize_for_filename(branch);
- format!("{}-{}.log", safe_branch, self.suffix())
- }
-
- /// Generate full log path for a branch in the given log directory.
- pub fn path(&self, log_dir: &Path, branch: &str) -> PathBuf {
- log_dir.join(self.filename(branch))
- }
-
/// Convert to CLI spec format (for error messages and roundtrip).
///
/// Returns the format used by `parse()`: `source:hook-type:name` or `internal:op`.
@@ -182,24 +177,6 @@ fn posix_command_separator(command: &str) -> &'static str {
}
}
-/// Spawn a detached background process with output redirected to a log file
-///
-/// The process will be fully detached from the parent:
-/// - On Unix: uses process_group(0) to create a new process group (survives PTY closure)
-/// - On Windows: uses CREATE_NEW_PROCESS_GROUP to detach from console
-///
-/// Logs are centralized in the main worktree's `.git/wt/logs/` directory.
-///
-/// # Arguments
-/// * `repo` - Repository instance for accessing git common directory
-/// * `worktree_path` - Working directory for the command
-/// * `command` - Shell command to execute
-/// * `branch` - Branch name for log organization
-/// * `hook_log` - Log specification (determines the log filename)
-/// * `context_json` - Optional JSON context to pipe to command's stdin
-///
-/// # Returns
-/// Path to the log file where output is being written
/// Create the log directory and file for a detached process.
///
/// Returns `(log_path, log_file)`. Shared by `spawn_detached` and
@@ -210,14 +187,21 @@ fn create_detach_log(
hook_log: &HookLog,
) -> anyhow::Result<(PathBuf, fs::File)> {
let log_dir = repo.wt_logs_dir();
- fs::create_dir_all(&log_dir).with_context(|| {
+ let log_path = hook_log.path(&log_dir, branch);
+
+ // Create the full ancestor chain (e.g., {log_dir}/{branch}/{source}/{hook-type}/).
+ // log_path always has a parent here because HookLog::path() always appends at
+ // least one segment beyond log_dir.
+ let parent = log_path
+ .parent()
+ .expect("HookLog::path always includes a parent");
+ fs::create_dir_all(parent).with_context(|| {
format!(
"Failed to create log directory {}",
- format_path_for_display(&log_dir)
+ format_path_for_display(parent)
)
})?;
- let log_path = hook_log.path(&log_dir, branch);
let log_file = fs::File::create(&log_path).with_context(|| {
format!(
"Failed to create log file {}",
@@ -228,6 +212,13 @@ fn create_detach_log(
Ok((log_path, log_file))
}
+/// Spawn a detached background process with output redirected to a log file.
+///
+/// The process will be fully detached from the parent:
+/// - On Unix: uses `process_group(0)` to create a new process group (survives PTY closure)
+/// - On Windows: uses `CREATE_NEW_PROCESS_GROUP` to detach from console
+///
+/// Logs are centralized in the main worktree's `.git/wt/logs/` directory.
pub fn spawn_detached(
repo: &Repository,
worktree_path: &Path,
@@ -701,6 +692,7 @@ pub fn build_remove_command(
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
+ use path_slash::PathExt as _;
use super::*;
@@ -844,42 +836,57 @@ mod tests {
}
#[test]
- fn test_hook_log_suffix() {
+ fn test_hook_log_path() {
use worktrunk::git::HookType;
- // Suffix includes sanitized name with hash for collision avoidance
- // Constructor and parse produce identical suffixes
- assert_snapshot!(HookLog::hook(HookSource::User, HookType::PostStart, "server").suffix(), @"user-post-start-server-f4t");
- assert_snapshot!(HookLog::hook(HookSource::Project, HookType::PreStart, "build").suffix(), @"project-pre-start-build-seq");
- assert_snapshot!(HookLog::hook(HookSource::User, HookType::PreRemove, "cleanup").suffix(), @"user-pre-remove-cleanup-non");
- assert_snapshot!(HookLog::parse("user:post-start:server").unwrap().suffix(), @"user-post-start-server-f4t");
- assert_snapshot!(HookLog::parse("project:pre-start:build").unwrap().suffix(), @"project-pre-start-build-seq");
+ let log_dir = Path::new("/repo/.git/wt/logs");
- // Internal operation suffix
- assert_eq!(HookLog::internal(InternalOp::Remove).suffix(), "remove");
- assert_eq!(
- HookLog::internal(InternalOp::TrashSweep).suffix(),
- "trash-sweep"
+ // Hook path: {log_dir}/{sanitized-branch}/{source}/{hook-type}/{sanitized-name}.log
+ let log = HookLog::hook(HookSource::User, HookType::PostStart, "server");
+ assert_snapshot!(
+ log.path(log_dir, "main").to_slash_lossy(),
+ @"/repo/.git/wt/logs/main-vfz/user/post-start/server-f4t.log"
);
- }
- #[test]
- fn test_hook_log_filename() {
- use worktrunk::git::HookType;
+ // Slash in branch name gets sanitized (feature/auth → feature-auth-{hash})
+ assert_snapshot!(
+ log.path(log_dir, "feature/auth").to_slash_lossy(),
+ @"/repo/.git/wt/logs/feature-auth-j34/user/post-start/server-f4t.log"
+ );
- let log = HookLog::hook(HookSource::User, HookType::PostStart, "server");
- assert_snapshot!(log.filename("main"), @"main-vfz-user-post-start-server-f4t.log");
- // Slash in branch name gets sanitized
- assert_snapshot!(log.filename("feature/auth"), @"feature-auth-j34-user-post-start-server-f4t.log");
+ // Project source
+ let log = HookLog::hook(HookSource::Project, HookType::PreStart, "build");
+ assert_snapshot!(
+ log.path(log_dir, "main").to_slash_lossy(),
+ @"/repo/.git/wt/logs/main-vfz/project/pre-start/build-seq.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(),
+ @"/repo/.git/wt/logs/main-vfz/internal/remove.log"
+ );
- assert_snapshot!(HookLog::internal(InternalOp::Remove).filename("main"), @"main-vfz-remove.log");
+ // Non-branch-scoped internal ops (like TrashSweep) use a pseudo-branch
+ // at the top level — `wt remove` calls this with branch = "wt".
+ assert_snapshot!(
+ HookLog::internal(InternalOp::TrashSweep).path(log_dir, "wt").to_slash_lossy(),
+ @"/repo/.git/wt/logs/wt-boj/internal/trash-sweep.log"
+ );
}
#[test]
fn test_hook_log_parse_internal() {
let log = HookLog::parse("internal:remove").unwrap();
assert_eq!(log, HookLog::Internal(InternalOp::Remove));
- assert_eq!(log.suffix(), "remove");
}
#[test]
@@ -910,15 +917,17 @@ mod tests {
// 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.filename("main"), parsed.filename("main"));
+ 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.filename("main"), parsed.filename("main"));
+ assert_eq!(created.path(log_dir, "main"), parsed.path(log_dir, "main"));
}
#[test]
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index 355a08e4e..2a68f95af 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -2211,19 +2211,16 @@ pub fn wait_for_file(path: &Path) {
);
}
-/// Wait for a directory to contain at least `expected_count` files with a given extension.
+/// Wait for a directory tree to contain at least `expected_count` files with a given extension.
+///
+/// Walks recursively — used to count hook log files which live in nested
+/// `{branch}/{source}/{hook-type}/{name}.log` subtrees under `.git/wt/logs/`.
pub fn wait_for_file_count(dir: &Path, extension: &str, expected_count: usize) {
let start = std::time::Instant::now();
let mut attempt = 0;
while start.elapsed() < BG_TIMEOUT {
- if let Ok(entries) = std::fs::read_dir(dir) {
- let count = entries
- .filter_map(|e| e.ok())
- .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some(extension))
- .count();
- if count >= expected_count {
- return;
- }
+ if count_files_recursive(dir, extension) >= expected_count {
+ return;
}
exponential_sleep(attempt);
attempt += 1;
@@ -2234,6 +2231,25 @@ pub fn wait_for_file_count(dir: &Path, extension: &str, expected_count: usize) {
);
}
+fn count_files_recursive(dir: &Path, extension: &str) -> usize {
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return 0;
+ };
+ let mut count = 0;
+ for entry in entries.filter_map(|e| e.ok()) {
+ let Ok(file_type) = entry.file_type() else {
+ continue;
+ };
+ let path = entry.path();
+ if file_type.is_dir() {
+ count += count_files_recursive(&path, extension);
+ } else if path.extension().and_then(|s| s.to_str()) == Some(extension) {
+ count += 1;
+ }
+ }
+ count
+}
+
/// Wait for a file to have non-empty content, polling with exponential backoff.
/// Use when a background process creates a file but may not have finished writing.
pub fn wait_for_file_content(path: &Path) {
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
index dbc7e1844..db1f8bb20 100644
--- a/tests/integration_tests/bare_repository.rs
+++ b/tests/integration_tests/bare_repository.rs
@@ -1,7 +1,7 @@
use crate::common::{
BareRepoTest, TestRepo, TestRepoBase, canonicalize, configure_directive_file,
configure_git_cmd, configure_git_env, directive_file, repo, setup_temp_snapshot_settings,
- wait_for, wait_for_file_content, wait_for_file_count, wt_command,
+ wait_for, wait_for_file, wait_for_file_content, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -703,26 +703,19 @@ fn test_bare_repo_background_logs_location() {
}
// Wait for background process to create log file (poll instead of fixed sleep)
- // The key test is that the path is correct, not that content was written (background processes are flaky in tests)
- // Log filename has hash suffix: feature-<hash>-remove-<hash>.log
+ // The key test is that the path is correct, not that content was written
+ // (background processes are flaky in tests). Logs live at:
+ // `{bare_repo}/wt/logs/{sanitized-branch}/internal/remove.log`
let log_dir = test.bare_repo_path().join("wt/logs");
- wait_for_file_count(&log_dir, "log", 1);
-
- // Verify the log file matches expected pattern (feature-*-remove.log)
- // Format: {branch_with_hash}-{op}.log (internal ops don't have hash on suffix)
- let log_files: Vec<_> = std::fs::read_dir(&log_dir)
- .unwrap()
- .filter_map(|e| e.ok())
- .filter(|e| {
- let name = e.file_name().to_string_lossy().to_string();
- name.starts_with("feature-") && name.ends_with("-remove.log")
- })
- .collect();
- assert_eq!(
- log_files.len(),
- 1,
- "Expected exactly one feature-*-remove.log file, found: {:?}",
- log_files
+ let remove_log = log_dir
+ .join(worktrunk::path::sanitize_for_filename("feature"))
+ .join("internal")
+ .join("remove.log");
+ wait_for_file(&remove_log);
+ assert!(
+ remove_log.exists(),
+ "Expected remove log at {}",
+ remove_log.display()
);
// Verify it's NOT in the worktree's .git directory (which doesn't exist for linked worktrees)
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index be784a2c4..e3bfe2f18 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -1,24 +1,44 @@
use crate::common::{TEST_EPOCH, TestRepo, repo, wt_command};
use insta::assert_snapshot;
use rstest::rstest;
+use std::path::{Path, PathBuf};
use std::process::Command;
use worktrunk::path::sanitize_for_filename;
-/// Generate a hook log filename matching the format from `commands::process::HookLog`.
+/// Relative path of a hook log file under the wt logs directory.
///
-/// Format: `{branch}-{source}-{hook_type}-{name}.log` where branch and name are sanitized.
-fn hook_log_filename(branch: &str, source: &str, hook_type: &str, name: &str) -> String {
+/// Layout: `{branch}/{source}/{hook_type}/{name}.log` — branch and name are
+/// sanitized to match `commands::process::HookLog::path`.
+fn hook_log_rel_path(branch: &str, source: &str, hook_type: &str, name: &str) -> PathBuf {
let safe_branch = sanitize_for_filename(branch);
let safe_name = sanitize_for_filename(name);
- format!("{safe_branch}-{source}-{hook_type}-{safe_name}.log")
+ PathBuf::from(safe_branch)
+ .join(source)
+ .join(hook_type)
+ .join(format!("{safe_name}.log"))
}
-/// Generate an internal operation log filename.
+/// Relative path of an internal-operation log file under the wt logs directory.
///
-/// Format: `{branch}-{op}.log` where branch is sanitized.
-fn internal_log_filename(branch: &str, op: &str) -> String {
+/// Layout: `{branch}/internal/{op}.log` — branch is sanitized.
+fn internal_log_rel_path(branch: &str, op: &str) -> PathBuf {
let safe_branch = sanitize_for_filename(branch);
- format!("{safe_branch}-{op}.log")
+ PathBuf::from(safe_branch)
+ .join("internal")
+ .join(format!("{op}.log"))
+}
+
+/// Write a log file at `log_dir / relative`, creating parent directories.
+fn write_log_at(log_dir: &Path, relative: &Path, contents: &str) {
+ let full = log_dir.join(relative);
+ std::fs::create_dir_all(full.parent().unwrap()).unwrap();
+ std::fs::write(&full, contents).unwrap();
+}
+
+/// Display string for a relative log path, forward-slashed for stable snapshots.
+fn rel_display(p: &Path) -> String {
+ use path_slash::PathExt as _;
+ p.to_slash_lossy().into_owned()
}
/// Settings for `wt config state get` snapshots (normalizes log paths)
@@ -532,12 +552,18 @@ fn test_state_get_logs_with_files(repo: TestRepo) {
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"),
+ write_log_at(
+ &log_dir,
+ &hook_log_rel_path("feature", "user", "post-start", "npm"),
"npm output here",
- )
- .unwrap();
- std::fs::write(log_dir.join("bugfix-remove.log"), "remove output").unwrap();
+ );
+ // >= 1024 bytes to exercise the `{}K` size-formatting branch in
+ // render_log_table (the other test files stay under 1KB to exercise `{}B`).
+ write_log_at(
+ &log_dir,
+ &internal_log_rel_path("bugfix", "remove"),
+ &"remove output\n".repeat(80),
+ );
std::fs::write(log_dir.join("commands.jsonl"), r#"{"ts":"2026-01-01"}"#).unwrap();
let output = wt_state_cmd(&repo, "logs", "get", &[]).output().unwrap();
@@ -553,10 +579,10 @@ fn test_state_get_logs_with_files(repo: TestRepo) {
commands.jsonl <SIZE> <AGE>
HOOK OUTPUT @ <PATH>
- File Size Age
- ────────────────────────── ──── ──────
- bugfix-remove.log <SIZE> <AGE>
- feature-post-start-npm.log <SIZE> <AGE>
+ File Size Age
+ ─────────────────────────────────────── ──── ──────
+ bugfix-zgc/internal/remove.log <SIZE> <AGE>
+ feature-axb/user/post-start/npm-iox.log <SIZE> <AGE>
DIAGNOSTIC @ <PATH>
  (none)
@@ -598,7 +624,8 @@ fn test_state_get_logs_diagnostic_files(repo: TestRepo) {
std::fs::write(log_dir.join("verbose.log"), "debug output").unwrap();
std::fs::write(log_dir.join("diagnostic.md"), "# Diagnostic Report").unwrap();
// Also add a hook output file to verify separation
- std::fs::write(log_dir.join("feature-remove.log"), "remove output").unwrap();
+ let remove_rel = internal_log_rel_path("feature", "remove");
+ write_log_at(&log_dir, &remove_rel, "remove output");
let output = wt_state_cmd(&repo, "logs", "get", &[]).output().unwrap();
assert!(output.status.success());
@@ -623,9 +650,10 @@ fn test_state_get_logs_diagnostic_files(repo: TestRepo) {
.rsplit("HOOK OUTPUT")
.next()
.unwrap();
+ let remove_display = rel_display(&remove_rel);
assert!(
- hook_section.contains("feature-remove.log"),
- "Expected feature-remove.log in HOOK OUTPUT: {hook_section}"
+ hook_section.contains(&remove_display),
+ "Expected {remove_display} in HOOK OUTPUT: {hook_section}"
);
assert!(
!hook_section.contains("verbose.log"),
@@ -664,8 +692,16 @@ fn test_state_clear_logs_with_files(repo: TestRepo) {
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();
+ write_log_at(
+ &log_dir,
+ &hook_log_rel_path("feature", "user", "post-start", "npm"),
+ "npm output",
+ );
+ write_log_at(
+ &log_dir,
+ &internal_log_rel_path("bugfix", "remove"),
+ "remove output",
+ );
std::fs::write(log_dir.join("commands.jsonl"), "jsonl data").unwrap();
let output = wt_state_cmd(&repo, "logs", "clear", &[]).output().unwrap();
@@ -676,13 +712,34 @@ fn test_state_clear_logs_with_files(repo: TestRepo) {
assert!(!log_dir.exists());
}
+#[rstest]
+fn test_state_clear_logs_sweeps_legacy_flat_files(repo: TestRepo) {
+ // Pre-nested layout left orphan `.log` files directly under wt/logs/.
+ // `clear_logs` self-heals by sweeping them along with everything else.
+ 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"), "old layout").unwrap();
+ std::fs::write(log_dir.join("bugfix-remove.log"), "old layout").unwrap();
+
+ let output = wt_state_cmd(&repo, "logs", "clear", &[]).output().unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("Cleared") && stderr.contains("2") && stderr.contains("log file"));
+ assert!(!log_dir.exists(), "log dir should be removed after sweep");
+}
+
#[rstest]
fn test_state_clear_logs_single_file(repo: TestRepo) {
// Create wt/logs directory with one 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();
- std::fs::write(log_dir.join("feature-remove.log"), "remove output").unwrap();
+ write_log_at(
+ &log_dir,
+ &internal_log_rel_path("feature", "remove"),
+ "remove output",
+ );
let output = wt_state_cmd(&repo, "logs", "clear", &[]).output().unwrap();
assert!(output.status.success());
@@ -738,7 +795,11 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {
let git_dir = repo.root_path().join(".git");
let log_dir = git_dir.join("wt/logs");
std::fs::create_dir_all(&log_dir).unwrap();
- std::fs::write(log_dir.join("feature-remove.log"), "output").unwrap();
+ write_log_at(
+ &log_dir,
+ &internal_log_rel_path("feature", "remove"),
+ "output",
+ );
let output = wt_state_clear_all_cmd(&repo).output().unwrap();
assert!(output.status.success());
@@ -946,8 +1007,16 @@ fn test_state_get_comprehensive(repo: TestRepo) {
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();
+ write_log_at(
+ &log_dir,
+ &hook_log_rel_path("feature", "user", "post-start", "npm"),
+ "npm output",
+ );
+ write_log_at(
+ &log_dir,
+ &internal_log_rel_path("bugfix", "remove"),
+ "remove output",
+ );
let output = wt_state_get_cmd(&repo).output().unwrap();
assert!(output.status.success());
@@ -1050,8 +1119,16 @@ fn test_state_get_json_with_logs(repo: TestRepo) {
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();
+ write_log_at(
+ &log_dir,
+ &hook_log_rel_path("feature", "user", "post-start", "npm"),
+ "npm output",
+ );
+ write_log_at(
+ &log_dir,
+ &internal_log_rel_path("bugfix", "remove"),
+ "remove log output",
+ );
std::fs::write(log_dir.join("commands.jsonl"), r#"{"ts":"2026-01-01"}"#).unwrap();
let output = wt_state_get_json_cmd(&repo).output().unwrap();
@@ -1087,12 +1164,12 @@ fn test_state_get_json_with_logs(repo: TestRepo) {
"hints": [],
"hook_output": [
{
- "file": "bugfix-remove.log",
+ "file": "bugfix-zgc/internal/remove.log",
"modified_at": "<MTIME>",
"size": "<SIZE>"
},
{
- "file": "feature-post-start-npm.log",
+ "file": "feature-axb/user/post-start/npm-iox.log",
"modified_at": "<MTIME>",
"size": "<SIZE>"
}
@@ -1373,9 +1450,8 @@ fn test_state_logs_get_hook_returns_path(repo: TestRepo) {
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 filename = hook_log_filename("main", "user", "post-start", "server");
- let log_file = log_dir.join(&filename);
- std::fs::write(&log_file, "server output here").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"])
@@ -1384,10 +1460,10 @@ fn test_state_logs_get_hook_returns_path(repo: TestRepo) {
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(&filename),
- "Expected log path in stdout: {}",
- stdout
+ stdout.contains(&expected),
+ "Expected {expected} in stdout: {stdout}",
);
}
@@ -1397,9 +1473,8 @@ fn test_state_logs_get_hook_project_source(repo: TestRepo) {
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 filename = hook_log_filename("main", "project", "post-start", "build");
- let log_file = log_dir.join(&filename);
- std::fs::write(&log_file, "build output here").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"])
@@ -1407,10 +1482,10 @@ fn test_state_logs_get_hook_project_source(repo: TestRepo) {
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
+ let expected = rel_display(&relative);
assert!(
- stdout.contains(&filename),
- "Expected log path in stdout: {}",
- stdout
+ stdout.contains(&expected),
+ "Expected {expected} in stdout: {stdout}",
);
}
@@ -1420,19 +1495,18 @@ fn test_state_logs_get_hook_internal_op(repo: TestRepo) {
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 filename = internal_log_filename("main", "remove");
- let log_file = log_dir.join(&filename);
- std::fs::write(&log_file, "remove output").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(&filename),
- "Expected log path in stdout: {}",
- stdout
+ stdout.contains(&expected),
+ "Expected {expected} in stdout: {stdout}",
);
}
@@ -1442,19 +1516,18 @@ fn test_state_logs_get_hook_not_found(repo: TestRepo) {
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 other_filename = hook_log_filename("main", "user", "post-start", "other");
- std::fs::write(log_dir.join(&other_filename), "other output").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), @"
- ✗ No log file matches user:post-start:server for branch main
-   Expected: main-vfz-user-post-start-server-f4t.log
-   Available: main-vfz-user-post-start-other-4n1.log
- ");
+ assert_snapshot!(String::from_utf8_lossy(&output.stderr));
}
#[rstest]
@@ -1474,8 +1547,11 @@ fn test_state_logs_get_hook_no_logs_for_branch(repo: TestRepo) {
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 other_branch_filename = hook_log_filename("other-branch", "user", "post-start", "server");
- std::fs::write(log_dir.join(&other_branch_filename), "other output").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"])
@@ -1496,8 +1572,8 @@ fn test_state_logs_get_hook_with_branch_flag(repo: TestRepo) {
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 filename = hook_log_filename("feature", "user", "post-start", "dev");
- std::fs::write(log_dir.join(&filename), "dev output").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(
@@ -1510,10 +1586,10 @@ fn test_state_logs_get_hook_with_branch_flag(repo: TestRepo) {
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
+ let expected = rel_display(&relative);
assert!(
- stdout.contains(&filename),
- "Expected log path in stdout: {}",
- stdout
+ stdout.contains(&expected),
+ "Expected {expected} in stdout: {stdout}",
);
}
@@ -1964,17 +2040,24 @@ fn test_logs_get_json_with_files(repo: TestRepo) {
let log_dir = repo.root_path().join(".git/wt/logs");
std::fs::create_dir_all(&log_dir).unwrap();
std::fs::write(log_dir.join("commands.jsonl"), "{}").unwrap();
- std::fs::write(log_dir.join("main-user-post-start-server.log"), "output").unwrap();
+ std::fs::write(log_dir.join("diagnostic.md"), "# report").unwrap();
+ write_log_at(
+ &log_dir,
+ &hook_log_rel_path("main", "user", "post-start", "server"),
+ "output",
+ );
let output = wt_state_cmd(&repo, "logs", "get", &["--format=json"])
.output()
.unwrap();
assert!(output.status.success());
- // Redact dynamic timestamps and sizes
+ // Redact dynamic timestamps, sizes, and sanitize hashes (hashes vary per input).
let mut settings = insta::Settings::clone_current();
settings.add_filter(r#""modified_at": \d+"#, r#""modified_at": "<TIMESTAMP>""#);
settings.add_filter(r#""size": \d+"#, r#""size": "<SIZE>""#);
+ settings.add_filter(r"main-[a-z0-9]{3}", "main-<HASH>");
+ settings.add_filter(r"server-[a-z0-9]{3}", "server-<HASH>");
settings.bind(|| {
assert_snapshot!(String::from_utf8_lossy(&output.stdout));
});
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 22f73ce0c..8dda05273 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -900,15 +900,19 @@ approved-commands = ["echo 'stdout output' && echo 'stderr output' >&2"]
// 2 log files: runner log + per-command log (cmd-0, unnamed single command)
wait_for_file_count(&log_dir, "log", 2);
- // Find the command log file (contains "cmd-0" in name, not "runner")
- let cmd_log = fs::read_dir(&log_dir)
- .unwrap()
+ // Find the command log file at `{branch}/project/post-start/cmd-0-*.log`.
+ let post_start_dir = log_dir
+ .join(worktrunk::path::sanitize_for_filename("feature"))
+ .join("project")
+ .join("post-start");
+ let cmd_log = fs::read_dir(&post_start_dir)
+ .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
.filter_map(|e| e.ok())
.map(|e| e.path())
.find(|p| {
p.file_name()
.and_then(|n| n.to_str())
- .is_some_and(|n| n.contains("cmd-0"))
+ .is_some_and(|n| n.starts_with("cmd-0"))
})
.expect("Should have a cmd-0 log file");
@@ -985,21 +989,25 @@ approved-commands = [
let log_dir = git_common_dir.join("wt/logs");
wait_for_file_count(&log_dir, "log", 4);
- // Verify each task's output is in its own log file.
+ // Verify each task's output is in its own log file. Hook logs live at
+ // `{branch}/project/post-start/{task}.log` in the nested layout.
+ let post_start_dir = log_dir
+ .join(worktrunk::path::sanitize_for_filename("feature"))
+ .join("project")
+ .join("post-start");
+ let log_files: Vec<_> = fs::read_dir(&post_start_dir)
+ .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
+ .filter_map(|e| e.ok())
+ .collect();
for (task, expected) in [
("task1", "TASK1_OUTPUT"),
("task2", "TASK2_OUTPUT"),
("task3", "TASK3_OUTPUT"),
] {
- let log_file = fs::read_dir(&log_dir)
- .unwrap()
- .filter_map(|e| e.ok())
- .find(|e| {
- e.file_name()
- .to_string_lossy()
- .contains(&format!("post-start-{task}"))
- })
- .unwrap_or_else(|| panic!("should have log file for {task}"));
+ let log_file = log_files
+ .iter()
+ .find(|e| e.file_name().to_string_lossy().starts_with(task))
+ .unwrap_or_else(|| panic!("should have log file for {task} in {post_start_dir:?}"));
wait_for_file_content(&log_file.path());
let contents = fs::read_to_string(log_file.path()).unwrap();
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index dd7ba013f..983d6f6a6 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -1546,9 +1546,13 @@ fn test_concurrent_hook_single_failure(repo: TestRepo) {
let log_dir = resolve_git_common_dir(repo.root_path()).join("wt/logs");
wait_for_file_count(&log_dir, "log", 2);
- // Find the command log file (contains "cmd-0" in name)
- let cmd_log = fs::read_dir(&log_dir)
- .unwrap()
+ // Hook logs live at `{branch}/project/post-start/{name}.log`.
+ let post_start_dir = log_dir
+ .join(worktrunk::path::sanitize_for_filename("main"))
+ .join("project")
+ .join("post-start");
+ let cmd_log = fs::read_dir(&post_start_dir)
+ .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
.filter_map(|e| e.ok())
.find(|e| e.file_name().to_string_lossy().contains("cmd-0"))
.expect("Should have a cmd-0 log file");
@@ -1592,16 +1596,21 @@ second = "echo SECOND_OUTPUT"
let log_dir = resolve_git_common_dir(repo.root_path()).join("wt/logs");
wait_for_file_count(&log_dir, "log", 3);
+ // Hook logs live at `{branch}/project/post-start/{name}.log`.
+ let post_start_dir = log_dir
+ .join(worktrunk::path::sanitize_for_filename("main"))
+ .join("project")
+ .join("post-start");
+ let log_files: Vec<_> = fs::read_dir(&post_start_dir)
+ .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
+ .filter_map(|e| e.ok())
+ .collect();
+
// Verify each command's output is in its own log file
for (task, expected) in [("first", "FIRST_OUTPUT"), ("second", "SECOND_OUTPUT")] {
- let log_file = fs::read_dir(&log_dir)
- .unwrap()
- .filter_map(|e| e.ok())
- .find(|e| {
- e.file_name()
- .to_string_lossy()
- .contains(&format!("post-start-{task}"))
- })
+ let log_file = log_files
+ .iter()
+ .find(|e| e.file_name().to_string_lossy().starts_with(task))
.unwrap_or_else(|| panic!("should have log file for {task}"));
wait_for_file_content(&log_file.path());
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 cd04f675a..843685c65 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
@@ -10,10 +10,16 @@ expression: "String::from_utf8_lossy(&output.stdout)"
"size": "<SIZE>"
}
],
- "diagnostic": [],
+ "diagnostic": [
+ {
+ "file": "diagnostic.md",
+ "modified_at": "<TIMESTAMP>",
+ "size": "<SIZE>"
+ }
+ ],
"hook_output": [
{
- "file": "main-user-post-start-server.log",
+ "file": "main-<HASH>/user/post-start/server-<HASH>.log",
"modified_at": "<TIMESTAMP>",
"size": "<SIZE>"
}
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 ac1f64ffe..a508a8d08 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
@@ -32,10 +32,10 @@ expression: "String::from_utf8_lossy(&output.stderr)"
  (none)
HOOK OUTPUT @ <PATH>
- File Size Age
- ────────────────────────── ──── ──────
- bugfix-remove.log 13B future
- feature-post-start-npm.log 10B future
+ File Size Age
+ ─────────────────────────────────────── ──── ──────
+ bugfix-zgc/internal/remove.log 13B future
+ feature-axb/user/post-start/npm-iox.log 10B future
DIAGNOSTIC @ <PATH>
  (none)
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
new file mode 100644
index 000000000..8ce9a2da1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__config_state__state_logs_get_hook_not_found.snap
@@ -0,0 +1,7 @@
+---
+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-vfz/user/post-start/server-f4t.log
+  Available: main-vfz/user/post-start/other-4n1.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 ffe610f14..ec6354b32 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
@@ -79,12 +79,14 @@ The command log appends entries and is not branch-specific — it records all ac
Hook output logs
- Operation Log file
- ────────────────── ──────────────────────────────────────────────────────
- Background hooks {branch}-{hash}-{source}-{hook-type}-{name}-{hash}.log
- Background removal {branch}-{hash}-remove.log
+Hook output lives in per-branch subtrees under .git/wt/logs/{branch}/:
-All post-* hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is user or project. Hash suffixes are added by filename sanitization. Same operation on same branch overwrites the previous log. Logs from deleted branches remain until manually cleared.
+ Operation Log path
+ ────────────────── ────────────────────────────────────────
+ Background hooks {branch}/{source}/{hook-type}/{name}.log
+ Background removal {branch}/internal/remove.log
+
+All post-* hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is user or project. Branch and hook names are sanitized for filesystem safety (invalid characters → -; short collision-avoidance hash appended). Same operation on same branch overwrites the previous log. Removing a branch clears its subtree; orphans from deleted branches can be swept with wt config state logs clear.
Diagnostic files
@@ -97,7 +99,7 @@ All post-* hooks (post-start, post-switch, post-commit, post-merge) run
Location
-All logs are stored in .git/wt/logs/ (in the main worktree's git directory). All worktrees write to the same directory.
+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.
Examples
@@ -108,7 +110,7 @@ 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-a1b-project-post-start-build-seq.log"
+  cat "$(git rev-parse --git-dir)/wt/logs/feature/project/post-start/build.log"
Clear all logs:
  wt config state logs clear
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
index b345d8f4e..500f7202f 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
@@ -141,9 +141,9 @@ Without --force, removal fails if the worktree contains untracked files.
Background removal
-Removal runs in the background by default — the command returns immediately. The worktree is renamed into .git/wt/trash/ (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached rm -rf finishes cleanup. Cross-filesystem worktrees fall back to git worktree remove. Logs: .git/wt/logs/{branch}-remove.log. Use --foreground to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into .git/wt/trash/ (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached rm -rf finishes cleanup. Cross-filesystem worktrees fall back to git worktree remove. Logs: .git/wt/logs/{branch}/internal/remove.log. Use --foreground to run in the foreground.
-After each wt remove, entries in .git/wt/trash/ older than 24 hours are swept by a detached rm -rf — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
+After each wt remove, entries in .git/wt/trash/ older than 24 hours are swept by a detached rm -rf — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full). The sweep's log lives at .git/wt/logs/wt-boj/internal/trash-sweep.log (the wt pseudo-branch is sanitized via sanitize_for_filename like any other branch name).
Hooks