Skip to content

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

fix(logs): report real branch names in hook-output JSON; fix tips recipes wt rejects (#4279)

Worktrunk Bot17b100ef35d9
diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.md
index 76ff93532..c9d350243 100644
--- a/docs/src/content/docs/config.md
+++ b/docs/src/content/docs/config.md
@@ -1182,7 +1182,7 @@ All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). A
### Structured output
-`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.
+`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. `branch` is the branch name, or `null` when no local branch writes to that log directory (e.g. the branch was deleted). `name` is the hook name as it appears in the log path, which differs from the configured name only when that contains characters unsafe in a filename. Filter with `jq` to pick out a specific entry.
### Examples
@@ -1198,12 +1198,12 @@ $ tail -5 .git/wt/logs/commands.jsonl | jq .
Path to one hook log (e.g. the `post-start` `server` hook for the current branch):
```console
-$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+$ wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path'
```
Logs for a specific branch:
```console
-$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch == "feature/auth")'
```
Clear all logs:
diff --git a/docs/src/content/docs/extending.md b/docs/src/content/docs/extending.md
index dd3f417d7..c80036f30 100644
--- a/docs/src/content/docs/extending.md
+++ b/docs/src/content/docs/extending.md
@@ -187,15 +187,15 @@ To copy instead of move, add `git stash apply --index --quiet` right after the p
# ~/.config/worktrunk/config.toml
[aliases]
hook-log = '''
-tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name | sanitize_hash }}" --arg kind "{{ kind }}" '
+tail -f "$(wt config state logs --format=json | jq -r --arg branch {{ branch }} --arg name {{ name | sanitize_hash }} --arg kind {{ kind }} '
.hook_output[]
- | select(.branch == "{{ branch | sanitize_hash }}" and .hook_type == $kind and .name == $name)
+ | select([.branch, .hook_type, .name] == [$branch, $kind, $name])
| .path
' | head -1)"
'''
```
-Run with `wt hook-log --kind=post-start --name=server` to tail the log for the `server` hook on the current branch. `--kind` picks the hook type; the branch is pulled from the current worktree via `{{ branch }}`. `sanitize_hash` rewrites `branch` and `name` to filesystem-safe forms with a hash suffix that keeps distinct originals unique (the same transformation Worktrunk applies on disk), so the alias resolves the right log even when either contains characters like `/`.
+Run with `wt hook-log --kind=post-start --name=server` to tail the log for the `server` hook on the current branch. `--kind` picks the hook type; the branch is pulled from the current worktree via `{{ branch }}`. `branch` in the JSON is the branch name itself, while `name` is the hook name as it appears on disk; `sanitize_hash` applies the same transformation to `{{ name }}`, so the alias resolves the right log even when the hook name contains characters like `/`.
## Custom subcommands
diff --git a/docs/src/content/docs/tips-patterns.md b/docs/src/content/docs/tips-patterns.md
index a70c007a5..099c7b4f0 100644
--- a/docs/src/content/docs/tips-patterns.md
+++ b/docs/src/content/docs/tips-patterns.md
@@ -237,10 +237,9 @@ Each worktree can have its own isolated database. A pipeline sets up names and p
# .config/wt.toml
[[post-start]]
set-vars = """
-wt config state vars set \
- container='{{ repo }}-{{ branch | sanitize }}-postgres' \
- port='{{ ('db-' ~ branch) | hash_port }}' \
- db_url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
+wt config state vars set container='{{ repo }}-{{ branch | sanitize }}-postgres' &&
+wt config state vars set port='{{ ('db-' ~ branch) | hash_port }}' &&
+wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
"""
[[post-start]]
@@ -264,7 +263,7 @@ The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so
The connection string is accessible anywhere — not just in hooks:
```bash
-DATABASE_URL=$(wt config state vars get db_url) npm start
+DATABASE_URL=$(wt config state vars get db-url) npm start
```
### Per-worktree env vars
@@ -530,13 +529,15 @@ Then `wt mc` opens an editor for the commit message while plain `wt merge` conti
Follow background hook output:
```bash
-tail -f "$(wt config state logs get --hook=user:post-start:server)"
+tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path')"
```
-The `--hook` format is `source:hook-type:name` — e.g., `project:post-start:build` for project-defined hooks. Use `wt config state logs get` to list all available logs.
+Each `hook_output` entry carries `branch`, `source` (`user`, `project`, or `internal`), `hook_type`, `name`, and `path` — adjust the `select` to pick a different hook or branch. Run `wt config state logs` to list all available logs.
-Create an alias for frequent use:
+Create a shell function for frequent use (`wtlog server`):
```bash
-alias wtlog='f() { tail -f "$(wt config state logs get --hook="$1")"; }; f'
+wtlog() {
+ tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" --arg name "$1" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", $name]) | .path')"
+}
```
diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.md
index 7879d22fa..573934cb8 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/config.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md
@@ -1174,7 +1174,7 @@ All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). A
### Structured output
-`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.
+`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. `branch` is the branch name, or `null` when no local branch writes to that log directory (e.g. the branch was deleted). `name` is the hook name as it appears in the log path, which differs from the configured name only when that contains characters unsafe in a filename. Filter with `jq` to pick out a specific entry.
### Examples
@@ -1190,12 +1190,12 @@ $ tail -5 .git/wt/logs/commands.jsonl | jq .
Path to one hook log (e.g. the `post-start` `server` hook for the current branch):
```console
-$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+$ wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path'
```
Logs for a specific branch:
```console
-$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch == "feature/auth")'
```
Clear all logs:
diff --git a/plugins/worktrunk/skills/worktrunk/reference/extending.md b/plugins/worktrunk/skills/worktrunk/reference/extending.md
index 7d5a44eeb..be5abb5d4 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/extending.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/extending.md
@@ -183,15 +183,15 @@ To copy instead of move, add `git stash apply --index --quiet` right after the p
# ~/.config/worktrunk/config.toml
[aliases]
hook-log = '''
-tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name | sanitize_hash }}" --arg kind "{{ kind }}" '
+tail -f "$(wt config state logs --format=json | jq -r --arg branch {{ branch }} --arg name {{ name | sanitize_hash }} --arg kind {{ kind }} '
.hook_output[]
- | select(.branch == "{{ branch | sanitize_hash }}" and .hook_type == $kind and .name == $name)
+ | select([.branch, .hook_type, .name] == [$branch, $kind, $name])
| .path
' | head -1)"
'''
```
-Run with `wt hook-log --kind=post-start --name=server` to tail the log for the `server` hook on the current branch. `--kind` picks the hook type; the branch is pulled from the current worktree via `{{ branch }}`. `sanitize_hash` rewrites `branch` and `name` to filesystem-safe forms with a hash suffix that keeps distinct originals unique (the same transformation Worktrunk applies on disk), so the alias resolves the right log even when either contains characters like `/`.
+Run with `wt hook-log --kind=post-start --name=server` to tail the log for the `server` hook on the current branch. `--kind` picks the hook type; the branch is pulled from the current worktree via `{{ branch }}`. `branch` in the JSON is the branch name itself, while `name` is the hook name as it appears on disk; `sanitize_hash` applies the same transformation to `{{ name }}`, so the alias resolves the right log even when the hook name contains characters like `/`.
## Custom subcommands
diff --git a/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
index 6e9a8d2b1..261d41c90 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
@@ -229,10 +229,9 @@ Each worktree can have its own isolated database. A pipeline sets up names and p
# .config/wt.toml
[[post-start]]
set-vars = """
-wt config state vars set \
- container='{{ repo }}-{{ branch | sanitize }}-postgres' \
- port='{{ ('db-' ~ branch) | hash_port }}' \
- db_url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
+wt config state vars set container='{{ repo }}-{{ branch | sanitize }}-postgres' &&
+wt config state vars set port='{{ ('db-' ~ branch) | hash_port }}' &&
+wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
"""
[[post-start]]
@@ -256,7 +255,7 @@ The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so
The connection string is accessible anywhere — not just in hooks:
```bash
-DATABASE_URL=$(wt config state vars get db_url) npm start
+DATABASE_URL=$(wt config state vars get db-url) npm start
```
### Per-worktree env vars
@@ -522,13 +521,15 @@ Then `wt mc` opens an editor for the commit message while plain `wt merge` conti
Follow background hook output:
```bash
-tail -f "$(wt config state logs get --hook=user:post-start:server)"
+tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path')"
```
-The `--hook` format is `source:hook-type:name` — e.g., `project:post-start:build` for project-defined hooks. Use `wt config state logs get` to list all available logs.
+Each `hook_output` entry carries `branch`, `source` (`user`, `project`, or `internal`), `hook_type`, `name`, and `path` — adjust the `select` to pick a different hook or branch. Run `wt config state logs` to list all available logs.
-Create an alias for frequent use:
+Create a shell function for frequent use (`wtlog server`):
```bash
-alias wtlog='f() { tail -f "$(wt config state logs get --hook="$1")"; }; f'
+wtlog() {
+ tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" --arg name "$1" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", $name]) | .path')"
+}
```
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 7879d22fa..573934cb8 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -1174,7 +1174,7 @@ All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). A
### Structured output
-`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.
+`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. `branch` is the branch name, or `null` when no local branch writes to that log directory (e.g. the branch was deleted). `name` is the hook name as it appears in the log path, which differs from the configured name only when that contains characters unsafe in a filename. Filter with `jq` to pick out a specific entry.
### Examples
@@ -1190,12 +1190,12 @@ $ tail -5 .git/wt/logs/commands.jsonl | jq .
Path to one hook log (e.g. the `post-start` `server` hook for the current branch):
```console
-$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+$ wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path'
```
Logs for a specific branch:
```console
-$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch == "feature/auth")'
```
Clear all logs:
diff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.md
index 7d5a44eeb..be5abb5d4 100644
--- a/skills/worktrunk/reference/extending.md
+++ b/skills/worktrunk/reference/extending.md
@@ -183,15 +183,15 @@ To copy instead of move, add `git stash apply --index --quiet` right after the p
# ~/.config/worktrunk/config.toml
[aliases]
hook-log = '''
-tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name | sanitize_hash }}" --arg kind "{{ kind }}" '
+tail -f "$(wt config state logs --format=json | jq -r --arg branch {{ branch }} --arg name {{ name | sanitize_hash }} --arg kind {{ kind }} '
.hook_output[]
- | select(.branch == "{{ branch | sanitize_hash }}" and .hook_type == $kind and .name == $name)
+ | select([.branch, .hook_type, .name] == [$branch, $kind, $name])
| .path
' | head -1)"
'''
```
-Run with `wt hook-log --kind=post-start --name=server` to tail the log for the `server` hook on the current branch. `--kind` picks the hook type; the branch is pulled from the current worktree via `{{ branch }}`. `sanitize_hash` rewrites `branch` and `name` to filesystem-safe forms with a hash suffix that keeps distinct originals unique (the same transformation Worktrunk applies on disk), so the alias resolves the right log even when either contains characters like `/`.
+Run with `wt hook-log --kind=post-start --name=server` to tail the log for the `server` hook on the current branch. `--kind` picks the hook type; the branch is pulled from the current worktree via `{{ branch }}`. `branch` in the JSON is the branch name itself, while `name` is the hook name as it appears on disk; `sanitize_hash` applies the same transformation to `{{ name }}`, so the alias resolves the right log even when the hook name contains characters like `/`.
## Custom subcommands
diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.md
index 6e9a8d2b1..261d41c90 100644
--- a/skills/worktrunk/reference/tips-patterns.md
+++ b/skills/worktrunk/reference/tips-patterns.md
@@ -229,10 +229,9 @@ Each worktree can have its own isolated database. A pipeline sets up names and p
# .config/wt.toml
[[post-start]]
set-vars = """
-wt config state vars set \
- container='{{ repo }}-{{ branch | sanitize }}-postgres' \
- port='{{ ('db-' ~ branch) | hash_port }}' \
- db_url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
+wt config state vars set container='{{ repo }}-{{ branch | sanitize }}-postgres' &&
+wt config state vars set port='{{ ('db-' ~ branch) | hash_port }}' &&
+wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
"""
[[post-start]]
@@ -256,7 +255,7 @@ The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so
The connection string is accessible anywhere — not just in hooks:
```bash
-DATABASE_URL=$(wt config state vars get db_url) npm start
+DATABASE_URL=$(wt config state vars get db-url) npm start
```
### Per-worktree env vars
@@ -522,13 +521,15 @@ Then `wt mc` opens an editor for the commit message while plain `wt merge` conti
Follow background hook output:
```bash
-tail -f "$(wt config state logs get --hook=user:post-start:server)"
+tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path')"
```
-The `--hook` format is `source:hook-type:name` — e.g., `project:post-start:build` for project-defined hooks. Use `wt config state logs get` to list all available logs.
+Each `hook_output` entry carries `branch`, `source` (`user`, `project`, or `internal`), `hook_type`, `name`, and `path` — adjust the `select` to pick a different hook or branch. Run `wt config state logs` to list all available logs.
-Create an alias for frequent use:
+Create a shell function for frequent use (`wtlog server`):
```bash
-alias wtlog='f() { tail -f "$(wt config state logs get --hook="$1")"; }; f'
+wtlog() {
+ tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" --arg name "$1" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", $name]) | .path')"
+}
```
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 864a7e183..d6e4947bf 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -1092,7 +1092,7 @@ All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). A
## Structured output
-`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.
+`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. `branch` is the branch name, or `null` when no local branch writes to that log directory (e.g. the branch was deleted). `name` is the hook name as it appears in the log path, which differs from the configured name only when that contains characters unsafe in a filename. Filter with `jq` to pick out a specific entry.
## Examples
@@ -1108,12 +1108,12 @@ $ tail -5 .git/wt/logs/commands.jsonl | jq .
Path to one hook log (e.g. the `post-start` `server` hook for the current branch):
```console
-$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+$ wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path'
```
Logs for a specific branch:
```console
-$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch == "feature/auth")'
```
Clear all logs:
@@ -1489,14 +1489,14 @@ List all log files:
$ wt config state logs
```
-Get the absolute path of one post-start hook log for the current branch (use `jq` to filter):
+Get the absolute path of the current branch's `server` post-start hook log:
```console
-$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+$ wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path'
```
Stream that log with `tail -f`:
```console
-$ tail -f "$(wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path' | head -1)"
+$ tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path')"
```
Logs for a background worktree removal (internal op):
@@ -1506,7 +1506,7 @@ $ wt config state logs --format=json | jq '.hook_output[] | select(.source == "i
Logs for a specific branch:
```console
-$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch == "feature/auth")'
```"#
)]
Get,
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 8cd876f1b..91746b427 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -69,6 +69,7 @@
//! 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::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
@@ -77,7 +78,7 @@ use anyhow::Context;
use color_print::cformat;
use path_slash::PathExt as _;
use worktrunk::git::{BranchRef, CommandError, Repository, resolve_input_path, sha_cache};
-use worktrunk::path::format_path_for_display;
+use worktrunk::path::{format_path_for_display, sanitize_for_filename};
use worktrunk::styling::{
eprintln, format_heading, format_with_gutter, hint_message, info_message, println,
success_message, warning_message,
@@ -360,11 +361,12 @@ struct LogRow {
/// Structured view of a hook-output log path. Values are the on-disk (sanitized)
/// names, so filters like `select(.source == "user")` work without splitting
-/// the relative path on `/`.
+/// the relative path on `/`. The JSON `branch` field is the exception: it maps
+/// `branch_dir` back to the branch name (see [`branch_by_log_dir`]).
struct HookStructure {
/// First path segment — sanitized branch directory (may include a short
/// collision-avoidance hash).
- branch: String,
+ branch_dir: String,
/// `"user"`, `"project"`, or `"internal"`.
source: String,
/// Hook type (`post-start`, `post-switch`, …) for user/project hooks;
@@ -377,15 +379,22 @@ struct HookStructure {
impl LogRow {
fn to_json(&self) -> serde_json::Value {
- let mut obj = serde_json::json!({
+ serde_json::json!({
"file": self.display_name,
"path": self.path,
"size": self.size,
"modified_at": self.modified_at,
- });
+ })
+ }
+
+ /// JSON for a hook-output row: the base fields plus the structured
+ /// segments, with `branch` resolved through `branch_by_dir`.
+ fn to_hook_json(&self, branch_by_dir: &HashMap<String, Option<String>>) -> serde_json::Value {
+ let mut obj = self.to_json();
if let Some(s) = &self.hook_structure {
let map = obj.as_object_mut().expect("json! produced an object");
- map.insert("branch".into(), s.branch.clone().into());
+ let branch = branch_by_dir.get(&s.branch_dir).cloned().flatten();
+ map.insert("branch".into(), branch.into());
map.insert("source".into(), s.source.clone().into());
map.insert(
"hook_type".into(),
@@ -451,14 +460,14 @@ fn hook_output_log_row(log_dir: &Path, entry: &HookOutputEntry) -> LogRow {
fn parse_hook_structure(relative: &str) -> Option<HookStructure> {
let parts: Vec<&str> = relative.split('/').collect();
match parts.as_slice() {
- [branch, "internal", op_log] => Some(HookStructure {
- branch: (*branch).to_string(),
+ [branch_dir, "internal", op_log] => Some(HookStructure {
+ branch_dir: (*branch_dir).to_string(),
source: "internal".to_string(),
hook_type: None,
name: op_log.strip_suffix(".log").unwrap_or(op_log).to_string(),
}),
- [branch, source, hook_type, name_log] => Some(HookStructure {
- branch: (*branch).to_string(),
+ [branch_dir, source, hook_type, name_log] => Some(HookStructure {
+ branch_dir: (*branch_dir).to_string(),
source: (*source).to_string(),
hook_type: Some((*hook_type).to_string()),
name: name_log
@@ -509,14 +518,36 @@ fn partition_log_files_json(
.iter()
.map(|e| hook_output_log_row(&log_dir, e))
.collect();
+ let branch_by_dir = branch_by_log_dir(repo)?;
Ok((
cmd_rows.iter().map(LogRow::to_json).collect(),
- hook_rows.iter().map(LogRow::to_json).collect(),
+ hook_rows
+ .iter()
+ .map(|r| r.to_hook_json(&branch_by_dir))
+ .collect(),
diagnostic_rows.iter().map(LogRow::to_json).collect(),
))
}
+/// Map each hook-log branch directory back to the local branch that writes it.
+///
+/// A branch's logs live under `sanitize_for_filename(branch)`, which appends a
+/// one-way hash to names that aren't filename-safe (`feature/x` →
+/// `feature-x-<hash>`), so the directory alone can't recover the name.
+/// Sanitizing every local branch inverts it for the branches that still exist.
+/// A directory two branches share maps to `None`, as does (by absence) one
+/// whose branch was deleted, so `branch` in JSON is either exact or `null`.
+fn branch_by_log_dir(repo: &Repository) -> anyhow::Result<HashMap<String, Option<String>>> {
+ let mut map = HashMap::new();
+ for branch in repo.local_branches()? {
+ map.entry(sanitize_for_filename(&branch.name))
+ .and_modify(|b| *b = None)
+ .or_insert_with(|| Some(branch.name.clone()));
+ }
+ Ok(map)
+}
+
/// Sort log rows by mtime (newest first), stable on display name.
fn sort_log_rows(rows: &mut [LogRow]) {
rows.sort_by(|a, b| {
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 72a51f240..d19482ac4 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -2178,7 +2178,9 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {
#[rstest]
fn test_state_get_json_with_logs(repo: TestRepo) {
- // Create hook output and command log files
+ // Create hook output and command log files. `feature` exists, so its log
+ // reports the branch; `bugfix` stands for a deleted branch (`branch: null`).
+ repo.run_git(&["branch", "feature"]);
let git_dir = repo.root_path().join(".git");
let log_dir = git_dir.join("wt/logs");
std::fs::create_dir_all(&log_dir).unwrap();
@@ -2229,7 +2231,7 @@ fn test_state_get_json_with_logs(repo: TestRepo) {
"hints": [],
"hook_output": [
{
- "branch": "bugfix",
+ "branch": null,
"file": "bugfix/internal/remove.log",
"hook_type": null,
"modified_at": "<MTIME>",
@@ -3024,6 +3026,7 @@ fn test_logs_get_json_with_files(repo: TestRepo) {
/// work the same as for user/project hooks.
#[rstest]
fn test_logs_get_json_internal_op_structure(repo: TestRepo) {
+ repo.run_git(&["branch", "feature"]);
let log_dir = repo.root_path().join(".git/wt/logs");
std::fs::create_dir_all(&log_dir).unwrap();
write_log_at(
@@ -3043,7 +3046,54 @@ fn test_logs_get_json_internal_op_structure(repo: TestRepo) {
assert_eq!(hook["source"], "internal");
assert_eq!(hook["hook_type"], serde_json::Value::Null);
assert_eq!(hook["name"], "remove");
- assert!(hook["branch"].as_str().unwrap().starts_with("feature"));
+ assert_eq!(hook["branch"], "feature");
+}
+
+/// `branch` is the real branch name, not the sanitized log directory, so
+/// `select(.branch == "feature/x")` matches exactly. A directory no local
+/// branch maps to — a deleted branch, or one two branches share — is `null`.
+#[rstest]
+fn test_logs_get_json_branch_is_unsanitized(repo: TestRepo) {
+ let feature_dir = sanitize_for_filename("feature/x");
+ let shared_dir = sanitize_for_filename("shared/x");
+ for branch in ["feature/x", "shared/x", shared_dir.as_str()] {
+ repo.run_git(&["branch", branch]);
+ }
+ let log_dir = repo.root_path().join(".git/wt/logs");
+ for branch in ["main", "feature/x", "shared/x", "gone/x"] {
+ write_log_at(
+ &log_dir,
+ &hook_log_rel_path(branch, "user", "post-start", "server"),
+ "output",
+ );
+ }
+
+ let output = wt_state_cmd(&repo, "logs", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let mut branches: Vec<(String, serde_json::Value)> = parsed["hook_output"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|h| {
+ let dir = h["file"].as_str().unwrap().split('/').next().unwrap();
+ (dir.to_string(), h["branch"].clone())
+ })
+ .collect();
+ branches.sort_by(|a, b| a.0.cmp(&b.0));
+ let gone_dir = sanitize_for_filename("gone/x");
+ let mut expected = vec![
+ (feature_dir, serde_json::json!("feature/x")),
+ (gone_dir, serde_json::Value::Null),
+ ("main".to_string(), serde_json::json!("main")),
+ (shared_dir, serde_json::Value::Null),
+ ];
+ expected.sort_by(|a, b| a.0.cmp(&b.0));
+ assert_eq!(branches, expected);
}
/// Repo-wide internal logs are top-level shared files, not branch subtrees.
diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rs
index 3e020d8c6..9fe0f227f 100644
--- a/tests/integration_tests/doc_templates.rs
+++ b/tests/integration_tests/doc_templates.rs
@@ -396,18 +396,16 @@ fn test_doc_hash_port_repo_branch_concatenation(repo: TestRepo) {
fn test_doc_example_database_vars(repo: TestRepo) {
// From docs/src/content/docs/tips-patterns.md, "Database per worktree" —
// the `set-vars` step that derives the container name and port:
- // wt config state vars set \
- // container='{{ repo }}-{{ branch | sanitize }}-postgres' \
- // port='{{ ('db-' ~ branch) | hash_port }}'
+ // wt config state vars set container='{{ repo }}-{{ branch | sanitize }}-postgres' &&
+ // wt config state vars set port='{{ ('db-' ~ branch) | hash_port }}'
let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
vars.insert("repo", "myproject");
vars.insert("branch", "feature-auth");
- let template = r#"wt config state vars set \
- container='{{ repo }}-{{ branch | sanitize }}-postgres' \
- port='{{ ('db-' ~ branch) | hash_port }}'"#;
+ let template = r#"wt config state vars set container='{{ repo }}-{{ branch | sanitize }}-postgres' &&
+wt config state vars set port='{{ ('db-' ~ branch) | hash_port }}'"#;
let result = expand_template(
template,
@@ -432,11 +430,69 @@ fn test_doc_example_database_vars(repo: TestRepo) {
);
}
+/// Runs the "Database per worktree" `set-vars` step exactly as the docs write
+/// it (read from the page, not copied here), through a `wt` alias so templates
+/// expand as in a hook. The expansion test above can't catch a command `wt`
+/// rejects — the recipe once passed three pairs to one `vars set`, which takes
+/// a single `KEY=VALUE`.
+#[cfg(unix)]
+#[rstest]
+fn test_doc_example_database_set_vars_step_runs(repo: TestRepo) {
+ let doc = std::fs::read_to_string(
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("docs/src/content/docs/tips-patterns.md"),
+ )
+ .unwrap();
+ let section = doc.split_once("### Database per worktree").unwrap().1;
+ let block = section
+ .split_once("```toml\n")
+ .unwrap()
+ .1
+ .split_once("```")
+ .unwrap()
+ .0;
+ let config: toml::Table = toml::from_str(block).unwrap();
+ let set_vars = config["post-start"][0]["set-vars"].as_str().unwrap();
+
+ let mut aliases = toml::Table::new();
+ aliases.insert("set-vars".into(), set_vars.into());
+ let mut user_config = toml::Table::new();
+ user_config.insert("aliases".into(), aliases.into());
+ repo.write_test_config(&toml::to_string(&user_config).unwrap());
+
+ let path = format!(
+ "{}:{}",
+ crate::common::wt_bin().parent().unwrap().display(),
+ std::env::var("PATH").unwrap_or_default()
+ );
+ let output = repo
+ .wt_command()
+ .args(["step", "set-vars"])
+ .env("PATH", path)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "set-vars step from the docs failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let port = repo
+ .wt_command()
+ .args(["config", "state", "vars", "get", "port"])
+ .output()
+ .unwrap();
+ assert_eq!(
+ String::from_utf8_lossy(&port.stdout).trim(),
+ hash_port("db-main").to_string()
+ );
+}
+
#[rstest]
fn test_doc_example_database_url(repo: TestRepo) {
// From docs/src/content/docs/tips-patterns.md, "Database per worktree" —
- // the `db_url` var the `set-vars` step stores:
- // db_url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
+ // the `db-url` var the `set-vars` step stores:
+ // db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
let repository = Repository::at(repo.root_path()).unwrap();
let mut vars = HashMap::new();
@@ -459,7 +515,7 @@ fn test_doc_example_database_url(repo: TestRepo) {
result.starts_with(&format!(
"postgres://postgres:dev@localhost:{expected_port}/feature_"
)),
- "db_url should carry the 'db-feature' port and the sanitized database name, got: {result}"
+ "db-url should carry the 'db-feature' port and the sanitized database name, got: {result}"
);
}
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 5d5cc2a78..b84699c57 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
@@ -126,7 +126,8 @@ All logs are stored in .git/wt/logs/ (in the main worktree's git directo
Structured output
-wt config state logs --format=json emits three arrays — command_log, hook_output, diagnostic. Each entry carries a file (relative), path (absolute), size, and modified_at (unix seconds). Hook-output entries additionally expose branch, source (user / project / internal), hook_type (the post-* kind, or null for internal ops), and name. Filter with jq to pick out a specific entry.
+wt config state logs --format=json emits three arrays — command_log, hook_output, diagnostic. Each entry carries a file (relative), path (absolute), size, and modified_at (unix seconds). Hook-output entries additionally expose branch, source (user / project / internal), hook_type (the post-* kind, or null for internal ops), and name. branch is the branch name, or null when no local branch writes to that log directory (e.g. the branch was deleted). name is the hook name as it appears in the log
+path, which differs from the configured name only when that contains characters unsafe in a filename. Filter with jq to pick out a specific entry.
Examples
@@ -137,10 +138,10 @@ Query the command log:
  tail -5 .git/wt/logs/commands.jsonl | jq .
Path to one hook log (e.g. the post-start server hook for the current branch):
-  wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'
+  wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path'
Logs for a specific branch:
-  wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'
+  wt config state logs --format=json | jq '.hook_output[] | select(.branch == "feature/auth")'
Clear all logs:
  wt config state logs clear