Skip to content

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

feat(config): add codename template filter (#2641)

Jesseecdb7bfc351a
diff --git a/Cargo.lock b/Cargo.lock
index 3b94b7c8e..c6c2b3dc4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1601,6 +1601,27 @@ dependencies = [
"sha2 0.10.9",
]
+[[package]]
+name = "petname"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ce610bff48dd7b6a127e45631795fbb0b302b99a39bef7e6da3d297e8eb2b6b"
+dependencies = [
+ "petname-macros",
+ "rand 0.10.1",
+]
+
+[[package]]
+name = "petname-macros"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "324239bd00dcf61f1a0e301d4d8f6f8c080a755248fc3fdc817ee1fdbbc27b8b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "pin-project-lite"
version = "0.2.16"
@@ -1743,7 +1764,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
dependencies = [
"rand_chacha",
- "rand_core",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
+dependencies = [
+ "rand_core 0.10.1",
]
[[package]]
@@ -1753,7 +1783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
- "rand_core",
+ "rand_core 0.9.5",
]
[[package]]
@@ -1765,6 +1795,12 @@ dependencies = [
"getrandom 0.3.4",
]
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
[[package]]
name = "rayon"
version = "1.12.0"
@@ -2219,7 +2255,7 @@ dependencies = [
"indexmap",
"log",
"nix 0.29.0",
- "rand",
+ "rand 0.9.4",
"rayon",
"regex",
"shell-quote",
@@ -3170,6 +3206,7 @@ dependencies = [
"osc8",
"path-slash",
"pathdiff",
+ "petname",
"portable-pty",
"rayon",
"reflink-copy",
diff --git a/Cargo.toml b/Cargo.toml
index c0a35084f..d2b8d978d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -139,6 +139,13 @@ schemars = { version = "1.2.1", features = ["derive"] }
# `.git/wt/cache/summary/`). stdlib's `DefaultHasher` is not guaranteed
# stable across Rust versions, so we need a deterministic algorithm on disk.
sha2 = "0.11"
+# Wordlists for the `codename` template filter. PINNED EXACT — bumping this
+# can silently shift every existing user's codename-derived worktree path,
+# orphaning their on-disk worktrees. Coordinate any version change as a
+# breaking-change rollout (see `test_codename_outputs_are_stable` and
+# `src/config/expansion.rs::codename`). We use only the static wordlists,
+# not the random-name generator, so `default-rng` and `clap` stay off.
+petname = { version = "=3.0.0", default-features = false, features = ["default-words"] }
tempfile = "3.27"
wait-timeout = "0.2"
diff --git a/dev/config.example.toml b/dev/config.example.toml
index 2072c7969..13c298838 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -19,6 +19,7 @@
# - `{{ branch }}` — raw branch name (e.g., `feature/auth`)
# - `{{ branch | sanitize }}` — filesystem-safe: `/` and `\` become `-` (e.g., `feature-auth`)
# - `{{ branch | sanitize_db }}` — database-safe: lowercase, underscores, hash suffix (e.g., `feature_auth_x7k`)
+# - `{{ branch | codename(2) }}` — deterministic friendly name from a ~1.26M-combo pool (e.g., `malleable-opah`)
#
# **Examples** for repo at `~/code/myproject`, branch `feature/auth`:
#
@@ -30,6 +31,14 @@
#
# worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"
#
+# Friendly branch-derived names (`~/code/myproject.malleable-opah`):
+#
+# worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+#
+# Friendly names with branch identity in a parent directory (`~/code/worktrees/feature-auth/malleable-opah`):
+#
+# worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+#
# Centralized worktrees directory (`~/worktrees/myproject/feature-auth`):
#
# worktree-path = "~/worktrees/{{ repo }}/{{ branch | sanitize }}"
diff --git a/docs/content/config.md b/docs/content/config.md
index 353869042..c725b5f63 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -81,6 +81,7 @@ Controls where new worktrees are created.
- `{{ branch }}` — raw branch name (e.g., `feature/auth`)
- `{{ branch | sanitize }}` — filesystem-safe: `/` and `\` become `-` (e.g., `feature-auth`)
- `{{ branch | sanitize_db }}` — database-safe: lowercase, underscores, hash suffix (e.g., `feature_auth_x7k`)
+- `{{ branch | codename(2) }}` — deterministic friendly name from a ~1.26M-combo pool (e.g., `malleable-opah`)
**Examples** for repo at `~/code/myproject`, branch `feature/auth`:
@@ -96,6 +97,18 @@ Inside the repository (`~/code/myproject/.worktrees/feature-auth`):
worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"
```
+Friendly branch-derived names (`~/code/myproject.malleable-opah`):
+
+```toml
+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+```
+
+Friendly names with branch identity in a parent directory (`~/code/worktrees/feature-auth/malleable-opah`):
+
+```toml
+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+```
+
Centralized worktrees directory (`~/worktrees/myproject/feature-auth`):
```toml
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 6b89abeec..6f9a66f03 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -188,8 +188,22 @@ Templates support Jinja2 filters for transforming values:
| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |
| `dirname` | `{{ repo_path \| dirname }}` | Strip the last path component (`/a/b/c` → `/a/b`) |
| `basename` | `{{ repo_path \| basename }}` | Keep only the last path component (`/a/b/c` → `c`) |
+| `codename(n)` | `{{ branch \| codename(2) }}` | Deterministic friendly words |
-The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers — lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words. The `sanitize_hash` filter produces a filesystem-safe name and appends a 3-character hash suffix when sanitization changed the input, so distinct originals never collide — already-safe names pass through unchanged. The `hash` filter is the bare 3-character base36 digest, useful for composing your own truncate-with-collision-avoidance recipes when an output budget is tight (e.g., Unix socket paths capped at 107 bytes):
+The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers — lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words. The `sanitize_hash` filter produces a filesystem-safe name and appends a 3-character hash suffix when sanitization changed the input, so distinct originals never collide — already-safe names pass through unchanged. The `codename(n)` filter produces deterministic friendly names from an input string: `codename(1)` returns a noun, `codename(2)` returns `adjective-noun`, and higher counts add more adjectives. The pool is large (~1.26M combinations for `codename(2)`), so it usually stands alone as a worktree leaf:
+
+```toml
+# Friendly branch-derived worktree names, e.g. myproject.malleable-opah
+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+```
+
+When you want both a friendly name and the original branch identity in the path, put the branch name in a parent directory:
+
+```toml
+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+```
+
+The `hash` filter is the bare 3-character base36 digest, useful for composing your own truncate-with-collision-avoidance recipes when an output budget is tight (e.g., Unix socket paths capped at 107 bytes):
```toml
# Truncated branch slug + hash: collisions remain disambiguated even when prefixes match
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 1b42b446c..93ae2676f 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -80,6 +80,7 @@ Controls where new worktrees are created.
- `{{ branch }}` — raw branch name (e.g., `feature/auth`)
- `{{ branch | sanitize }}` — filesystem-safe: `/` and `\` become `-` (e.g., `feature-auth`)
- `{{ branch | sanitize_db }}` — database-safe: lowercase, underscores, hash suffix (e.g., `feature_auth_x7k`)
+- `{{ branch | codename(2) }}` — deterministic friendly name from a ~1.26M-combo pool (e.g., `malleable-opah`)
**Examples** for repo at `~/code/myproject`, branch `feature/auth`:
@@ -95,6 +96,18 @@ Inside the repository (`~/code/myproject/.worktrees/feature-auth`):
worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"
```
+Friendly branch-derived names (`~/code/myproject.malleable-opah`):
+
+```toml
+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+```
+
+Friendly names with branch identity in a parent directory (`~/code/worktrees/feature-auth/malleable-opah`):
+
+```toml
+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+```
+
Centralized worktrees directory (`~/worktrees/myproject/feature-auth`):
```toml
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index cff9e2b12..38fc0885e 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -179,8 +179,22 @@ Templates support Jinja2 filters for transforming values:
| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |
| `dirname` | `{{ repo_path \| dirname }}` | Strip the last path component (`/a/b/c` → `/a/b`) |
| `basename` | `{{ repo_path \| basename }}` | Keep only the last path component (`/a/b/c` → `c`) |
+| `codename(n)` | `{{ branch \| codename(2) }}` | Deterministic friendly words |
-The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers — lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words. The `sanitize_hash` filter produces a filesystem-safe name and appends a 3-character hash suffix when sanitization changed the input, so distinct originals never collide — already-safe names pass through unchanged. The `hash` filter is the bare 3-character base36 digest, useful for composing your own truncate-with-collision-avoidance recipes when an output budget is tight (e.g., Unix socket paths capped at 107 bytes):
+The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers — lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words. The `sanitize_hash` filter produces a filesystem-safe name and appends a 3-character hash suffix when sanitization changed the input, so distinct originals never collide — already-safe names pass through unchanged. The `codename(n)` filter produces deterministic friendly names from an input string: `codename(1)` returns a noun, `codename(2)` returns `adjective-noun`, and higher counts add more adjectives. The pool is large (~1.26M combinations for `codename(2)`), so it usually stands alone as a worktree leaf:
+
+```toml
+# Friendly branch-derived worktree names, e.g. myproject.malleable-opah
+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+```
+
+When you want both a friendly name and the original branch identity in the path, put the branch name in a parent directory:
+
+```toml
+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+```
+
+The `hash` filter is the bare 3-character base36 digest, useful for composing your own truncate-with-collision-avoidance recipes when an output budget is tight (e.g., Unix socket paths capped at 107 bytes):
```toml
# Truncated branch slug + hash: collisions remain disambiguated even when prefixes match
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 330466ae8..ad8de4b61 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1373,8 +1373,22 @@ Templates support Jinja2 filters for transforming values:
| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |
| `dirname` | `{{ repo_path \| dirname }}` | Strip the last path component (`/a/b/c` → `/a/b`) |
| `basename` | `{{ repo_path \| basename }}` | Keep only the last path component (`/a/b/c` → `c`) |
+| `codename(n)` | `{{ branch \| codename(2) }}` | Deterministic friendly words |
-The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers — lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words. The `sanitize_hash` filter produces a filesystem-safe name and appends a 3-character hash suffix when sanitization changed the input, so distinct originals never collide — already-safe names pass through unchanged. The `hash` filter is the bare 3-character base36 digest, useful for composing your own truncate-with-collision-avoidance recipes when an output budget is tight (e.g., Unix socket paths capped at 107 bytes):
+The `sanitize` filter makes branch names safe for filesystem paths. The `sanitize_db` filter produces database-safe identifiers — lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words. The `sanitize_hash` filter produces a filesystem-safe name and appends a 3-character hash suffix when sanitization changed the input, so distinct originals never collide — already-safe names pass through unchanged. The `codename(n)` filter produces deterministic friendly names from an input string: `codename(1)` returns a noun, `codename(2)` returns `adjective-noun`, and higher counts add more adjectives. The pool is large (~1.26M combinations for `codename(2)`), so it usually stands alone as a worktree leaf:
+
+```toml
+# Friendly branch-derived worktree names, e.g. myproject.malleable-opah
+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+```
+
+When you want both a friendly name and the original branch identity in the path, put the branch name in a parent directory:
+
+```toml
+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+```
+
+The `hash` filter is the bare 3-character base36 digest, useful for composing your own truncate-with-collision-avoidance recipes when an output budget is tight (e.g., Unix socket paths capped at 107 bytes):
```toml
# Truncated branch slug + hash: collisions remain disambiguated even when prefixes match
@@ -1599,6 +1613,7 @@ Controls where new worktrees are created.
- `{{ branch }}` — raw branch name (e.g., `feature/auth`)
- `{{ branch | sanitize }}` — filesystem-safe: `/` and `\` become `-` (e.g., `feature-auth`)
- `{{ branch | sanitize_db }}` — database-safe: lowercase, underscores, hash suffix (e.g., `feature_auth_x7k`)
+- `{{ branch | codename(2) }}` — deterministic friendly name from a ~1.26M-combo pool (e.g., `malleable-opah`)
**Examples** for repo at `~/code/myproject`, branch `feature/auth`:
@@ -1614,6 +1629,18 @@ Inside the repository (`~/code/myproject/.worktrees/feature-auth`):
worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"
```
+Friendly branch-derived names (`~/code/myproject.malleable-opah`):
+
+```toml
+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+```
+
+Friendly names with branch identity in a parent directory (`~/code/worktrees/feature-auth/malleable-opah`):
+
+```toml
+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+```
+
Centralized worktrees directory (`~/worktrees/myproject/feature-auth`):
```toml
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 71488420e..98287f054 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -19,6 +19,7 @@ use color_print::cformat;
use minijinja::value::{Enumerator, Object, ObjectRepr};
use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
use regex::Regex;
+use sha2::{Digest, Sha256};
use shell_escape::escape;
use crate::git::{Diagnostic, HookType, Repository};
@@ -356,6 +357,23 @@ fn string_to_port(s: &str) -> u16 {
10000 + (h.finish() % 10000) as u16
}
+const CODENAME_MAX_WORDS: usize = 8;
+
+/// Wordlists used by [`codename`].
+///
+/// Sourced from `petname::Petnames::medium()` (1198 adjectives, 1052 nouns —
+/// ~1.26M `codename(2)` combinations, ~1.5B for `codename(3)`). The pin in
+/// `Cargo.toml` is `=3.0.0`; bumping it may change, add, or remove words and
+/// would silently shift every existing user's `worktree-path` output. Treat
+/// any upgrade as a breaking change — see `test_codename_outputs_are_stable`.
+///
+/// `petname::Petnames::medium()` is effectively free — its `Cow::Borrowed`
+/// fields point at static slices embedded by the `petnames!` macro — so
+/// re-constructing per call is cheaper than reaching for a `OnceLock`.
+fn codename_words() -> petname::Petnames<'static> {
+ petname::Petnames::medium()
+}
+
/// Sanitize a branch name for use in filesystem paths.
///
/// Replaces path separators (`/` and `\`) with dashes to prevent directory traversal
@@ -464,6 +482,63 @@ pub fn short_hash(s: &str) -> String {
String::from_utf8(vec![c0, c1, c2]).unwrap()
}
+fn codename_index(input: &str, position: usize, salt: usize, pool: &str, len: usize) -> usize {
+ // Cast to a fixed-width type so the hash is identical across 32-bit and
+ // 64-bit builds. `usize::to_le_bytes` is architecture-dependent and would
+ // change the on-disk codename for the same branch when users move between
+ // architectures.
+ let mut hasher = Sha256::new();
+ hasher.update(input.as_bytes());
+ hasher.update([0]);
+ hasher.update((position as u64).to_le_bytes());
+ hasher.update((salt as u64).to_le_bytes());
+ hasher.update(pool.as_bytes());
+ let digest = hasher.finalize();
+ let mut bytes = [0_u8; 8];
+ bytes.copy_from_slice(&digest[..8]);
+ (u64::from_le_bytes(bytes) as usize) % len
+}
+
+fn codename(input: &str, words: usize) -> String {
+ let lists = codename_words();
+ let adjectives: &[&str] = lists.adjectives.as_ref();
+ let nouns: &[&str] = lists.nouns.as_ref();
+
+ let mut parts = Vec::with_capacity(words);
+ let adjective_count = words.saturating_sub(1);
+
+ for position in 0..adjective_count {
+ let mut salt = 0;
+ loop {
+ let index = codename_index(input, position, salt, "adjective", adjectives.len());
+ let word = adjectives[index];
+ if !parts.contains(&word) || salt >= adjectives.len() {
+ parts.push(word);
+ break;
+ }
+ salt += 1;
+ }
+ }
+
+ let index = codename_index(input, adjective_count, 0, "noun", nouns.len());
+ parts.push(nouns[index]);
+ parts.join("-")
+}
+
+fn invalid_filter_arg(message: impl Into<String>) -> minijinja::Error {
+ minijinja::Error::new(ErrorKind::InvalidOperation, message.into())
+}
+
+fn codename_filter(value: Value, words: Option<usize>) -> Result<String, minijinja::Error> {
+ let words = words.unwrap_or(2);
+ if words == 0 || words > CODENAME_MAX_WORDS {
+ return Err(invalid_filter_arg(format!(
+ "codename word count must be between 1 and {CODENAME_MAX_WORDS}"
+ )));
+ }
+ Ok(codename(value.as_str().unwrap_or_default(), words))
+}
+
/// Redact credentials from URLs for safe logging.
///
/// URLs with embedded credentials (e.g., `https://[email protected]/...`) have
@@ -631,6 +706,7 @@ fn setup_template_env(repo: &Repository) -> Environment<'static> {
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
});
+ env.add_filter("codename", codename_filter);
// Register worktree_path_of_branch function for looking up branch worktree paths.
// Returns raw paths — shell escaping is applied by the formatter at output time.
@@ -771,6 +847,7 @@ pub fn validate_template(
/// - `hash_port` — Hash to deterministic port number (10000-19999)
/// - `dirname` — Strip the last path component (e.g., `/a/b/c` → `/a/b`)
/// - `basename` — Keep only the last path component (e.g., `/a/b/c` → `c`)
+/// - `codename(n)` — deterministic friendly words, e.g. `malleable-opah`
///
/// # Functions
/// - `worktree_path_of_branch(branch)` — Look up the filesystem path of a branch's worktree
@@ -1466,6 +1543,205 @@ mod tests {
assert_eq!(empty.len(), 3);
}
+ #[test]
+ fn test_codename_filter() {
+ let test = test_repo();
+ let mut vars = HashMap::new();
+ vars.insert("branch", "feature/very-long-branch-name");
+
+ let default =
+ expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
+ let explicit_default = expand_template(
+ "{{ branch | codename(2) }}",
+ &vars,
+ false,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
+ assert_eq!(default, explicit_default);
+ assert_eq!(default.split('-').count(), 2, "got: {default}");
+
+ let one_word = expand_template(
+ "{{ branch | codename(1) }}",
+ &vars,
+ false,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
+ assert!(!one_word.contains('-'), "got: {one_word}");
+ let lists = codename_words();
+ let nouns: &[&str] = lists.nouns.as_ref();
+ assert!(nouns.contains(&one_word.as_str()));
+
+ let three_words = expand_template(
+ "{{ branch | codename(3) }}",
+ &vars,
+ false,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
+ assert_eq!(three_words.split('-').count(), 3, "got: {three_words}");
+
+ let repeat =
+ expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
+ assert_eq!(default, repeat);
+
+ vars.insert("branch", "feature/different-name");
+ let other =
+ expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
+ assert_eq!(other.split('-').count(), 2, "got: {other}");
+
+ vars.insert("branch", "feature/73");
+ let ticket_73 = expand_template(
+ "{{ branch | codename(3) }}",
+ &vars,
+ false,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
+ vars.insert("branch", "feature/149");
+ let ticket_149 = expand_template(
+ "{{ branch | codename(3) }}",
+ &vars,
+ false,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
+ assert_ne!(ticket_73, ticket_149);
+ }
+
+ #[test]
+ fn test_codename_filter_rejects_invalid_counts() {
+ let test = test_repo();
+ let mut vars = HashMap::new();
+ vars.insert("branch", "feature");
+
+ let zero = expand_template(
+ "{{ branch | codename(0) }}",
+ &vars,
+ false,
+ &test.repo,
+ "test",
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(
+ zero.contains("codename word count must be between 1 and 8"),
+ "got: {zero}"
+ );
+
+ let too_many = expand_template(
+ "{{ branch | codename(9) }}",
+ &vars,
+ false,
+ &test.repo,
+ "test",
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(
+ too_many.contains("codename word count must be between 1 and 8"),
+ "got: {too_many}"
+ );
+ }
+
+ #[test]
+ fn test_codename_word_lists_are_path_safe() {
+ fn assert_word_list(name: &str, words: &[&str]) {
+ assert!(words.len() >= 160, "{name} should have enough entries");
+ let mut seen = std::collections::HashSet::new();
+ for &word in words {
+ assert!(seen.insert(word), "duplicate {name} word: {word}");
+ assert!(!word.is_empty(), "empty {name} word");
+ assert!(
+ word.chars().all(|c| c.is_ascii_lowercase()),
+ "{name} word is not lowercase ASCII: {word}"
+ );
+ assert!(
+ !word.contains('-') && !word.contains(' '),
+ "{name} word is not a single path component fragment: {word}"
+ );
+ }
+ }
+
+ let lists = codename_words();
+ let adjectives: &[&str] = lists.adjectives.as_ref();
+ let nouns: &[&str] = lists.nouns.as_ref();
+ assert_word_list("adjective", adjectives);
+ assert_word_list("noun", nouns);
+ // codename(2) cardinality — petname::medium() gives ~1.26M combinations,
+ // so a single adjective+noun pair is enough on its own for typical
+ // worktree counts.
+ assert!(adjectives.len() * nouns.len() >= 1_000_000);
+ }
+
+ /// Pins specific `codename(input, n)` outputs so the on-disk contract
+ /// is impossible to break by accident. Once a user adopts this filter in
+ /// their `worktree-path` template, the petname wordlists (and the
+ /// hash-input layout in `codename_index`) become an on-disk identity for
+ /// every worktree they own. Anything that shifts the wordlists (a
+ /// `petname` version bump that adds, removes, or reorders a word) or
+ /// changes how the hash is computed produces a different name for the
+ /// same branch on the next `wt switch`, orphaning the existing worktree.
+ ///
+ /// If this test fails:
+ ///
+ /// 1. Stop. Do not update the expected values to silence it.
+ /// 2. Confirm whether you actually intended to change the wordlists
+ /// (e.g. via a `petname` version bump) or the hash layout. If it was
+ /// unintentional (a refactor, a Cargo update), revert.
+ /// 3. If the change is intentional, accept that you are breaking every
+ /// existing user's worktree paths. Coordinate the rollout, document
+ /// it as a breaking change, and only then update the expected values.
+ #[test]
+ fn test_codename_outputs_are_stable() {
+ let cases: &[(&str, usize, &str)] = &[
+ ("main", 1, "gorilla"),
+ ("feature/auth", 2, "malleable-opah"),
+ ("feature/73", 2, "prodigious-shoveler"),
+ ("feature/149", 2, "tuneful-vendace"),
+ ("release/1.0", 3, "intent-equipped-treefrog"),
+ (
+ "hotfix/some-very-long-thing",
+ 4,
+ "noteworthy-musical-durable-silkworm",
+ ),
+ ];
+
+ for (input, n, expected) in cases {
+ let actual = codename(input, *n);
+ assert_eq!(
+ &actual, expected,
+ "\n\
+ codename({input:?}, {n}) returned {actual:?}, expected {expected:?}.\n\
+ \n\
+ Changing the petname version, or the codename algorithm,\n\
+ BREAKS every existing user's worktree paths derived from\n\
+ `{{{{ branch | codename(...) }}}}`. See the comment above\n\
+ this test before updating these expectations.\n"
+ );
+ }
+ }
+
+ #[test]
+ fn test_validate_template_accepts_codename_filter() {
+ let test = test_repo();
+ assert!(
+ validate_template(
+ "{{ branch | codename(2) }}",
+ ValidationScope::SwitchExecute,
+ &test.repo,
+ "test"
+ )
+ .is_ok()
+ );
+ }
+
#[test]
fn test_hash_port_filter() {
let test = test_repo();
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 944a28951..df3ff09d5 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -1623,6 +1623,46 @@ fn test_switch_create_no_hint_with_custom_worktree_path(repo: TestRepo) {
);
}
+#[rstest]
+fn test_switch_create_uses_codename_in_worktree_path(repo: TestRepo) {
+ repo.write_test_config(
+ r#"worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(3) }}""#,
+ );
+
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "feature/JIRA-1234",
+ "--format=json",
+ "--no-cd",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "switch --create should succeed, stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let path = Path::new(json["path"].as_str().unwrap());
+ let dir_name = path.file_name().unwrap().to_str().unwrap();
+ let repo_prefix = format!(
+ "{}.",
+ repo.root_path().file_name().unwrap().to_str().unwrap()
+ );
+ let codename = dir_name.strip_prefix(&repo_prefix).unwrap();
+
+ assert!(path.exists(), "worktree should exist @ {}", path.display());
+ assert_eq!(codename.split('-').count(), 3, "got: {codename}");
+ assert!(
+ codename.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
+ "got: {codename}"
+ );
+}
+
/// Test that the worktree-path hint is suppressed when a project-specific
/// worktree-path is configured (not just a global one).
///
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index e78a14951..601d4b575 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -84,6 +84,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # - `{{ branch }}` — raw branch name (e.g., `feature/auth`)
  # - `{{ branch | sanitize }}` — filesystem-safe: `/` and `\` become `-` (e.g., `feature-auth`)
  # - `{{ branch | sanitize_db }}` — database-safe: lowercase, underscores, hash suffix (e.g., `feature_auth_x7k`)
+  # - `{{ branch | codename(2) }}` — deterministic friendly name from a ~1.26M-combo pool (e.g., `malleable-opah`)
  #
  # **Examples** for repo at `~/code/myproject`, branch `feature/auth`:
  #
@@ -95,6 +96,14 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  #
  # worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"
  #
+  # Friendly branch-derived names (`~/code/myproject.malleable-opah`):
+  #
+  # worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+  #
+  # Friendly names with branch identity in a parent directory (`~/code/worktrees/feature-auth/malleable-opah`):
+  #
+  # worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+  #
  # Centralized worktrees directory (`~/worktrees/myproject/feature-auth`):
  #
  # worktree-path = "~/worktrees/{{ repo }}/{{ branch | sanitize }}"
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 9a0516336..b33d54106 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -132,6 +132,7 @@ Controls where new worktrees are created.
- {{ branch }} — raw branch name (e.g., feature/auth)
- {{ branch | sanitize }} — filesystem-safe: / and \ become - (e.g., feature-auth)
- {{ branch | sanitize_db }} — database-safe: lowercase, underscores, hash suffix (e.g., feature_auth_x7k)
+- {{ branch | codename(2) }} — deterministic friendly name from a ~1.26M-combo pool (e.g., malleable-opah)
Examples for repo at ~/code/myproject, branch feature/auth:
@@ -143,6 +144,14 @@ Inside the repository (~/code/myproject/.worktrees/feature-auth):
  worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"
+Friendly branch-derived names (~/code/myproject.malleable-opah):
+
+  worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"
+
+Friendly names with branch identity in a parent directory (~/code/worktrees/feature-auth/malleable-opah):
+
+  worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"
+
Centralized worktrees directory (~/worktrees/myproject/feature-auth):
  worktree-path = "~/worktrees/{{ repo }}/{{ branch | sanitize }}"