Skip to content

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

feat: add `wt config state vars` for per-branch custom variables (#1006)

Maximilian Roos69edc3a3373b
diff --git a/docs/content/config.md b/docs/content/config.md
index c126b1f34..4f427cf44 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -516,6 +516,7 @@ Use `wt config show` to view file-based configuration.
- **previous-branch**: Previous branch for `wt switch -`
- **ci-status**: CI/PR status for a branch (passed, running, failed, conflicts, no-ci, error)
- **marker**: Custom status marker for a branch (shown in `wt list`)
+- **vars**: <span class="badge-experimental"></span> Custom variables per branch
- **logs**: Background operation logs
### Examples
@@ -529,6 +530,9 @@ Set the default branch manually:
Set a marker for current branch:
{{ terminal(cmd="wt config state marker set __WT_QUOT__🚧 WIP__WT_QUOT__") }}
+Store arbitrary data:
+{{ terminal(cmd="wt config state vars set env=staging") }}
+
Clear all CI status cache:
{{ terminal(cmd="wt config state ci-status clear --all") }}
@@ -552,6 +556,7 @@ Usage: <b><span class=c>wt config state</span></b> <span class=c>[OPTIONS]</span
<b><span class=c>marker</span></b> Branch markers
<b><span class=c>logs</span></b> Background operation logs
<b><span class=c>hints</span></b> One-time hints shown in this repo
+ <b><span class=c>vars</span></b> [experimental] Custom variables per branch
<b><span class=c>get</span></b> Get all stored state
<b><span class=c>clear</span></b> Clear all stored state
@@ -735,6 +740,77 @@ Usage: <b><span class=c>wt config state marker</span></b> <span class=c>[OPTIONS
Verbose output (-v: hooks, templates; -vv: debug report)
{% end %}
+## wt config state vars
+
+<span class="badge-experimental"></span>
+
+Custom variables per branch.
+
+Store custom variables per branch. Values are stored as-is β€” plain strings or JSON.
+
+### Examples
+
+Set and get values:
+{{ terminal(cmd="wt config state vars set env=staging|||wt config state vars get env") }}
+
+Store JSON:
+{{ terminal(cmd="wt config state vars set config='{__WT_QUOT__port__WT_QUOT__: 3000, __WT_QUOT__debug__WT_QUOT__: true}'") }}
+
+List all keys:
+{{ terminal(cmd="wt config state vars list") }}
+
+Operate on a different branch:
+{{ terminal(cmd="wt config state vars set env=production --branch=main") }}
+
+### Template access
+
+Variables are available in hook templates as `{{ vars.<key> }}`. Use the `default` filter for keys that may not be set:
+
+```toml
+[post-start]
+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.port | default('3000') }}"
+```
+
+JSON object and array values support dot access:
+
+{{ terminal(cmd="wt config state vars set config='{__WT_QUOT__port__WT_QUOT__: 3000, __WT_QUOT__debug__WT_QUOT__: true}'") }}
+```toml
+[post-start]
+dev = "npm start -- --port {{ vars.config.port }}"
+```
+
+### Storage format
+
+Stored in git config as `worktrunk.state.<branch>.vars.<key>`. Keys must contain only letters, digits, hyphens, and underscores β€” dots conflict with git config's section separator.
+
+### Command reference
+
+{% terminal() %}
+wt config state vars - [experimental] Custom variables per branch
+
+Usage: <b><span class=c>wt config state vars</span></b> <span class=c>[OPTIONS]</span> <span class=c>&lt;COMMAND&gt;</span>
+
+<b><span class=g>Commands:</span></b>
+ <b><span class=c>get</span></b> Get a value
+ <b><span class=c>set</span></b> Set a value
+ <b><span class=c>list</span></b> List all keys
+ <b><span class=c>clear</span></b> Clear a key or all keys
+
+<b><span class=g>Options:</span></b>
+ <b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
+ Print help (see a summary with &#39;-h&#39;)
+
+<b><span class=g>Global Options:</span></b>
+ <b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
+ Working directory for this command
+
+ <b><span class=c>--config</span></b><span class=c> &lt;path&gt;</span>
+ User config file path
+
+ <b><span class=c>-v</span></b>, <b><span class=c>--verbose</span></b><span class=c>...</span>
+ Verbose output (-v: hooks, templates; -vv: debug report)
+{% end %}
+
## wt config state logs
Background operation logs.
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 8a3cf6ff2..1ee06e532 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -113,7 +113,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| Location | Purpose | Created by |
|----------|---------|------------|
-| `.git/config` keys under `worktrunk.*` | Cached default branch, switch history, branch markers | Various commands |
+| `.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/*.log` | Background command output | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
diff --git a/docs/content/hook.md b/docs/content/hook.md
index bf199a0fd..6622e2814 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -118,6 +118,7 @@ Hooks can use template variables that expand at runtime:
| `{{ remote_url }}` | Remote URL |
| `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) |
| `{{ hook_name }}` | Hook command name (if named) |
+| `{{ vars.<key> }}` | Per-branch variables from `wt config state vars` |
Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the operation acts on: the destination for switch/create, the source for merge/remove. `base` and `target` give the other side:
@@ -129,7 +130,7 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope
Pre and post hooks share the same perspective β€” `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same β€” the active worktree is gone, so the hook runs in target.
-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks. Undefined variables error β€” use conditionals:
+Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error β€” use conditionals or defaults for optional behavior:
```toml
[pre-start]
@@ -137,6 +138,13 @@ Some variables are conditional: `upstream` requires remote tracking; `base`/`tar
sync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"
```
+Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:
+
+```toml
+[post-start]
+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"
+```
+
## Worktrunk filters
Templates support Jinja2 filters for transforming values:
@@ -325,7 +333,7 @@ server = "npm run dev -- --host {{ branch | sanitize }}.localhost --port {{ bran
## Databases
-Each worktree can have its own database. Docker containers get unique names and ports:
+Each worktree can have its own database. Docker containers get unique names and ports, and the connection string is stored in `vars` for use outside hooks:
```toml
[post-start]
@@ -337,25 +345,17 @@ docker run -d --rm \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
+db-url = "wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'"
[post-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.
-Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.
-Generate `.env.local` with the connection string:
+The connection string is now accessible anywhere β€” not just in hooks:
-```toml
-[pre-start]
-env = """
-cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
-DEV_PORT={{ branch | hash_port }}
-EOF
-"""
-```
+{{ terminal(cmd="DATABASE_URL=$(wt config state vars get db-url) npm start") }}
## Progressive validation
diff --git a/docs/content/list.md b/docs/content/list.md
index 01febe9bb..c8ca1e39a 100644
--- a/docs/content/list.md
+++ b/docs/content/list.md
@@ -162,6 +162,7 @@ Query structured data with `--format=json`:
| `summary` | string | LLM-generated branch summary; absent when not configured or no summary |
| `statusline` | string | Pre-formatted status with ANSI colors |
| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |
+| `vars` | object | Per-branch variables from `wt config state vars` (absent when empty) |
### Commit object
diff --git a/docs/content/tips-patterns.md b/docs/content/tips-patterns.md
index dfa763808..fc4ca04f6 100644
--- a/docs/content/tips-patterns.md
+++ b/docs/content/tips-patterns.md
@@ -65,7 +65,7 @@ Ports are deterministic β€” `fix-auth` always gets port 16460, regardless of whi
## Database per worktree
-Each worktree can have its own isolated database. Docker containers get unique names and ports:
+Each worktree can have its own isolated database. Docker containers get unique names and ports, and the connection string is stored in `vars` for use outside hooks:
```toml
[post-start]
@@ -77,27 +77,17 @@ docker run -d --rm \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
+db-url = "wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'"
[pre-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
-The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.
-Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.
+The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide. The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix to avoid collisions and SQL reserved words).
-The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix to avoid collisions and SQL reserved words).
+The connection string is now accessible anywhere β€” not just in hooks:
-Generate `.env.local` with the correct `DATABASE_URL` using a `pre-start` hook:
-
-```toml
-[pre-start]
-env = """
-cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
-DEV_PORT={{ branch | hash_port }}
-EOF
-"""
-```
+{{ terminal(cmd="DATABASE_URL=$(wt config state vars get db-url) npm start") }}
## Local CI gate
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index d8985070a..a910ef2ac 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -517,6 +517,7 @@ Use `wt config show` to view file-based configuration.
- **previous-branch**: Previous branch for `wt switch -`
- **ci-status**: CI/PR status for a branch (passed, running, failed, conflicts, no-ci, error)
- **marker**: Custom status marker for a branch (shown in `wt list`)
+- **vars**: [experimental] Custom variables per branch
- **logs**: Background operation logs
### Examples
@@ -536,6 +537,11 @@ Set a marker for current branch:
$ wt config state marker set "🚧 WIP"
```
+Store arbitrary data:
+```bash
+$ wt config state vars set env=staging
+```
+
Clear all CI status cache:
```bash
$ wt config state ci-status clear --all
@@ -564,6 +570,7 @@ Usage: <b><span class=c>wt config state</span></b> <span class=c>[OPTIONS]</span
<b><span class=c>marker</span></b> Branch markers
<b><span class=c>logs</span></b> Background operation logs
<b><span class=c>hints</span></b> One-time hints shown in this repo
+ <b><span class=c>vars</span></b> [experimental] Custom variables per branch
<b><span class=c>get</span></b> Get all stored state
<b><span class=c>clear</span></b> Clear all stored state
@@ -744,6 +751,86 @@ Usage: <b><span class=c>wt config state marker</span></b> <span class=c>[OPTIONS
<b><span class=c>-v</span></b>, <b><span class=c>--verbose</span></b><span class=c>...</span>
Verbose output (-v: hooks, templates; -vv: debug report)
+## wt config state vars
+
+[experimental]
+
+Custom variables per branch.
+
+Store custom variables per branch. Values are stored as-is β€” plain strings or JSON.
+
+### Examples
+
+Set and get values:
+```bash
+$ wt config state vars set env=staging
+$ wt config state vars get env
+```
+
+Store JSON:
+```bash
+$ wt config state vars set config='{"port": 3000, "debug": true}'
+```
+
+List all keys:
+```bash
+$ wt config state vars list
+```
+
+Operate on a different branch:
+```bash
+$ wt config state vars set env=production --branch=main
+```
+
+### Template access
+
+Variables are available in hook templates as `{{ vars.<key> }}`. Use the `default` filter for keys that may not be set:
+
+```toml
+[post-start]
+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.port | default('3000') }}"
+```
+
+JSON object and array values support dot access:
+
+```bash
+$ wt config state vars set config='{"port": 3000, "debug": true}'
+```
+```toml
+[post-start]
+dev = "npm start -- --port {{ vars.config.port }}"
+```
+
+### Storage format
+
+Stored in git config as `worktrunk.state.<branch>.vars.<key>`. Keys must contain only letters, digits, hyphens, and underscores β€” dots conflict with git config's section separator.
+
+### Command reference
+
+wt config state vars - [experimental] Custom variables per branch
+
+Usage: <b><span class=c>wt config state vars</span></b> <span class=c>[OPTIONS]</span> <span class=c>&lt;COMMAND&gt;</span>
+
+<b><span class=g>Commands:</span></b>
+ <b><span class=c>get</span></b> Get a value
+ <b><span class=c>set</span></b> Set a value
+ <b><span class=c>list</span></b> List all keys
+ <b><span class=c>clear</span></b> Clear a key or all keys
+
+<b><span class=g>Options:</span></b>
+ <b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
+ Print help (see a summary with &#39;-h&#39;)
+
+<b><span class=g>Global Options:</span></b>
+ <b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
+ Working directory for this command
+
+ <b><span class=c>--config</span></b><span class=c> &lt;path&gt;</span>
+ User config file path
+
+ <b><span class=c>-v</span></b>, <b><span class=c>--verbose</span></b><span class=c>...</span>
+ Verbose output (-v: hooks, templates; -vv: debug report)
+
## wt config state logs
Background operation logs.
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index b2a6c94ea..17f9933f0 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -106,7 +106,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| Location | Purpose | Created by |
|----------|---------|------------|
-| `.git/config` keys under `worktrunk.*` | Cached default branch, switch history, branch markers | Various commands |
+| `.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/*.log` | Background command output | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 3fe1c6542..e44d10d71 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -107,6 +107,7 @@ Hooks can use template variables that expand at runtime:
| `{{ remote_url }}` | Remote URL |
| `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) |
| `{{ hook_name }}` | Hook command name (if named) |
+| `{{ vars.<key> }}` | Per-branch variables from `wt config state vars` |
Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the operation acts on: the destination for switch/create, the source for merge/remove. `base` and `target` give the other side:
@@ -118,7 +119,7 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope
Pre and post hooks share the same perspective β€” `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same β€” the active worktree is gone, so the hook runs in target.
-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks. Undefined variables error β€” use conditionals:
+Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error β€” use conditionals or defaults for optional behavior:
```toml
[pre-start]
@@ -126,6 +127,13 @@ Some variables are conditional: `upstream` requires remote tracking; `base`/`tar
sync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"
```
+Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:
+
+```toml
+[post-start]
+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"
+```
+
## Worktrunk filters
Templates support Jinja2 filters for transforming values:
@@ -323,7 +331,7 @@ server = "npm run dev -- --host {{ branch | sanitize }}.localhost --port {{ bran
## Databases
-Each worktree can have its own database. Docker containers get unique names and ports:
+Each worktree can have its own database. Docker containers get unique names and ports, and the connection string is stored in `vars` for use outside hooks:
```toml
[post-start]
@@ -335,24 +343,18 @@ docker run -d --rm \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
+db-url = "wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'"
[post-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.
-Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.
-Generate `.env.local` with the connection string:
+The connection string is now accessible anywhere β€” not just in hooks:
-```toml
-[pre-start]
-env = """
-cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
-DEV_PORT={{ branch | hash_port }}
-EOF
-"""
+```bash
+$ DATABASE_URL=$(wt config state vars get db-url) npm start
```
## Progressive validation
diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.md
index 49577a5b4..0e9757331 100644
--- a/skills/worktrunk/reference/list.md
+++ b/skills/worktrunk/reference/list.md
@@ -178,6 +178,7 @@ $ wt list --format=json --full | jq '.[] | select(.ci.stale) | .branch'
| `summary` | string | LLM-generated branch summary; absent when not configured or no summary |
| `statusline` | string | Pre-formatted status with ANSI colors |
| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |
+| `vars` | object | Per-branch variables from `wt config state vars` (absent when empty) |
### Commit object
diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.md
index 893980bc6..9b94d2b0c 100644
--- a/skills/worktrunk/reference/tips-patterns.md
+++ b/skills/worktrunk/reference/tips-patterns.md
@@ -58,7 +58,7 @@ Ports are deterministic β€” `fix-auth` always gets port 16460, regardless of whi
## Database per worktree
-Each worktree can have its own isolated database. Docker containers get unique names and ports:
+Each worktree can have its own isolated database. Docker containers get unique names and ports, and the connection string is stored in `vars` for use outside hooks:
```toml
[post-start]
@@ -70,26 +70,18 @@ docker run -d --rm \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
+db-url = "wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'"
[pre-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
-The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.
-Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.
+The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide. The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix to avoid collisions and SQL reserved words).
-The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix to avoid collisions and SQL reserved words).
+The connection string is now accessible anywhere β€” not just in hooks:
-Generate `.env.local` with the correct `DATABASE_URL` using a `pre-start` hook:
-
-```toml
-[pre-start]
-env = """
-cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
-DEV_PORT={{ branch | hash_port }}
-EOF
-"""
+```bash
+$ DATABASE_URL=$(wt config state vars get db-url) npm start
```
## Local CI gate
diff --git a/src/cli/config.rs b/src/cli/config.rs
index ca6b2361e..3305f6b1f 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -271,6 +271,7 @@ Use `wt config show` to view file-based configuration.
- **previous-branch**: Previous branch for `wt switch -`
- **ci-status**: CI/PR status for a branch (passed, running, failed, conflicts, no-ci, error)
- **marker**: Custom status marker for a branch (shown in `wt list`)
+- **vars**: [experimental] Custom variables per branch
- **logs**: Background operation logs
## Examples
@@ -290,6 +291,11 @@ Set a marker for current branch:
$ wt config state marker set "🚧 WIP"
```
+Store arbitrary data:
+```console
+$ wt config state vars set env=staging
+```
+
Clear all CI status cache:
```console
$ wt config state ci-status clear --all
@@ -307,6 +313,7 @@ $ wt config state clear
<!-- subdoc: default-branch -->
<!-- subdoc: ci-status -->
<!-- subdoc: marker -->
+<!-- subdoc: vars -->
<!-- subdoc: logs -->"#
)]
State {
@@ -513,12 +520,69 @@ $ wt config state hints clear NAME # re-show specific hint
action: Option<HintsAction>,
},
+ /// \[experimental\] Custom variables per branch
+ #[command(
+ name = "vars",
+ after_long_help = r#"Store custom variables per branch. Values are stored as-is β€” plain strings or JSON.
+
+## Examples
+
+Set and get values:
+```console
+$ wt config state vars set env=staging
+$ wt config state vars get env
+```
+
+Store JSON:
+```console
+$ wt config state vars set config='{"port": 3000, "debug": true}'
+```
+
+List all keys:
+```console
+$ wt config state vars list
+```
+
+Operate on a different branch:
+```console
+$ wt config state vars set env=production --branch=main
+```
+
+## Template access
+
+Variables are available in hook templates as `{{ vars.<key> }}`. Use the `default` filter for keys that may not be set:
+
+```toml
+[post-start]
+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.port | default('3000') }}"
+```
+
+JSON object and array values support dot access:
+
+```console
+$ wt config state vars set config='{"port": 3000, "debug": true}'
+```
+```toml
+[post-start]
+dev = "npm start -- --port {{ vars.config.port }}"
+```
+
+## Storage format
+
+Stored in git config as `worktrunk.state.<branch>.vars.<key>`. Keys must contain only letters, digits, hyphens, and underscores β€” dots conflict with git config's section separator."#
+ )]
+ Vars {
+ #[command(subcommand)]
+ action: VarsAction,
+ },
+
/// Get all stored state
#[command(after_long_help = r#"Shows all stored state including:
- **Default branch**: Cached result of querying remote for default branch
- **Previous branch**: Previous branch for `wt switch -`
- **Branch markers**: User-defined branch notes
+- **Vars**: Custom variables per branch
- **CI status**: Cached GitHub/GitLab CI status per branch (30s TTL)
- **Hints**: One-time hints that have been shown
- **Log files**: Background operation logs
@@ -536,6 +600,7 @@ CI cache entries show status, age, and the commit SHA they were fetched for."#)]
- Default branch cache
- Previous branch
- All branch markers
+- All variables
- All CI status cache
- All hints
- All log files
@@ -819,3 +884,103 @@ $ wt config state hints clear worktree-path
name: Option<String>,
},
}
+
+#[derive(Subcommand)]
+pub enum VarsAction {
+ /// Get a value
+ #[command(after_long_help = r#"## Examples
+
+Get a value for the current branch:
+```console
+$ wt config state vars get env
+```
+
+Get a value for a specific branch:
+```console
+$ wt config state vars get env --branch=feature
+```"#)]
+ Get {
+ /// Key name
+ key: String,
+
+ /// Target branch (defaults to current)
+ #[arg(long, add = crate::completion::branch_value_completer())]
+ branch: Option<String>,
+ },
+
+ /// Set a value
+ #[command(after_long_help = r#"## Examples
+
+Set a plain string:
+```console
+$ wt config state vars set env=staging
+```
+
+Set JSON:
+```console
+$ wt config state vars set config='{"port": 3000}'
+```
+
+Set for a specific branch:
+```console
+$ wt config state vars set env=production --branch=main
+```"#)]
+ Set {
+ /// KEY=VALUE pair
+ #[arg(value_name = "KEY=VALUE", value_parser = super::parse_vars_assignment)]
+ assignment: (String, String),
+
+ /// Target branch (defaults to current)
+ #[arg(long, add = crate::completion::branch_value_completer())]
+ branch: Option<String>,
+ },
+
+ /// List all keys
+ #[command(after_long_help = r#"## Examples
+
+List keys for current branch:
+```console
+$ wt config state vars list
+```
+
+List keys for a specific branch:
+```console
+$ wt config state vars list --branch=feature
+```"#)]
+ List {
+ /// Target branch (defaults to current)
+ #[arg(long, add = crate::completion::branch_value_completer())]
+ branch: Option<String>,
+ },
+
+ /// Clear a key or all keys
+ #[command(after_long_help = r#"## Examples
+
+Clear a specific key:
+```console
+$ wt config state vars clear env
+```
+
+Clear all keys for current branch:
+```console
+$ wt config state vars clear --all
+```
+
+Clear all keys for a specific branch:
+```console
+$ wt config state vars clear env --branch=feature
+```"#)]
+ Clear {
+ /// Key to clear (required unless --all)
+ #[arg(conflicts_with = "all")]
+ key: Option<String>,
+
+ /// Clear all keys for the branch
+ #[arg(long)]
+ all: bool,
+
+ /// Target branch (defaults to current)
+ #[arg(long, add = crate::completion::branch_value_completer())]
+ branch: Option<String>,
+ },
+}
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 3306de461..a6abfa934 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -5,7 +5,7 @@ mod step;
pub(crate) use config::{
ApprovalsCommand, CiStatusAction, ConfigCommand, ConfigShellCommand, DefaultBranchAction,
- HintsAction, LogsAction, MarkerAction, PreviousBranchAction, StateCommand,
+ HintsAction, LogsAction, MarkerAction, PreviousBranchAction, StateCommand, VarsAction,
};
pub(crate) use hook::HookCommand;
pub(crate) use list::ListSubcommand;
@@ -39,6 +39,20 @@ pub(super) fn parse_key_val(s: &str) -> Result<(String, String), String> {
Ok((key.to_string(), value.to_string()))
}
+/// Parse KEY=VALUE string for `wt config state vars set`.
+///
+/// Like `parse_key_val`, but without template variable name validation.
+/// Key validation is deferred to `validate_vars_key` in the command handler.
+pub(super) fn parse_vars_assignment(s: &str) -> Result<(String, String), String> {
+ let (key, value) = s
+ .split_once('=')
+ .ok_or_else(|| format!("invalid KEY=VALUE: no `=` found in `{s}`"))?;
+ if key.is_empty() {
+ return Err("invalid KEY=VALUE: key cannot be empty".to_string());
+ }
+ Ok((key.to_string(), value.to_string()))
+}
+
/// Custom styles for help output - matches worktrunk's color scheme
fn help_styles() -> Styles {
Styles::styled()
@@ -629,6 +643,7 @@ $ wt list --format=json --full | jq '.[] | select(.ci.stale) | .branch'
| `summary` | string | LLM-generated branch summary; absent when not configured or no summary |
| `statusline` | string | Pre-formatted status with ANSI colors |
| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |
+| `vars` | object | Per-branch variables from `wt config state vars` (absent when empty) |
### Commit object
@@ -1206,6 +1221,7 @@ Hooks can use template variables that expand at runtime:
| `{{ remote_url }}` | Remote URL |
| `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) |
| `{{ hook_name }}` | Hook command name (if named) |
+| `{{ vars.<key> }}` | Per-branch variables from `wt config state vars` |
Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the operation acts on: the destination for switch/create, the source for merge/remove. `base` and `target` give the other side:
@@ -1217,7 +1233,7 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope
Pre and post hooks share the same perspective β€” `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same β€” the active worktree is gone, so the hook runs in target.
-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks. Undefined variables error β€” use conditionals:
+Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error β€” use conditionals or defaults for optional behavior:
```toml
[pre-start]
@@ -1225,6 +1241,13 @@ Some variables are conditional: `upstream` requires remote tracking; `base`/`tar
sync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"
```
+Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:
+
+```toml
+[post-start]
+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"
+```
+
## Worktrunk filters
Templates support Jinja2 filters for transforming values:
@@ -1420,7 +1443,7 @@ server = "npm run dev -- --host {{ branch | sanitize }}.localhost --port {{ bran
## Databases
-Each worktree can have its own database. Docker containers get unique names and ports:
+Each worktree can have its own database. Docker containers get unique names and ports, and the connection string is stored in `vars` for use outside hooks:
```toml
[post-start]
@@ -1432,24 +1455,18 @@ docker run -d --rm \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
+db-url = "wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'"
[post-remove]
db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"
```
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.
-Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.
-Generate `.env.local` with the connection string:
+The connection string is now accessible anywhere β€” not just in hooks:
-```toml
-[pre-start]
-env = """
-cat > .env.local << EOF
-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}
-DEV_PORT={{ branch | hash_port }}
-EOF
-"""
+```console
+$ DATABASE_URL=$(wt config state vars get db-url) npm start
```
## Progressive validation
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index 5c0e129be..ab23bf3e2 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -14,7 +14,8 @@ pub use hints::{handle_hints_clear, handle_hints_get};
pub use show::handle_config_show;
pub use state::{
handle_logs_get, handle_state_clear, handle_state_clear_all, handle_state_get,
- handle_state_set, handle_state_show,
+ handle_state_set, handle_state_show, handle_vars_clear, handle_vars_get, handle_vars_list,
+ handle_vars_set,
};
pub use update::handle_config_update;
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index f161f8896..5518d38d6 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -586,6 +586,12 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {
cleared_any = true;
}
+ // Clear all vars data
+ let vars_cleared = clear_all_vars(&repo)?;
+ if vars_cleared > 0 {
+ cleared_any = true;
+ }
+
// Clear all logs
let logs_cleared = clear_logs(&repo)?;
if logs_cleared > 0 {
@@ -713,6 +719,21 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
(vec![], vec![])
};
+ // Get vars data (all branches) β€” collect into BTreeMap for sorted output
+ let all_vars: std::collections::BTreeMap<_, _> = repo.all_vars_entries().into_iter().collect();
+ let vars_data: Vec<serde_json::Value> = all_vars
+ .into_iter()
+ .flat_map(|(branch, entries)| {
+ entries.into_iter().map(move |(key, value)| {
+ serde_json::json!({
+ "branch": branch,
+ "key": key,
+ "value": value
+ })
+ })
+ })
+ .collect();
+
// Get hints
let hints = repo.list_shown_hints();
@@ -721,6 +742,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
"previous_branch": previous_branch,
"markers": markers,
"ci_status": ci_status,
+ "vars": vars_data,
"command_log": command_log,
"hook_output": hook_output,
"hints": hints
@@ -771,6 +793,31 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
}
writeln!(out)?;
+ // Show vars data
+ writeln!(out, "{}", format_heading("VARS", None))?;
+ let all_vars: std::collections::BTreeMap<_, _> = repo.all_vars_entries().into_iter().collect();
+
+ if all_vars.is_empty() {
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
+ } else {
+ let mut table = String::from("| Branch | Key | Value |\n");
+ table.push_str("|--------|-----|-------|\n");
+ for (branch, entries) in &all_vars {
+ for (key, value) in entries {
+ // Truncate long values for display
+ let display_value = if value.len() > 40 {
+ format!("{}...", &value[..37])
+ } else {
+ value.to_string()
+ };
+ table.push_str(&format!("| {branch} | {key} | {display_value} |\n"));
+ }
+ }
+ let rendered = crate::md_help::render_markdown_table(&table);
+ writeln!(out, "{}", rendered.trim_end())?;
+ }
+ writeln!(out)?;
+
// Show CI status cache
writeln!(out, "{}", format_heading("CI STATUS CACHE", None))?;
let mut entries = CachedCiStatus::list_all(repo);
@@ -834,6 +881,158 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
Ok(())
}
+// ==================== Vars Operations ====================
+
+/// Validate a vars key name: letters, digits, hyphens, underscores only.
+fn validate_vars_key(key: &str) -> anyhow::Result<()> {
+ if key.is_empty() {
+ anyhow::bail!("Key cannot be empty");
+ }
+ if !key
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ {
+ anyhow::bail!(
+ "Invalid key {key:?}: keys must contain only letters, digits, hyphens, and underscores"
+ );
+ }
+ Ok(())
+}
+
+/// Handle vars get
+pub fn handle_vars_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {
+ validate_vars_key(key)?;
+ let repo = Repository::current()?;
+ let branch_name = match branch {
+ Some(b) => b,
+ None => repo.require_current_branch("get variable for current branch")?,
+ };
+
+ let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
+ if let Some(value) = repo.config_value(&config_key)? {
+ println!("{value}");
+ }
+ Ok(())
+}
+
+/// Handle vars set
+pub fn handle_vars_set(key: &str, value: &str, branch: Option<String>) -> anyhow::Result<()> {
+ validate_vars_key(key)?;
+ let repo = Repository::current()?;
+ let branch_name = match branch {
+ Some(b) => b,
+ None => repo.require_current_branch("set variable for current branch")?,
+ };
+
+ let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
+ repo.run_command(&["config", &config_key, value])?;
+
+ eprintln!(
+ "{}",
+ success_message(cformat!("Set <bold>{key}</> for <bold>{branch_name}</>"))
+ );
+ Ok(())
+}
+
+/// Handle vars list
+pub fn handle_vars_list(branch: Option<String>) -> anyhow::Result<()> {
+ let repo = Repository::current()?;
+ let branch_name = match branch {
+ Some(b) => b,
+ None => repo.require_current_branch("list variables for current branch")?,
+ };
+
+ let entries: Vec<_> = repo.vars_entries(&branch_name).into_iter().collect();
+ if entries.is_empty() {
+ eprintln!(
+ "{}",
+ info_message(cformat!("No variables for <bold>{branch_name}</>"))
+ );
+ } else {
+ for (key, value) in &entries {
+ println!("{key}\t{value}");
+ }
+ }
+ Ok(())
+}
+
+/// Handle vars clear
+pub fn handle_vars_clear(
+ key: Option<&str>,
+ all: bool,
+ branch: Option<String>,
+) -> anyhow::Result<()> {
+ let repo = Repository::current()?;
+ let branch_name = match branch {
+ Some(b) => b,
+ None => repo.require_current_branch("clear variable for current branch")?,
+ };
+
+ if !all && key.is_none() {
+ anyhow::bail!("Specify a key to clear, or use --all to clear all keys");
+ }
+
+ if all {
+ let entries: Vec<_> = repo.vars_entries(&branch_name).into_iter().collect();
+ if entries.is_empty() {
+ eprintln!(
+ "{}",
+ info_message(cformat!("No variables for <bold>{branch_name}</>"))
+ );
+ } else {
+ let count = entries.len();
+ for (key, _) in entries {
+ let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
+ let _ = repo.run_command(&["config", "--unset", &config_key]);
+ }
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Cleared <bold>{count}</> variable{} for <bold>{branch_name}</>",
+ if count == 1 { "" } else { "s" }
+ ))
+ );
+ }
+ } else {
+ let key = key.expect("key required when --all not set");
+ validate_vars_key(key)?;
+ let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
+ if repo
+ .run_command(&["config", "--unset", &config_key])
+ .is_ok()
+ {
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Cleared <bold>{key}</> for <bold>{branch_name}</>"
+ ))
+ );
+ } else {
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "No variable <bold>{key}</> for <bold>{branch_name}</>"
+ ))
+ );
+ }
+ }
+ Ok(())
+}
+
+/// Clear all vars entries across all branches (used by handle_state_clear_all).
+fn clear_all_vars(repo: &Repository) -> anyhow::Result<usize> {
+ let all_vars = repo.all_vars_entries();
+ let mut cleared = 0;
+ for (branch, entries) in &all_vars {
+ for key in entries.keys() {
+ let config_key = format!("worktrunk.state.{branch}.vars.{key}");
+ let _ = repo.run_command(&["config", "--unset", &config_key]);
+ cleared += 1;
+ }
+ }
+ Ok(cleared)
+}
+
// ==================== Marker Helpers ====================
/// Marker entry with branch, text, and timestamp
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index 40abc8d71..361bb5f2a 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -15,11 +15,12 @@
//! - `remote`: relationship to tracking branch
//! - `worktree`: worktree-specific state (locked, prunable, etc.)
+use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use schemars::JsonSchema;
use serde::Serialize;
-use worktrunk::git::LineDiff;
+use worktrunk::git::{LineDiff, Repository};
use super::ci_status::{CiSource, PrStatus};
use super::model::{ItemKind, ListItem, UpstreamStatus};
@@ -102,6 +103,10 @@ pub struct JsonItem {
/// Raw status symbols without ANSI colors (e.g., "+! βœ– ↑")
#[serde(skip_serializing_if = "Option::is_none")]
pub symbols: Option<String>,
+
+ /// Custom variables stored via `wt config state vars`
+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]
+ pub vars: BTreeMap<String, String>,
}
/// Commit information
@@ -223,7 +228,13 @@ pub struct JsonCi {
impl JsonItem {
/// Convert a ListItem to the new JSON structure
- pub fn from_list_item(item: &ListItem) -> Self {
+ ///
+ /// `all_vars` is pre-fetched vars data for all branches (from `repo.all_vars_entries()`),
+ /// avoiding N+1 git process spawns. Entries are moved out via `.remove()` to avoid cloning.
+ pub fn from_list_item(
+ item: &ListItem,
+ all_vars: &mut HashMap<String, BTreeMap<String, String>>,
+ ) -> Self {
let (kind_str, worktree_data) = match &item.kind {
ItemKind::Worktree(data) => ("worktree", Some(data.as_ref())),
ItemKind::Branch => ("branch", None),
@@ -329,6 +340,13 @@ impl JsonItem {
.map(format_raw_symbols)
.filter(|s| !s.is_empty());
+ // Per-branch vars data (pre-fetched, moved out to avoid cloning)
+ let vars = item
+ .branch
+ .as_deref()
+ .and_then(|b| all_vars.remove(b))
+ .unwrap_or_default();
+
// Summary: flatten Option<Option<String>> β†’ Option<String>
let summary = item.summary.as_ref().and_then(|s| s.clone());
@@ -353,6 +371,7 @@ impl JsonItem {
summary,
statusline,
symbols,
+ vars,
}
}
}
@@ -456,8 +475,14 @@ fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {
}
/// Convert a list of ListItems to JSON output
-pub fn to_json_items(items: &[ListItem]) -> Vec<JsonItem> {
- items.iter().map(JsonItem::from_list_item).collect()
+///
+/// Fetches all vars data in a single git call, then distributes per-branch.
+pub fn to_json_items(items: &[ListItem], repo: &Repository) -> Vec<JsonItem> {
+ let mut all_vars = repo.all_vars_entries();
+ items
+ .iter()
+ .map(|item| JsonItem::from_list_item(item, &mut all_vars))
+ .collect()
}
#[cfg(test)]
@@ -848,22 +873,47 @@ mod tests {
"#);
}
+ fn test_repo() -> (tempfile::TempDir, Repository) {
+ let tmp = tempfile::tempdir().unwrap();
+ worktrunk::shell_exec::Cmd::new("git")
+ .args(["init", "-b", "main"])
+ .current_dir(tmp.path())
+ .run()
+ .unwrap();
+ let repo = Repository::at(tmp.path()).unwrap();
+ (tmp, repo)
+ }
+
#[test]
fn test_json_item_summary_present() {
+ let (_tmp, repo) = test_repo();
+ let mut all_vars = repo.all_vars_entries();
+
let mut item = ListItem::new_branch("abc1234".into(), "feature".into());
item.summary = Some(Some("Add login page".to_string()));
- let json_item = JsonItem::from_list_item(&item);
+ let json_item = JsonItem::from_list_item(&item, &mut all_vars);
assert_eq!(json_item.summary, Some("Add login page".to_string()));
}
#[test]
fn test_json_item_summary_absent() {
+ let (_tmp, repo) = test_repo();
+ let mut all_vars = repo.all_vars_entries();
+
let mut item = ListItem::new_branch("abc1234".into(), "feature".into());
// Both "not collected" and "no summary" should be absent in JSON
- assert!(JsonItem::from_list_item(&item).summary.is_none());
+ assert!(
+ JsonItem::from_list_item(&item, &mut all_vars)
+ .summary
+ .is_none()
+ );
item.summary = Some(None);
- assert!(JsonItem::from_list_item(&item).summary.is_none());
+ assert!(
+ JsonItem::from_list_item(&item, &mut all_vars)
+ .summary
+ .is_none()
+ );
}
#[test]
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 452372ddd..ecbe3d004 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -187,7 +187,7 @@ pub fn handle_list(
match format {
crate::OutputFormat::Json => {
// Convert to new JSON structure
- let json_items = json_output::to_json_items(&items);
+ let json_items = json_output::to_json_items(&items, &repo);
let json =
serde_json::to_string_pretty(&json_items).context("Failed to serialize to JSON")?;
println!("{}", json);
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index f8a228386..f38a9f5ab 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -29,7 +29,8 @@ pub(crate) use alias::{AliasOptions, step_alias};
pub(crate) use config::{
handle_config_create, handle_config_show, handle_config_update, handle_hints_clear,
handle_hints_get, handle_logs_get, handle_state_clear, handle_state_clear_all,
- handle_state_get, handle_state_set, handle_state_show,
+ handle_state_get, handle_state_set, handle_state_show, handle_vars_clear, handle_vars_get,
+ handle_vars_list, handle_vars_set,
};
pub(crate) use configure_shell::{
handle_configure_shell, handle_show_theme, handle_unconfigure_shell,
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 4516c3d6e..1b04a5f5b 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -6,6 +6,7 @@
//! This command reuses the data collection infrastructure from `wt list`,
//! avoiding duplication of git operations.
+use std::collections::HashMap;
use std::env;
use std::io::{self, IsTerminal, Read};
use std::path::{Component, Path};
@@ -302,8 +303,15 @@ fn run_json() -> Result<()> {
// Populate computed fields (parallel git operations)
list::populate_item(&repo, &mut item, options)?;
- // Convert to JSON format
- let json_item = json_output::JsonItem::from_list_item(&item);
+ // Convert to JSON format β€” single-branch lookup (not all_vars_entries)
+ let mut all_vars = HashMap::new();
+ if let Some(branch) = &item.branch {
+ let entries = repo.vars_entries(branch);
+ if !entries.is_empty() {
+ all_vars.insert(branch.clone(), entries);
+ }
+ }
+ let json_item = json_output::JsonItem::from_list_item(&item, &mut all_vars);
// Output as JSON array (consistent with wt list --format=json)
let output = serde_json::to_string_pretty(&[json_item])?;
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 57e646ed6..41291ceb5 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -48,6 +48,8 @@ pub const TEMPLATE_VARS: &[&str] = &[
"base", // Added by creation/switch hooks via extra_vars
"base_worktree_path", // Added by creation/switch hooks via extra_vars
"cwd", // Execution directory (always exists on disk)
+ // Note: `vars` is NOT listed here β€” it's a structured object injected by expand_template,
+ // not a simple string that --var can override.
];
/// Deprecated template variable aliases (still valid for backward compatibility).
@@ -354,9 +356,14 @@ pub fn validate_template(
name: &str,
) -> Result<(), TemplateExpandError> {
let all_vars = TEMPLATE_VARS.iter().chain(DEPRECATED_TEMPLATE_VARS.iter());
- let context: HashMap<String, minijinja::Value> = all_vars
+ let mut context: HashMap<String, minijinja::Value> = all_vars
.map(|&k| (k.to_string(), minijinja::Value::from("PLACEHOLDER")))
.collect();
+ // Inject vars as empty map so {{ vars.key | default(...) }} doesn't error
+ context.insert(
+ "vars".to_string(),
+ minijinja::Value::from_serialize(std::collections::BTreeMap::<String, String>::new()),
+ );
let env = setup_template_env(repo);
@@ -413,6 +420,32 @@ pub fn expand_template(
);
}
+ // Inject vars data as a nested object: {{ vars.env }}, {{ vars.config.port }}
+ // When branch is present, always inject (even if empty map) so {{ vars.key | default(...) }}
+ // works in SemiStrict mode. Only look up vars data if the template references it (avoids a
+ // git process spawn per expansion). JSON objects/arrays are parsed so dot access works
+ // ({{ vars.config.port }}); plain strings and numbers stay as-is.
+ //
+ // Use "vars." to avoid false positives from branch names or URLs containing "vars"
+ // (e.g., "envvars.internal"). Template access is always `vars.<key>`.
+ if template.contains("vars.")
+ && let Some(branch) = vars.get("branch")
+ {
+ let entries = repo.vars_entries(branch);
+ let vars_map: std::collections::BTreeMap<String, Value> = entries
+ .into_iter()
+ .map(|(k, v)| {
+ let value = serde_json::from_str::<serde_json::Value>(&v)
+ .ok()
+ .filter(|j| j.is_object() || j.is_array())
+ .map(|j| Value::from_serialize(&j))
+ .unwrap_or_else(|| Value::from(v));
+ (k, value)
+ })
+ .collect();
+ context.insert("vars".to_string(), Value::from_serialize(&vars_map));
+ }
+
let mut env = setup_template_env(repo);
if shell_escape {
// Preserve trailing newlines in templates (important for multiline shell commands)
@@ -1110,6 +1143,200 @@ mod tests {
);
}
+ #[test]
+ fn test_expand_template_vars_data() {
+ let test = test_repo();
+
+ // Set vars data via git config
+ std::process::Command::new("git")
+ .args(["config", "worktrunk.state.main.vars.env", "staging"])
+ .current_dir(test._dir.path())
+ .status()
+ .unwrap();
+ std::process::Command::new("git")
+ .args(["config", "worktrunk.state.main.vars.port", "3000"])
+ .current_dir(test._dir.path())
+ .status()
+ .unwrap();
+
+ let mut vars = HashMap::new();
+ vars.insert("branch", "main");
+
+ // Access vars via dot notation
+ assert_eq!(
+ expand_template("{{ vars.env }}", &vars, false, &test.repo, "test").unwrap(),
+ "staging"
+ );
+ assert_eq!(
+ expand_template("{{ vars.port }}", &vars, false, &test.repo, "test").unwrap(),
+ "3000"
+ );
+
+ // Default filter for missing vars keys
+ assert_eq!(
+ expand_template(
+ "{{ vars.missing | default('fallback') }}",
+ &vars,
+ false,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
+ "fallback"
+ );
+
+ // Conditional on vars
+ assert_eq!(
+ expand_template(
+ "{% if vars.env %}env={{ vars.env }}{% endif %}",
+ &vars,
+ false,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
+ "env=staging"
+ );
+ }
+
+ #[test]
+ fn test_expand_template_vars_json_dot_access() {
+ let test = test_repo();
+
+ // Store a JSON object as a vars value
+ std::process::Command::new("git")
+ .args([
+ "config",
+ "worktrunk.state.main.vars.config",
+ r#"{"port": 3000, "debug": true}"#,
+ ])
+ .current_dir(test._dir.path())
+ .status()
+ .unwrap();
+
+ // Store a JSON array
+ std::process::Command::new("git")
+ .args([
+ "config",
+ "worktrunk.state.main.vars.tags",
+ r#"["alpha", "beta"]"#,
+ ])
+ .current_dir(test._dir.path())
+ .status()
+ .unwrap();
+
+ // Store a plain string (not JSON)
+ std::process::Command::new("git")
+ .args(["config", "worktrunk.state.main.vars.env", "staging"])
+ .current_dir(test._dir.path())
+ .status()
+ .unwrap();
+
+ let mut vars = HashMap::new();
+ vars.insert("branch", "main");
+
+ // Dot access into JSON object
+ assert_eq!(
+ expand_template("{{ vars.config.port }}", &vars, false, &test.repo, "test").unwrap(),
+ "3000"
+ );
+ assert_eq!(
+ expand_template("{{ vars.config.debug }}", &vars, false, &test.repo, "test").unwrap(),
+ "true"
+ );
+
+ // Array index access
+ assert_eq!(
+ expand_template("{{ vars.tags[0] }}", &vars, false, &test.repo, "test").unwrap(),
+ "alpha"
+ );
+
+ // Plain string still works
+ assert_eq!(
+ expand_template("{{ vars.env }}", &vars, false, &test.repo, "test").unwrap(),
+ "staging"
+ );
+
+ // Default filter on missing nested key
+ assert_eq!(
+ expand_template(
+ "{{ vars.config.missing | default('fallback') }}",
+ &vars,
+ false,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
+ "fallback"
+ );
+ }
+
+ #[test]
+ fn test_expand_template_vars_json_shell_escape() {
+ let test = test_repo();
+
+ std::process::Command::new("git")
+ .args([
+ "config",
+ "worktrunk.state.main.vars.config",
+ r#"{"name": "my project", "cmd": "echo hello"}"#,
+ ])
+ .current_dir(test._dir.path())
+ .status()
+ .unwrap();
+
+ let mut vars = HashMap::new();
+ vars.insert("branch", "main");
+
+ // Shell escaping should work on JSON-parsed nested values
+ let result =
+ expand_template("{{ vars.config.name }}", &vars, true, &test.repo, "test").unwrap();
+ assert_eq!(result, "'my project'");
+
+ let result =
+ expand_template("{{ vars.config.cmd }}", &vars, true, &test.repo, "test").unwrap();
+ assert_eq!(result, "'echo hello'");
+ }
+
+ #[test]
+ fn test_expand_template_vars_empty_when_no_branch() {
+ let test = test_repo();
+ let vars = HashMap::new(); // No branch var
+
+ // vars should be undefined (no branch to look up)
+ assert_eq!(
+ expand_template(
+ "{{ vars | default('none') }}",
+ &vars,
+ false,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
+ "none"
+ );
+ }
+
+ #[test]
+ fn test_expand_template_vars_empty_when_no_data() {
+ let test = test_repo();
+ let mut vars = HashMap::new();
+ vars.insert("branch", "main");
+
+ // vars injected as empty map when no entries exist β€” use default filter for missing keys
+ assert_eq!(
+ expand_template(
+ "{{ vars.env | default('dev') }}",
+ &vars,
+ false,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
+ "dev"
+ );
+ }
+
#[test]
fn test_validate_template_valid() {
let test = test_repo();
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 1825cbec4..46d9d20eb 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -58,6 +58,60 @@ impl Repository {
branch.and_then(|branch| self.branch_marker(branch))
}
+ /// Get all vars entries for a branch, sorted by key name.
+ ///
+ /// Returns a `BTreeMap` so it serializes to a minijinja object for template access
+ /// via `{{ vars.key }}`.
+ pub fn vars_entries(&self, branch: &str) -> std::collections::BTreeMap<String, String> {
+ let pattern = format!(r"^worktrunk\.state\.{branch}\.vars\.");
+ let output = self
+ .run_command(&["config", "--get-regexp", &pattern])
+ .unwrap_or_default();
+
+ let prefix = format!("worktrunk.state.{branch}.vars.");
+ output
+ .lines()
+ .filter_map(|line| {
+ let (config_key, value) = line.split_once(' ')?;
+ let key = config_key.strip_prefix(&prefix)?;
+ Some((key.to_string(), value.to_string()))
+ })
+ .collect()
+ }
+
+ /// Get all vars entries across all branches in a single git call.
+ ///
+ /// Returns a map of branch β†’ (key β†’ value). Uses one `git config --get-regexp`
+ /// instead of N per-branch calls, avoiding N+1 subprocess spawns in `wt list --format=json`.
+ pub fn all_vars_entries(
+ &self,
+ ) -> std::collections::HashMap<String, std::collections::BTreeMap<String, String>> {
+ let output = self
+ .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.vars\."])
+ .unwrap_or_default();
+
+ let mut result: std::collections::HashMap<
+ String,
+ std::collections::BTreeMap<String, String>,
+ > = std::collections::HashMap::new();
+ for line in output.lines() {
+ let Some((config_key, value)) = line.split_once(' ') else {
+ continue;
+ };
+ let Some(rest) = config_key.strip_prefix("worktrunk.state.") else {
+ continue;
+ };
+ let Some((branch, key)) = rest.split_once(".vars.") else {
+ continue;
+ };
+ result
+ .entry(branch.to_string())
+ .or_default()
+ .insert(key.to_string(), value.to_string());
+ }
+ result
+ }
+
/// Set the previous branch in worktrunk.history for `wt switch -` support.
///
/// Stores the branch we're switching FROM, so `wt switch -` can return to it.
diff --git a/src/main.rs b/src/main.rs
index 3d4eff87b..1d4ab569d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -52,15 +52,16 @@ use commands::{
handle_hook_show, handle_init, handle_list, handle_logs_get, handle_merge, handle_promote,
handle_rebase, handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all,
handle_state_get, handle_state_set, handle_state_show, handle_switch, handle_unconfigure_shell,
- resolve_worktree_arg, run_hook, step_commit, step_copy_ignored, step_diff, step_eval,
- step_for_each, step_prune, step_relocate,
+ handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set, resolve_worktree_arg,
+ run_hook, step_commit, step_copy_ignored, step_diff, step_eval, step_for_each, step_prune,
+ step_relocate,
};
use output::handle_remove_output;
use cli::{
ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigCommand, ConfigShellCommand,
DefaultBranchAction, HintsAction, HookCommand, ListSubcommand, LogsAction, MarkerAction,
- PreviousBranchAction, StateCommand, StepCommand,
+ PreviousBranchAction, StateCommand, StepCommand, VarsAction,
};
use worktrunk::HookType;
@@ -389,6 +390,17 @@ fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {
Some(HintsAction::Get) | None => handle_hints_get(),
Some(HintsAction::Clear { name }) => handle_hints_clear(name),
},
+ StateCommand::Vars { action } => match action {
+ VarsAction::Get { key, branch } => handle_vars_get(&key, branch),
+ VarsAction::Set {
+ assignment: (key, value),
+ branch,
+ } => handle_vars_set(&key, &value, branch),
+ VarsAction::List { branch } => handle_vars_list(branch),
+ VarsAction::Clear { key, all, branch } => {
+ handle_vars_clear(key.as_deref(), all, branch)
+ }
+ },
StateCommand::Get { format } => handle_state_show(format),
StateCommand::Clear => handle_state_clear_all(),
}
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index b90d8eab9..a1b5c9c24 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -621,6 +621,12 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {
r#"{"checked_at":1704067200,"head":"abc123","branch":"feature"}"#,
);
+ // Vars data
+ repo.git_command()
+ .args(["config", "worktrunk.state.main.vars.env", "staging"])
+ .run()
+ .unwrap();
+
// Logs
let git_dir = repo.root_path().join(".git");
let log_dir = git_dir.join("wt/logs");
@@ -650,6 +656,16 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {
.code()
== Some(1)
);
+ assert!(
+ repo.git_command()
+ .args(["config", "--get", "worktrunk.state.main.vars.env"])
+ .run()
+ .unwrap()
+ .status
+ .code()
+ == Some(1),
+ "Vars data should be cleared"
+ );
// CI cache is now file-based, verify the cache file is cleared
let ci_cache_dir = git_dir.join("wt").join("cache").join("ci-status");
assert!(
@@ -689,6 +705,9 @@ fn test_state_get_empty(repo: TestRepo) {
BRANCH MARKERS
  (none)
+ VARS
+   (none)
+
CI STATUS CACHE
  (none)
@@ -764,6 +783,16 @@ fn test_state_get_comprehensive(repo: TestRepo) {
.run()
.unwrap();
+ // Set up vars data
+ repo.git_command()
+ .args(["config", "worktrunk.state.main.vars.env", "staging"])
+ .run()
+ .unwrap();
+ repo.git_command()
+ .args(["config", "worktrunk.state.feature.vars.port", "3000"])
+ .run()
+ .unwrap();
+
// Set up CI cache (file-based)
write_ci_cache(
&repo,
@@ -822,6 +851,12 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {
.run()
.unwrap();
+ // Set up vars data
+ repo.git_command()
+ .args(["config", "worktrunk.state.main.vars.env", "staging"])
+ .run()
+ .unwrap();
+
// Set up CI cache (file-based)
write_ci_cache(
&repo,
@@ -847,6 +882,13 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {
assert_eq!(markers[0]["marker"], "🚧 WIP");
assert_eq!(markers[0]["set_at"], TEST_EPOCH);
+ // Check vars data
+ let vars = json["vars"].as_array().unwrap();
+ assert_eq!(vars.len(), 1);
+ assert_eq!(vars[0]["branch"], "main");
+ assert_eq!(vars[0]["key"], "env");
+ assert_eq!(vars[0]["value"], "staging");
+
// Check CI status
let ci_status = json["ci_status"].as_array().unwrap();
assert_eq!(ci_status.len(), 1);
@@ -1390,3 +1432,345 @@ fn test_state_logs_get_hook_invalid_hook_type(repo: TestRepo) {
stderr
);
}
+
+// ============================================================================
+// vars
+// ============================================================================
+
+#[rstest]
+fn test_vars_set_and_get(repo: TestRepo) {
+ // Set a value
+ let output = wt_state_cmd(&repo, "vars", "set", &["env=staging"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("Set"), "Expected success message: {stderr}");
+
+ // Get the value
+ let output = wt_state_cmd(&repo, "vars", "get", &["env"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "staging");
+}
+
+#[rstest]
+fn test_vars_set_json_value(repo: TestRepo) {
+ let json = r#"{"port":3000,"debug":true}"#;
+ let output = wt_state_cmd(&repo, "vars", "set", &[&format!("config={json}")])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let output = wt_state_cmd(&repo, "vars", "get", &["config"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), json);
+}
+
+#[rstest]
+fn test_vars_get_missing_key(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "vars", "get", &["nonexistent"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ // Empty output for missing keys
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "");
+}
+
+#[rstest]
+fn test_vars_list(repo: TestRepo) {
+ // Set multiple values
+ wt_state_cmd(&repo, "vars", "set", &["env=staging"])
+ .output()
+ .unwrap();
+ wt_state_cmd(&repo, "vars", "set", &["port=3000"])
+ .output()
+ .unwrap();
+
+ let output = wt_state_cmd(&repo, "vars", "list", &[]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("env\tstaging"),
+ "Expected env key: {stdout}"
+ );
+ assert!(stdout.contains("port\t3000"), "Expected port key: {stdout}");
+}
+
+#[rstest]
+fn test_vars_list_empty(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "vars", "list", &[]).output().unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("No variables"),
+ "Expected empty message: {stderr}"
+ );
+}
+
+#[rstest]
+fn test_vars_clear_single_key(repo: TestRepo) {
+ // Set and clear
+ wt_state_cmd(&repo, "vars", "set", &["env=staging"])
+ .output()
+ .unwrap();
+ let output = wt_state_cmd(&repo, "vars", "clear", &["env"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Cleared"),
+ "Expected clear message: {stderr}"
+ );
+
+ // Verify it's gone
+ let output = wt_state_cmd(&repo, "vars", "get", &["env"])
+ .output()
+ .unwrap();
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "");
+}
+
+#[rstest]
+fn test_vars_clear_all(repo: TestRepo) {
+ // Set multiple values
+ wt_state_cmd(&repo, "vars", "set", &["env=staging"])
+ .output()
+ .unwrap();
+ wt_state_cmd(&repo, "vars", "set", &["port=3000"])
+ .output()
+ .unwrap();
+
+ let output = wt_state_cmd(&repo, "vars", "clear", &["--all"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Cleared") && stderr.contains("2"),
+ "Expected clear 2 entries: {stderr}"
+ );
+
+ // Verify all gone
+ let output = wt_state_cmd(&repo, "vars", "list", &[]).output().unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("No variables"));
+}
+
+#[rstest]
+fn test_vars_invalid_key(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "vars", "set", &["foo.bar=value"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Invalid key"),
+ "Expected invalid key error: {stderr}"
+ );
+}
+
+#[rstest]
+fn test_vars_branch_flag(repo: TestRepo) {
+ // Create a branch
+ repo.run_git(&["branch", "feature"]);
+
+ // Set vars on a different branch
+ let output = wt_state_cmd(
+ &repo,
+ "vars",
+ "set",
+ &["env=production", "--branch=feature"],
+ )
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ // Get from that branch
+ let output = wt_state_cmd(&repo, "vars", "get", &["env", "--branch=feature"])
+ .output()
+ .unwrap();
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "production");
+
+ // Current branch should not have the value
+ let output = wt_state_cmd(&repo, "vars", "get", &["env"])
+ .output()
+ .unwrap();
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "");
+}
+
+#[rstest]
+fn test_vars_value_with_spaces(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "vars", "set", &["note=hello world foo"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let output = wt_state_cmd(&repo, "vars", "get", &["note"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_eq!(
+ String::from_utf8_lossy(&output.stdout).trim(),
+ "hello world foo"
+ );
+}
+
+#[rstest]
+fn test_vars_value_containing_equals(repo: TestRepo) {
+ let url = "postgres://user:pass@host/db?sslmode=require";
+ let output = wt_state_cmd(&repo, "vars", "set", &[&format!("db-url={url}")])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let output = wt_state_cmd(&repo, "vars", "get", &["db-url"])
+ .output()
+ .unwrap();
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), url);
+}
+
+#[rstest]
+fn test_vars_empty_value(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "vars", "set", &["key="])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let output = wt_state_cmd(&repo, "vars", "get", &["key"])
+ .output()
+ .unwrap();
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "");
+}
+
+#[rstest]
+fn test_vars_overwrite(repo: TestRepo) {
+ wt_state_cmd(&repo, "vars", "set", &["env=staging"])
+ .output()
+ .unwrap();
+ wt_state_cmd(&repo, "vars", "set", &["env=production"])
+ .output()
+ .unwrap();
+
+ let output = wt_state_cmd(&repo, "vars", "get", &["env"])
+ .output()
+ .unwrap();
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "production");
+}
+
+#[rstest]
+fn test_vars_in_json_output(repo: TestRepo) {
+ // Set vars data
+ repo.git_command()
+ .args(["config", "worktrunk.state.main.vars.env", "staging"])
+ .run()
+ .unwrap();
+ repo.git_command()
+ .args(["config", "worktrunk.state.main.vars.port", "3000"])
+ .run()
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let items = json.as_array().unwrap();
+ assert!(!items.is_empty());
+
+ let main_item = &items[0];
+ assert_eq!(main_item["vars"]["env"], "staging");
+ assert_eq!(main_item["vars"]["port"], "3000");
+}
+
+#[rstest]
+fn test_vars_absent_in_json_when_empty(repo: TestRepo) {
+ // No vars data set β€” vars field should be absent from JSON
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
+ let items = json.as_array().unwrap();
+ assert!(!items.is_empty());
+
+ // vars should not be present when empty (skip_serializing_if)
+ assert!(items[0].get("vars").is_none());
+}
+
+#[rstest]
+fn test_vars_clear_nonexistent_key(repo: TestRepo) {
+ // Clear a key that was never set
+ let output = wt_state_cmd(&repo, "vars", "clear", &["nonexistent"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("No variable"),
+ "Expected 'No variable' message: {stderr}"
+ );
+}
+
+#[rstest]
+fn test_vars_clear_all_empty(repo: TestRepo) {
+ // Clear --all when no vars data exists
+ let output = wt_state_cmd(&repo, "vars", "clear", &["--all"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("No variables"),
+ "Expected 'No variables' message: {stderr}"
+ );
+}
+
+#[rstest]
+fn test_vars_list_with_branch_flag(repo: TestRepo) {
+ // Create a branch and set vars data
+ repo.run_git(&["branch", "feature"]);
+ repo.git_command()
+ .args(["config", "worktrunk.state.feature.vars.env", "production"])
+ .run()
+ .unwrap();
+
+ // List vars for specific branch
+ let output = wt_state_cmd(&repo, "vars", "list", &["--branch=feature"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("env\tproduction"),
+ "Expected vars entry: {stdout}"
+ );
+}
+
+#[rstest]
+fn test_vars_clear_with_branch_flag(repo: TestRepo) {
+ // Create a branch and set vars data
+ repo.run_git(&["branch", "feature"]);
+ repo.git_command()
+ .args(["config", "worktrunk.state.feature.vars.env", "production"])
+ .run()
+ .unwrap();
+
+ // Clear vars for specific branch
+ let output = wt_state_cmd(&repo, "vars", "clear", &["env", "--branch=feature"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Cleared"),
+ "Expected clear message: {stderr}"
+ );
+}
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 b58181ebd..59fbd0733 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
@@ -14,6 +14,12 @@ expression: "String::from_utf8_lossy(&output.stderr)"
bugfix πŸ› debugging now
feature 🚧 WIP now
+VARS
+ Branch Key Value
+ ─────── ──── ───────
+ feature port 3000
+ main env staging
+
CI STATUS CACHE
Branch Status Age Head
─────── ────── ─── ────────
diff --git a/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap b/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap
index 523e339a5..5c7142db5 100644
--- a/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap
+++ b/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap
@@ -11,6 +11,9 @@ expression: "String::from_utf8_lossy(&output.stderr)"
BRANCH MARKERS
  (none)
+VARS
+  (none)
+
CI STATUS CACHE
Branch Status Age Head
─────── ────── ─── ────────
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state.snap b/tests/snapshots/integration__integration_tests__help__help_config_state.snap
index d6e95019e..5b482383e 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state.snap
@@ -43,6 +43,7 @@ Usage: wt config state [OPTIONS] <COMMAND>
marker Branch markers
logs Background operation logs
hints One-time hints shown in this repo
+ vars [experimental] Custom variables per branch
get Get all stored state
clear Clear all stored state
@@ -69,6 +70,7 @@ Use wt config show to view file-based configuration.
- previous-branch: Previous branch for wt switch -
- ci-status: CI/PR status for a branch (passed, running, failed, conflicts, no-ci, error)
- marker: Custom status marker for a branch (shown in wt list)
+- vars: [experimental] Custom variables per branch
- logs: Background operation logs
Examples
@@ -82,6 +84,9 @@ Set the default branch manually:
Set a marker for current branch:
  $ wt config state marker set "🚧 WIP"
+Store arbitrary data:
+  $ wt config state vars set env=staging
+
Clear all CI status cache:
  $ wt config state ci-status clear --all
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap
index cbb971e1c..8a9fd0add 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap
@@ -13,14 +13,18 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
+ NO_COLOR: ""
PSModulePath: ""
RUST_LOG: warn
SHELL: ""
TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: /nonexistent/test/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
+ WORKTRUNK_SYSTEM_CONFIG_PATH: /etc/xdg/worktrunk/config.toml
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -52,6 +56,7 @@ Clears all stored state:
- Default branch cache
- Previous branch
- All branch markers
+- All variables
- All CI status cache
- All hints
- All log files
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap
index 7d7d46397..52bb6bf07 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap
@@ -13,14 +13,18 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
+ NO_COLOR: ""
PSModulePath: ""
RUST_LOG: warn
SHELL: ""
TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: /nonexistent/test/approvals.toml
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
+ WORKTRUNK_SYSTEM_CONFIG_PATH: /etc/xdg/worktrunk/config.toml
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
---
@@ -57,6 +61,7 @@ Shows all stored state including:
- Default branch: Cached result of querying remote for default branch
- Previous branch: Previous branch for wt switch -
- Branch markers: User-defined branch notes
+- Vars: Custom variables per branch
- CI status: Cached GitHub/GitLab CI status per branch (30s TTL)
- Hints: One-time hints that have been shown
- Log files: Background operation logs
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
index d8fae130c..b22637566 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
@@ -233,6 +233,7 @@ Query structured data with --format=json:
summary string LLM-generated branch summary; absent when not configured or no summary
statusline string Pre-formatted status with ANSI colors
symbols string Raw status symbols without colors (e.g., "!?↓")
+ vars object Per-branch variables from wt config state vars (absent when empty)
Commit object
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index 18cd65903..07f30ccd6 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -265,6 +265,8 @@ Query structured data with --format=json:
configured or no summary
statusline string Pre-formatted status with ANSI colors
symbols string Raw status symbols without colors (e.g., "!?↓")
+ vars object Per-branch variables from wt config state vars
+ (absent when empty)
Commit object