Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add per-project hooks with append semantics (#842)
Maximilian Roos79fe892bfa93
diff --git a/.claude-plugin/skills/worktrunk/reference/config.md b/.claude-plugin/skills/worktrunk/reference/config.mdindex 49c9a24f4..7fe68d529 100644--- a/.claude-plugin/skills/worktrunk/reference/config.md+++ b/.claude-plugin/skills/worktrunk/reference/config.md@@ -176,13 +176,14 @@ To reset, delete the entry or run `wt hook approvals clear`.#### Setting overrides (Experimental)-Override global settings for a specific project. Useful when one repo needs a different worktree layout or merge behavior.+Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run.```toml[projects."github.com/user/repo"]worktree-path = ".worktrees/{{ branch | sanitize }}"list.full = truemerge.squash = false+post-create.env = "cp .env.example .env"```### Custom prompt templatesdiff --git a/.claude-plugin/skills/worktrunk/reference/hook.md b/.claude-plugin/skills/worktrunk/reference/hook.mdindex 3d4f1d30b..4d74c45e0 100644--- a/.claude-plugin/skills/worktrunk/reference/hook.md+++ b/.claude-plugin/skills/worktrunk/reference/hook.md@@ -140,7 +140,7 @@ build = "cargo build --release"### User hooks-Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval.+Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval. For repository-specific user hooks, see [setting overrides](https://worktrunk.dev/config/#setting-overrides-experimental).```toml# ~/.config/worktrunk/config.toml@@ -158,9 +158,9 @@ User hooks support the same hook types and template variables as project hooks.| Aspect | Project hooks | User hooks ||--------|--------------|------------|| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |-| Scope | Single repository | All repositories |+| Scope | Single repository | All repositories (or per-project) || Approval | Required | Not required |-| Execution order | After user hooks | Before project hooks |+| Execution order | After user hooks | Global first, then per-project |Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.@@ -168,24 +168,6 @@ Skip hooks with `--no-verify`. To run a specific hook when user and project both- Personal notifications or logging- Editor/IDE integration- Repository-agnostic setup tasks-- Filtering by repository using JSON context--**Filtering by repository:**--User hooks receive JSON context on stdin, enabling repository-specific behavior:--```toml-# ~/.config/worktrunk/config.toml-[post-create]-gitlab-setup = """-python3 -c '-import json, sys, subprocess-ctx = json.load(sys.stdin)-if "gitlab" in ctx.get("remote", ""):- subprocess.run(["glab", "mr", "create", "--fill"])-'-"""-```### Template variables@@ -259,12 +241,14 @@ setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path### JSON context-Hooks also receive context as JSON on stdin, enabling hooks in any language:+Hooks receive context as JSON on stdin, enabling complex logic that templates can't express:```python-import json, sys+import json, sys, subprocessctx = json.load(sys.stdin)-print(f"Setting up {ctx['repo']} on branch {ctx['branch']}")+# Run extra setup for feature branches on backend repos+if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+ subprocess.run(['make', 'seed-db'])```The JSON includes all template variables plus `hook_type` and `hook_name`.diff --git a/Cargo.lock b/Cargo.lockindex e3831e695..34769b6e4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -231,9 +231,9 @@ dependencies = [[[package]]name = "bumpalo"-version = "3.19.0"+version = "3.19.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"+checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"[[package]]name = "cast"@@ -243,9 +243,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"[[package]]name = "cc"-version = "1.2.47"+version = "1.2.54"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cd405d82c84ff7f35739f175f67d8b9fb7687a0e84ccdc78bd3568839827cf07"+checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583"dependencies = ["find-msvc-tools","shlex",@@ -366,9 +366,9 @@ dependencies = [[[package]]name = "clap_lex"-version = "0.7.6"+version = "0.7.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"+checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32"[[package]]name = "color-print"@@ -436,9 +436,9 @@ dependencies = [[[package]]name = "convert_case"-version = "0.7.1"+version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bb402b8d4c85569410425650ce3eddc7d698ed96d39a73f941b08fb63082f1e7"+checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"dependencies = ["unicode-segmentation",]@@ -728,22 +728,23 @@ dependencies = [[[package]]name = "derive_more"-version = "2.0.1"+version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678"+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"dependencies = ["derive_more-impl",][[package]]name = "derive_more-impl"-version = "2.0.1"+version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3"+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"dependencies = [- "convert_case 0.7.1",+ "convert_case 0.10.0","proc-macro2","quote",+ "rustc_version","syn",]@@ -820,6 +821,12 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"+[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]name = "east-asian-width"version = "0.1.0"@@ -912,9 +919,9 @@ dependencies = [[[package]]name = "find-msvc-tools"-version = "0.1.5"+version = "0.1.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844"+checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"[[package]]name = "fnv"@@ -996,9 +1003,9 @@ dependencies = [[[package]]name = "getrandom"-version = "0.2.16"+version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"dependencies = ["cfg-if","libc",@@ -1191,15 +1198,15 @@ dependencies = [[[package]]name = "itoa"-version = "1.0.15"+version = "1.0.17"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"[[package]]name = "jiff"-version = "0.2.16"+version = "0.2.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "49cce2b81f2098e7e3efc35bc2e0a6b7abec9d34128283d7a26fa8f32a6dbb35"+checksum = "e67e8da4c49d6d9909fe03361f9b620f58898859f5c7aded68351e85e71ecf50"dependencies = ["jiff-static","log",@@ -1210,9 +1217,9 @@ dependencies = [[[package]]name = "jiff-static"-version = "0.2.16"+version = "0.2.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69"+checksum = "e0c84ee7f197eca9a86c6fd6cb771e55eb991632f15f2bc3ca6ec838929e6e78"dependencies = ["proc-macro2","quote",@@ -1221,9 +1228,9 @@ dependencies = [[[package]]name = "js-sys"-version = "0.3.82"+version = "0.3.85"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65"+checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"dependencies = ["once_cell","wasm-bindgen",@@ -1231,9 +1238,9 @@ dependencies = [[[package]]name = "lazy-regex"-version = "3.4.2"+version = "3.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "191898e17ddee19e60bccb3945aa02339e81edd4a8c50e21fd4d48cdecda7b29"+checksum = "c5c13b6857ade4c8ee05c3c3dc97d2ab5415d691213825b90d3211c425c1f907"dependencies = ["lazy-regex-proc_macros","once_cell",@@ -1242,9 +1249,9 @@ dependencies = [[[package]]name = "lazy-regex-proc_macros"-version = "3.4.2"+version = "3.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c35dc8b0da83d1a9507e12122c80dea71a9c7c613014347392483a83ea593e04"+checksum = "32a95c68db5d41694cea563c86a4ba4dc02141c16ef64814108cb23def4d5438"dependencies = ["proc-macro2","quote",@@ -1260,15 +1267,15 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"[[package]]name = "libc"-version = "0.2.177"+version = "0.2.180"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976"+checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"[[package]]name = "libredox"-version = "0.1.10"+version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb"+checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616"dependencies = ["bitflags 2.10.0","libc",@@ -1333,9 +1340,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"[[package]]name = "mio"-version = "1.1.0"+version = "1.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873"+checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"dependencies = ["libc","log",@@ -1411,9 +1418,9 @@ checksum = "f5438dd2b2ff4c6df6e1ce22d825ed2fa93ee2922235cc45186991717f0a892d"[[package]]name = "num-conv"-version = "0.1.0"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"+checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"[[package]]name = "num-traits"@@ -1516,9 +1523,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"[[package]]name = "pest"-version = "2.8.4"+version = "2.8.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cbcfd20a6d4eeba40179f05735784ad32bdaef05ce8e8af05f180d45bb3e7e22"+checksum = "2c9eb05c21a464ea704b53158d358a31e6425db2f63a1a7312268b05fe2b75f7"dependencies = ["memchr","ucd-trie",@@ -1526,9 +1533,9 @@ dependencies = [[[package]]name = "pest_derive"-version = "2.8.4"+version = "2.8.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "51f72981ade67b1ca6adc26ec221be9f463f2b5839c7508998daa17c23d94d7f"+checksum = "68f9dbced329c441fa79d80472764b1a2c7e57123553b8519b36663a2fb234ed"dependencies = ["pest","pest_generator",@@ -1536,9 +1543,9 @@ dependencies = [[[package]]name = "pest_generator"-version = "2.8.4"+version = "2.8.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dee9efd8cdb50d719a80088b76f81aec7c41ed6d522ee750178f83883d271625"+checksum = "3bb96d5051a78f44f43c8f712d8e810adb0ebf923fc9ed2655a7f66f63ba8ee5"dependencies = ["pest","pest_meta",@@ -1549,9 +1556,9 @@ dependencies = [[[package]]name = "pest_meta"-version = "2.8.4"+version = "2.8.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bf1d70880e76bdc13ba52eafa6239ce793d85c8e43896507e43dd8984ff05b82"+checksum = "602113b5b5e8621770cfd490cfd90b9f84ab29bd2b0e49ad83eb6d186cef2365"dependencies = ["pest","sha2",@@ -1599,9 +1606,9 @@ dependencies = [[[package]]name = "portable-atomic"-version = "1.11.1"+version = "1.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"+checksum = "f89776e4d69bb58bc6993e99ffa1d11f228b839984854c7daeb5d37f87cbe950"[[package]]name = "portable-atomic-util"@@ -1659,9 +1666,9 @@ dependencies = [[[package]]name = "proc-macro2"-version = "1.0.103"+version = "1.0.106"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"dependencies = ["unicode-ident",]@@ -1679,9 +1686,9 @@ dependencies = [[[package]]name = "quote"-version = "1.0.42"+version = "1.0.44"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f"+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"dependencies = ["proc-macro2",]@@ -1714,9 +1721,9 @@ dependencies = [[[package]]name = "rand_core"-version = "0.9.3"+version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"dependencies = ["getrandom 0.3.4",]@@ -1756,7 +1763,7 @@ version = "0.4.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"dependencies = [- "getrandom 0.2.16",+ "getrandom 0.2.17","libredox","thiserror 1.0.69",]@@ -1767,9 +1774,29 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"dependencies = [- "getrandom 0.2.16",+ "getrandom 0.2.17","libredox",- "thiserror 2.0.17",+ "thiserror 2.0.18",+]++[[package]]+name = "ref-cast"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",][[package]]@@ -1915,6 +1942,31 @@ dependencies = ["regex",]+[[package]]+name = "schemars"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "54e910108742c57a770f492731f99be216a52fadd361b06c8fb59d74ccc267d2"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "schemars_derive",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4908ad288c5035a8eb12cfdf0d49270def0a268ee162b75eeee0f85d155a7c45"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn",+]+[[package]]name = "scopeguard"version = "1.2.0"@@ -1957,6 +2009,17 @@ dependencies = ["syn",]+[[package]]+name = "serde_derive_internals"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "serde_json"version = "1.0.149"@@ -2029,9 +2092,9 @@ dependencies = [[[package]]name = "shell-words"-version = "1.1.0"+version = "1.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"+checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"[[package]]name = "shellexpand"@@ -2060,9 +2123,9 @@ dependencies = [[[package]]name = "signal-hook"-version = "0.4.1"+version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2a37d01603c37b5466f808de79f845c7116049b0579adb70a6b7d47c1fa3a952"+checksum = "3b57709da74f9ff9f4a27dce9526eec25ca8407c45a7887243b031a58935fb8e"dependencies = ["libc","signal-hook-registry",@@ -2081,10 +2144,11 @@ dependencies = [[[package]]name = "signal-hook-registry"-version = "1.4.7"+version = "1.4.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7664a098b8e616bdfcc2dc0e9ac44eb231eedf41db4e9fe95d8d32ec728dedad"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"dependencies = [+ "errno","libc",]@@ -2228,9 +2292,9 @@ checksum = "e396b6523b11ccb83120b115a0b7366de372751aa6edf19844dfb13a6af97e91"[[package]]name = "syn"-version = "2.0.111"+version = "2.0.114"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87"+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"dependencies = ["proc-macro2","quote",@@ -2286,7 +2350,7 @@ dependencies = ["lazy-regex","minimad","serde",- "thiserror 2.0.17",+ "thiserror 2.0.18","unicode-width 0.1.14",]@@ -2311,11 +2375,11 @@ dependencies = [[[package]]name = "thiserror"-version = "2.0.17"+version = "2.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"dependencies = [- "thiserror-impl 2.0.17",+ "thiserror-impl 2.0.18",][[package]]@@ -2331,9 +2395,9 @@ dependencies = [[[package]]name = "thiserror-impl"-version = "2.0.17"+version = "2.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"dependencies = ["proc-macro2","quote",@@ -2351,9 +2415,9 @@ dependencies = [[[package]]name = "time"-version = "0.3.45"+version = "0.3.46"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd"+checksum = "9da98b7d9b7dad93488a84b8248efc35352b0b2657397d4167e7ad67e5d535e5"dependencies = ["deranged","itoa",@@ -2368,15 +2432,15 @@ dependencies = [[[package]]name = "time-core"-version = "0.1.7"+version = "0.1.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca"+checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"[[package]]name = "time-macros"-version = "0.2.25"+version = "0.2.26"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd"+checksum = "78cc610bac2dcee56805c99642447d4c5dbde4d01f752ffea0199aee1f601dc4"dependencies = ["num-conv","time-core",@@ -2499,15 +2563,15 @@ checksum = "adc5f880ad8d8f94e88cb81c3557024cf1a8b75e3b504c50481ed4f5a6006ff3"dependencies = ["regex","streaming-iterator",- "thiserror 2.0.17",+ "thiserror 2.0.18","tree-sitter",][[package]]name = "tree-sitter-language"-version = "0.1.5"+version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c4013970217383f67b18aef68f6fb2e8d409bc5755227092d32efb0422ba24b8"+checksum = "4ae62f7eae5eb549c71b76658648b72cc6111f2d87d24a1e31fa907f4943e3ce"[[package]]name = "typeid"@@ -2529,9 +2593,9 @@ checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"[[package]]name = "unicase"-version = "2.8.1"+version = "2.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539"+checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"[[package]]name = "unicode-ident"@@ -2662,18 +2726,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"[[package]]name = "wasip2"-version = "1.0.1+wasi-0.2.4"+version = "1.0.2+wasi-0.2.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"dependencies = ["wit-bindgen",][[package]]name = "wasm-bindgen"-version = "0.2.105"+version = "0.2.108"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60"+checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"dependencies = ["cfg-if","once_cell",@@ -2684,9 +2748,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro"-version = "0.2.105"+version = "0.2.108"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2"+checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"dependencies = ["quote","wasm-bindgen-macro-support",@@ -2694,9 +2758,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro-support"-version = "0.2.105"+version = "0.2.108"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc"+checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"dependencies = ["bumpalo","proc-macro2",@@ -2707,18 +2771,18 @@ dependencies = [[[package]]name = "wasm-bindgen-shared"-version = "0.2.105"+version = "0.2.108"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76"+checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"dependencies = ["unicode-ident",][[package]]name = "web-sys"-version = "0.3.82"+version = "0.3.85"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1"+checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"dependencies = ["js-sys","wasm-bindgen",@@ -3046,9 +3110,9 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"[[package]]name = "winnow"-version = "0.7.13"+version = "0.7.14"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf"+checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"dependencies = ["memchr",]@@ -3070,9 +3134,9 @@ checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"[[package]]name = "wit-bindgen"-version = "0.46.0"+version = "0.51.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"[[package]]name = "worktrunk"@@ -3117,12 +3181,13 @@ dependencies = ["regex","rstest","sanitize-filename",+ "schemars","serde","serde_json","shell-escape","shellexpand","shlex",- "signal-hook 0.4.1",+ "signal-hook 0.4.3","similar","skim","strum",@@ -3154,7 +3219,7 @@ dependencies = ["ansi-escape-sequences","regex","string-width",- "thiserror 2.0.17",+ "thiserror 2.0.18",][[package]]@@ -3169,18 +3234,18 @@ dependencies = [[[package]]name = "zerocopy"-version = "0.8.28"+version = "0.8.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "43fa6694ed34d6e57407afbccdeecfa268c470a7d2a5b0cf49ce9fcc345afb90"+checksum = "668f5168d10b9ee831de31933dc111a459c97ec93225beb307aed970d1372dfd"dependencies = ["zerocopy-derive",][[package]]name = "zerocopy-derive"-version = "0.8.28"+version = "0.8.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c640b22cd9817fae95be82f0d2f90b11f7605f6c319d16705c459b27ac2cbc26"+checksum = "2c7962b26b0a8685668b671ee4b54d007a67d4eaf05fda79ac0ecf41e32270f1"dependencies = ["proc-macro2","quote",@@ -3189,6 +3254,6 @@ dependencies = [[[package]]name = "zmij"-version = "1.0.2"+version = "1.0.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0f4a4e8e9dc5c62d159f04fcdbe07f4c3fb710415aab4754bf11505501e3251d"+checksum = "dfcd145825aace48cff44a8844de64bf75feec3080e0aa5cdbde72961ae51a65"diff --git a/Cargo.toml b/Cargo.tomlindex 054a82f04..8572c0e3e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -120,6 +120,7 @@ reflink-copy = "0.1"dashmap = "6.1.0"fs2 = "0.4.3"sanitize-filename = "0.6.0"+schemars = { version = "1.2.0", features = ["derive"] }[target.'cfg(unix)'.dependencies]skim = "0.20"diff --git a/dev/config.example.toml b/dev/config.example.tomlindex ac6b30e6c..ca9cb9c99 100644--- a/dev/config.example.toml+++ b/dev/config.example.toml@@ -102,12 +102,13 @@## #### Setting overrides (Experimental)#-# Override global settings for a specific project. Useful when one repo needs a different worktree layout or merge behavior.+# Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run.## [projects."github.com/user/repo"]# worktree-path = ".worktrees/{{ branch | sanitize }}"# list.full = true# merge.squash = false+# post-create.env = "cp .env.example .env"## ### Custom prompt templates#diff --git a/docs/content/config.md b/docs/content/config.mdindex d3422c562..2554ab16f 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -184,13 +184,14 @@ To reset, delete the entry or run `wt hook approvals clear`.#### Setting overrides (Experimental)-Override global settings for a specific project. Useful when one repo needs a different worktree layout or merge behavior.+Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run.```toml[projects."github.com/user/repo"]worktree-path = ".worktrees/{{ branch | sanitize }}"list.full = truemerge.squash = false+post-create.env = "cp .env.example .env"```### Custom prompt templatesdiff --git a/docs/content/hook.md b/docs/content/hook.mdindex d8492269c..bf9eec0ba 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -148,7 +148,7 @@ build = "cargo build --release"### User hooks-Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval.+Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval. For repository-specific user hooks, see [setting overrides](@/config.md#setting-overrides-experimental).```toml# ~/.config/worktrunk/config.toml@@ -166,9 +166,9 @@ User hooks support the same hook types and template variables as project hooks.| Aspect | Project hooks | User hooks ||--------|--------------|------------|| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |-| Scope | Single repository | All repositories |+| Scope | Single repository | All repositories (or per-project) || Approval | Required | Not required |-| Execution order | After user hooks | Before project hooks |+| Execution order | After user hooks | Global first, then per-project |Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.@@ -176,24 +176,6 @@ Skip hooks with `--no-verify`. To run a specific hook when user and project both- Personal notifications or logging- Editor/IDE integration- Repository-agnostic setup tasks-- Filtering by repository using JSON context--**Filtering by repository:**--User hooks receive JSON context on stdin, enabling repository-specific behavior:--```toml-# ~/.config/worktrunk/config.toml-[post-create]-gitlab-setup = """-python3 -c '-import json, sys, subprocess-ctx = json.load(sys.stdin)-if "gitlab" in ctx.get("remote", ""):- subprocess.run(["glab", "mr", "create", "--fill"])-'-"""-```### Template variables@@ -267,12 +249,14 @@ setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path### JSON context-Hooks also receive context as JSON on stdin, enabling hooks in any language:+Hooks receive context as JSON on stdin, enabling complex logic that templates can't express:```python-import json, sys+import json, sys, subprocessctx = json.load(sys.stdin)-print(f"Setting up {ctx['repo']} on branch {ctx['branch']}")+# Run extra setup for feature branches on backend repos+if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+ subprocess.run(['make', 'seed-db'])```The JSON includes all template variables plus `hook_type` and `hook_name`.diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 48e6b9406..0a5690fa2 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1174,7 +1174,7 @@ build = "cargo build --release"### User hooks-Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval.+Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval. For repository-specific user hooks, see [setting overrides](@/config.md#setting-overrides-experimental).```toml# ~/.config/worktrunk/config.toml@@ -1192,9 +1192,9 @@ User hooks support the same hook types and template variables as project hooks.| Aspect | Project hooks | User hooks ||--------|--------------|------------|| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |-| Scope | Single repository | All repositories |+| Scope | Single repository | All repositories (or per-project) || Approval | Required | Not required |-| Execution order | After user hooks | Before project hooks |+| Execution order | After user hooks | Global first, then per-project |Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.@@ -1202,24 +1202,6 @@ Skip hooks with `--no-verify`. To run a specific hook when user and project both- Personal notifications or logging- Editor/IDE integration- Repository-agnostic setup tasks-- Filtering by repository using JSON context--**Filtering by repository:**--User hooks receive JSON context on stdin, enabling repository-specific behavior:--```toml-# ~/.config/worktrunk/config.toml-[post-create]-gitlab-setup = """-python3 -c '-import json, sys, subprocess-ctx = json.load(sys.stdin)-if "gitlab" in ctx.get("remote", ""):- subprocess.run(["glab", "mr", "create", "--fill"])-'-"""-```### Template variables@@ -1293,12 +1275,14 @@ setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path### JSON context-Hooks also receive context as JSON on stdin, enabling hooks in any language:+Hooks receive context as JSON on stdin, enabling complex logic that templates can't express:```python-import json, sys+import json, sys, subprocessctx = json.load(sys.stdin)-print(f"Setting up {ctx['repo']} on branch {ctx['branch']}")+# Run extra setup for feature branches on backend repos+if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+ subprocess.run(['make', 'seed-db'])```The JSON includes all template variables plus `hook_type` and `hook_name`.@@ -1640,13 +1624,14 @@ To reset, delete the entry or run `wt hook approvals clear`.#### Setting overrides (Experimental)-Override global settings for a specific project. Useful when one repo needs a different worktree layout or merge behavior.+Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run.```toml[projects."github.com/user/repo"]worktree-path = ".worktrees/{{ branch | sanitize }}"list.full = truemerge.squash = false+post-create.env = "cp .env.example .env"```### Custom prompt templatesdiff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 5daa3a055..0d8646064 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -149,7 +149,8 @@ impl<'a> CommitGenerator<'a> {impl CommitOptions<'_> {pub fn commit(self) -> anyhow::Result<()> {let project_config = self.ctx.repo.load_project_config()?;- let user_hooks_exist = self.ctx.config.hooks.pre_commit.is_some();+ let user_hooks = self.ctx.config.hooks(self.ctx.project_id().as_deref());+ let user_hooks_exist = user_hooks.pre_commit.is_some();let project_hooks_exist = project_config.as_ref().map(|c| c.hooks.pre_commit.is_some())@@ -174,7 +175,7 @@ impl CommitOptions<'_> {// Run pre-commit hooks (user first, then project)super::hooks::run_hook_with_filter(self.ctx,- self.ctx.config.hooks.pre_commit.as_ref(),+ user_hooks.pre_commit.as_ref(),project_config.as_ref().and_then(|c| c.hooks.pre_commit.as_ref()),diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 598cda16d..180d45564 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -413,8 +413,7 @@ pub(super) fn warn_unknown_keys<C: worktrunk::config::WorktrunkConfig>(keys.sort();for key in keys {- let value = &unknown_keys[key];- let msg = match worktrunk::config::key_belongs_in::<C>(key, value) {+ let msg = match worktrunk::config::key_belongs_in::<C>(key) {Some(location) => {cformat!("Key <bold>{key}</> belongs in {location} (will be ignored)")}diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 001b360dc..43125f6a4 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -95,10 +95,13 @@ pub fn run_hook(Ok(())}+ // Get effective user hooks (global + per-project merged)+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());+// Execute the hook based on typematch hook_type {HookType::PostCreate => {- let user_config = ctx.config.hooks.post_create.as_ref();+ let user_config = user_hooks.post_create.as_ref();let project_config = project_config.as_ref().and_then(|c| c.hooks.post_create.as_ref());@@ -116,7 +119,7 @@ pub fn run_hook()}HookType::PostStart => {- let user_config = ctx.config.hooks.post_start.as_ref();+ let user_config = user_hooks.post_start.as_ref();let project_config = project_config.as_ref().and_then(|c| c.hooks.post_start.as_ref());@@ -155,7 +158,7 @@ pub fn run_hook(}}HookType::PostSwitch => {- let user_config = ctx.config.hooks.post_switch.as_ref();+ let user_config = user_hooks.post_switch.as_ref();let project_config = project_config.as_ref().and_then(|c| c.hooks.post_switch.as_ref());@@ -194,7 +197,7 @@ pub fn run_hook(}}HookType::PreCommit => {- let user_config = ctx.config.hooks.pre_commit.as_ref();+ let user_config = user_hooks.pre_commit.as_ref();let project_config = project_config.as_ref().and_then(|c| c.hooks.pre_commit.as_ref());@@ -253,7 +256,7 @@ pub fn run_hook()}HookType::PostRemove => {- let user_config = ctx.config.hooks.post_remove.as_ref();+ let user_config = user_hooks.post_remove.as_ref();let project_config = project_config.as_ref().and_then(|c| c.hooks.post_remove.as_ref());@@ -512,16 +515,18 @@ fn render_user_hooks())?;- // Collect all user hooks+ // Collect all user hooks (global hooks from the user config file)+ // Note: uses overrides.hooks for display, not the merged hooks() accessor+ let user_hooks = &config.configs.hooks;let hooks = [- (HookType::PostCreate, &config.hooks.post_create),- (HookType::PostStart, &config.hooks.post_start),- (HookType::PostSwitch, &config.hooks.post_switch),- (HookType::PreCommit, &config.hooks.pre_commit),- (HookType::PreMerge, &config.hooks.pre_merge),- (HookType::PostMerge, &config.hooks.post_merge),- (HookType::PreRemove, &config.hooks.pre_remove),- (HookType::PostRemove, &config.hooks.post_remove),+ (HookType::PostCreate, &user_hooks.post_create),+ (HookType::PostStart, &user_hooks.post_start),+ (HookType::PostSwitch, &user_hooks.post_switch),+ (HookType::PreCommit, &user_hooks.pre_commit),+ (HookType::PreMerge, &user_hooks.pre_merge),+ (HookType::PostMerge, &user_hooks.post_merge),+ (HookType::PreRemove, &user_hooks.pre_remove),+ (HookType::PostRemove, &user_hooks.post_remove),];let mut has_any = false;diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex 7fe446bd6..1d5258fce 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -9,6 +9,7 @@ mod gitlab;mod platform;use anstyle::{AnsiColor, Color, Style};+use schemars::JsonSchema;use serde::{Deserialize, Serialize, de::DeserializeOwned};use worktrunk::git::Repository;use worktrunk::shell_exec::Cmd;@@ -227,7 +228,9 @@ pub enum CiStatus {/// Source of CI status (PR/MR vs branch workflow)////// Serialized to JSON as "pr" or "branch" for programmatic consumers.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::IntoStaticStr)]+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::IntoStaticStr, JsonSchema,+)]#[strum(serialize_all = "kebab-case")]pub enum CiSource {/// Pull request or merge requestdiff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex d5eb62221..d4f068d91 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -17,6 +17,7 @@use std::path::PathBuf;+use schemars::JsonSchema;use serde::Serialize;use worktrunk::git::LineDiff;@@ -24,7 +25,7 @@ use super::ci_status::{CiSource, PrStatus};use super::model::{ItemKind, ListItem, UpstreamStatus};/// JSON output for a single list item-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonItem {/// Branch name, null for detached HEADpub branch: Option<String>,@@ -100,7 +101,7 @@ pub struct JsonItem {}/// Commit information-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonCommit {/// Full commit SHApub sha: String,@@ -116,7 +117,7 @@ pub struct JsonCommit {}/// Working tree state-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonWorkingTree {/// Has staged files (+)pub staged: bool,@@ -139,7 +140,7 @@ pub struct JsonWorkingTree {}/// Line diff statistics-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonDiff {pub added: usize,pub deleted: usize,@@ -155,7 +156,7 @@ impl From<LineDiff> for JsonDiff {}/// Relationship to default branch-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonMain {/// Commits ahead of default branchpub ahead: usize,@@ -169,7 +170,7 @@ pub struct JsonMain {}/// Relationship to remote tracking branch-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonRemote {/// Remote name (e.g., "origin")pub name: String,@@ -185,7 +186,7 @@ pub struct JsonRemote {}/// Worktree-specific state-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonWorktree {/// Worktree state: "branch_worktree_mismatch", "prunable", "locked" (absent when normal)#[serde(skip_serializing_if = "Option::is_none")]@@ -200,7 +201,7 @@ pub struct JsonWorktree {}/// CI status from PR or branch workflow-#[derive(Debug, Clone, Serialize)]+#[derive(Debug, Clone, Serialize, JsonSchema)]pub struct JsonCi {/// CI status: "passed", "running", "failed", "conflicts", "no-ci", "error"pub status: &'static str,diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex 85f78a864..a8dd7000c 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -188,7 +188,7 @@ pub fn handle_list(None // --full disables timeout for complete data collection} else {config- .overrides+ .configs.list.as_ref().and_then(|l| l.timeout_ms)diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 017416670..a5ce9c554 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -319,9 +319,10 @@ pub fn run_pre_merge_commands(// Combine target with any custom vars (custom vars take precedence, added last)let mut vars = vec![("target", target_branch)];vars.extend_from_slice(extra_vars);+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());run_hook_with_filter(ctx,- ctx.config.hooks.pre_merge.as_ref(),+ user_hooks.pre_merge.as_ref(),project_config.hooks.pre_merge.as_ref(),HookType::PreMerge,&vars,@@ -352,9 +353,10 @@ pub fn execute_post_merge_commands(// Combine target with any custom vars (custom vars take precedence, added last)let mut vars = vec![("target", target_branch)];vars.extend_from_slice(extra_vars);+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());run_hook_with_filter(ctx,- ctx.config.hooks.post_merge.as_ref(),+ user_hooks.post_merge.as_ref(),project_config.as_ref().and_then(|c| c.hooks.post_merge.as_ref()),@@ -382,10 +384,11 @@ pub fn execute_pre_remove_commands(extra_vars: &[(&str, &str)],) -> anyhow::Result<()> {let project_config = ctx.repo.load_project_config()?;+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());run_hook_with_filter(ctx,- ctx.config.hooks.pre_remove.as_ref(),+ user_hooks.pre_remove.as_ref(),project_config.as_ref().and_then(|c| c.hooks.pre_remove.as_ref()),diff --git a/src/commands/select/pager.rs b/src/commands/select/pager.rsindex 919635ea1..ff8f21cb6 100644--- a/src/commands/select/pager.rs+++ b/src/commands/select/pager.rs@@ -36,7 +36,7 @@ pub(super) fn get_diff_pager() -> Option<&'static String> {// Check user config first for explicit pager override// When set, use exactly as specified (no auto-detection)if let Ok(config) = UserConfig::load()- && let Some(select_config) = config.overrides.select+ && let Some(select_config) = config.configs.select&& let Some(pager) = select_config.pager&& !pager.trim().is_empty(){@@ -81,7 +81,7 @@ pub(super) fn pager_needs_paging_disabled(pager_cmd: &str) -> bool {pub(super) fn has_explicit_pager_config() -> bool {UserConfig::load().ok()- .and_then(|config| config.overrides.select)+ .and_then(|config| config.configs.select).and_then(|select| select.pager).is_some_and(|p| !p.trim().is_empty())}diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex bded8e3dd..1dd90e614 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -145,7 +145,8 @@ pub fn handle_squash(.as_ref().map(|c| c.hooks.pre_commit.is_some()).unwrap_or(false);- let has_user_pre_commit = ctx.config.hooks.pre_commit.is_some();+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());+ let has_user_pre_commit = user_hooks.pre_commit.is_some();let has_any_pre_commit = has_project_pre_commit || has_user_pre_commit;if skip_pre_commit && has_any_pre_commit {@@ -160,7 +161,7 @@ pub fn handle_squash(let extra_vars = [("target", integration_target.as_str())];run_hook_with_filter(&ctx,- ctx.config.hooks.pre_commit.as_ref(),+ user_hooks.pre_commit.as_ref(),project_config.as_ref().and_then(|c| c.hooks.pre_commit.as_ref()),diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex f07c7e9d1..d3710687f 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -22,9 +22,10 @@ impl<'a> CommandContext<'a> {/// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).pub fn execute_post_create_commands(&self, extra_vars: &[(&str, &str)]) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;+ let user_hooks = self.config.hooks(self.project_id().as_deref());crate::commands::hooks::run_hook_with_filter(self,- self.config.hooks.post_create.as_ref(),+ user_hooks.post_create.as_ref(),project_config.as_ref().and_then(|c| c.hooks.post_create.as_ref()),@@ -47,10 +48,11 @@ impl<'a> CommandContext<'a> {display_path: Option<&std::path::Path>,) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;+ let user_hooks = self.config.hooks(self.project_id().as_deref());let commands = prepare_hook_commands(self,- self.config.hooks.post_start.as_ref(),+ user_hooks.post_start.as_ref(),project_config.as_ref().and_then(|c| c.hooks.post_start.as_ref()),@@ -76,10 +78,11 @@ impl<'a> CommandContext<'a> {display_path: Option<&std::path::Path>,) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;+ let user_hooks = self.config.hooks(self.project_id().as_deref());let commands = prepare_hook_commands(self,- self.config.hooks.post_switch.as_ref(),+ user_hooks.post_switch.as_ref(),project_config.as_ref().and_then(|c| c.hooks.post_switch.as_ref()),@@ -137,9 +140,10 @@ impl<'a> CommandContext<'a> {("short_commit", short_commit),];+ let user_hooks = self.config.hooks(self.project_id().as_deref());let commands = prepare_hook_commands(self,- self.config.hooks.post_remove.as_ref(),+ user_hooks.post_remove.as_ref(),project_config.as_ref().and_then(|c| c.hooks.post_remove.as_ref()),diff --git a/src/completion.rs b/src/completion.rsindex da5c06713..03cb960ae 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -260,8 +260,9 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {};// Load user config and add user hook names+ // Uses overrides.hooks for completion (global hooks from user config file)if let Ok(user_config) = UserConfig::load()- && let Some(config) = user_config.hooks.get(hook_type)+ && let Some(config) = user_config.configs.hooks.get(hook_type){add_named_commands(&mut candidates, config);}diff --git a/src/config/commands.rs b/src/config/commands.rsindex 8bf46a937..a44cd8e1f 100644--- a/src/config/commands.rs+++ b/src/config/commands.rs@@ -4,6 +4,7 @@//! of worktree and merge operations.use indexmap::IndexMap;+use schemars::JsonSchema;use serde::ser::SerializeMap;use serde::{Deserialize, Serialize};@@ -60,6 +61,15 @@ impl CommandConfig {pub fn commands(&self) -> &[Command] {&self.commands}++ /// Merge two configs by appending commands (base commands first, then overlay).+ ///+ /// Used for per-project hook overrides where both global and project hooks run.+ pub fn merge_append(&self, other: &Self) -> Self {+ let mut commands = self.commands.clone();+ commands.extend(other.commands.iter().cloned());+ Self { commands }+ }}// Custom deserialization to handle 2 TOML formats@@ -92,6 +102,24 @@ impl<'de> Deserialize<'de> for CommandConfig {}}+// JsonSchema for CommandConfig - describes the two TOML formats+impl JsonSchema for CommandConfig {+ fn schema_name() -> std::borrow::Cow<'static, str> {+ "CommandConfig".into()+ }++ fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {+ // CommandConfig accepts either a string or an object with string values+ // We just need this for schema generation, not validation+ schemars::json_schema!({+ "oneOf": [+ { "type": "string" },+ { "type": "object", "additionalProperties": { "type": "string" } }+ ]+ })+ }+}+// Serialize back to most appropriate formatimpl Serialize for CommandConfig {fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>@@ -328,4 +356,47 @@ third = "echo 3"};assert_eq!(config1, config2);}++ #[test]+ fn test_command_config_merge_append() {+ let base = CommandConfig {+ commands: vec![+ Command::new(None, "echo base1".to_string()),+ Command::new(Some("named".to_string()), "echo base2".to_string()),+ ],+ };+ let overlay = CommandConfig {+ commands: vec![Command::new(None, "echo overlay".to_string())],+ };++ let merged = base.merge_append(&overlay);+ assert_eq!(merged.commands.len(), 3);+ assert_eq!(merged.commands[0].template, "echo base1");+ assert_eq!(merged.commands[1].template, "echo base2");+ assert_eq!(merged.commands[2].template, "echo overlay");+ }++ #[test]+ fn test_command_config_merge_append_empty_base() {+ let base = CommandConfig { commands: vec![] };+ let overlay = CommandConfig {+ commands: vec![Command::new(None, "echo overlay".to_string())],+ };++ let merged = base.merge_append(&overlay);+ assert_eq!(merged.commands.len(), 1);+ assert_eq!(merged.commands[0].template, "echo overlay");+ }++ #[test]+ fn test_command_config_merge_append_empty_overlay() {+ let base = CommandConfig {+ commands: vec![Command::new(None, "echo base".to_string())],+ };+ let overlay = CommandConfig { commands: vec![] };++ let merged = base.merge_append(&overlay);+ assert_eq!(merged.commands.len(), 1);+ assert_eq!(merged.commands[0].template, "echo base");+ }}diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex 0be60ba8a..fb81f0dfb 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -764,11 +764,11 @@ pub fn format_deprecation_details(info: &DeprecationInfo) -> String {/// Generic over `C`, the config type where the key was found. If the key would/// be valid in `C::Other`, returns that config's description.///-/// For example, `key_belongs_in::<ProjectConfig>("commit-generation", value)` returns+/// For example, `key_belongs_in::<ProjectConfig>("commit-generation")` returns/// `Some("user config")`./// Returns `None` if the key is truly unknown (not valid in either config).-pub fn key_belongs_in<C: WorktrunkConfig>(key: &str, value: &toml::Value) -> Option<&'static str> {- C::Other::is_valid_key(key, value).then(C::Other::description)+pub fn key_belongs_in<C: WorktrunkConfig>(key: &str) -> Option<&'static str> {+ C::Other::is_valid_key(key).then(C::Other::description)}/// Warn about unknown fields in config file@@ -804,8 +804,7 @@ pub fn warn_unknown_fields<C: WorktrunkConfig>(keys.sort();for key in keys {- let value = &unknown_keys[key];- if let Some(other_location) = key_belongs_in::<C>(key, value) {+ if let Some(other_location) = key_belongs_in::<C>(key) {eprintln!("{}",warning_message(cformat!(diff --git a/src/config/hooks.rs b/src/config/hooks.rsindex 8627949a0..f9b247539 100644--- a/src/config/hooks.rs+++ b/src/config/hooks.rs@@ -1,3 +1,4 @@+use schemars::JsonSchema;use serde::{Deserialize, Serialize};use crate::git::HookType;@@ -5,7 +6,7 @@ use crate::git::HookType;use super::commands::CommandConfig;/// Shared hook configuration for user and project configs.-#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]pub struct HooksConfig {/// Commands to execute after worktree creation (blocking)#[serde(@@ -82,3 +83,36 @@ impl HooksConfig {}}}++use super::user::Merge;++/// Merge two optional command configs by appending (base commands first, then overlay).+fn merge_append_hooks(+ base: &Option<CommandConfig>,+ overlay: &Option<CommandConfig>,+) -> Option<CommandConfig> {+ match (base, overlay) {+ (None, None) => None,+ (Some(b), None) => Some(b.clone()),+ (None, Some(o)) => Some(o.clone()),+ (Some(b), Some(o)) => Some(b.merge_append(o)),+ }+}++impl Merge for HooksConfig {+ /// Merge two hook configs using append semantics.+ ///+ /// Both global and per-project hooks run (global first, then per-project).+ fn merge_with(&self, other: &Self) -> Self {+ Self {+ post_create: merge_append_hooks(&self.post_create, &other.post_create),+ post_start: merge_append_hooks(&self.post_start, &other.post_start),+ post_switch: merge_append_hooks(&self.post_switch, &other.post_switch),+ pre_commit: merge_append_hooks(&self.pre_commit, &other.pre_commit),+ pre_merge: merge_append_hooks(&self.pre_merge, &other.pre_merge),+ post_merge: merge_append_hooks(&self.post_merge, &other.post_merge),+ pre_remove: merge_append_hooks(&self.pre_remove, &other.pre_remove),+ post_remove: merge_append_hooks(&self.post_remove, &other.post_remove),+ }+ }+}diff --git a/src/config/mod.rs b/src/config/mod.rsindex a81cc0d0f..ffbbaa42d 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -24,56 +24,51 @@ mod project;mod test;mod user;-use std::collections::HashMap;-/// Trait for worktrunk config types (user and project config).///-/// Both config types capture unrecognized fields during parsing, allowing-/// validation to detect misplaced or misspelled keys. The `Other` associated-/// type enables checking whether a key belongs in the other config.+/// Both config types use JsonSchema to derive valid keys, allowing validation+/// to detect misplaced or misspelled keys. The `Other` associated type enables+/// checking whether a key belongs in the other config.pub trait WorktrunkConfig: for<'de> serde::Deserialize<'de> + Sized {/// The other config type (UserConfig ↔ ProjectConfig).type Other: WorktrunkConfig;- /// Returns the map of unknown fields captured during deserialization.- fn unknown(&self) -> &HashMap<String, toml::Value>;-/// Human-readable description of where this config lives.fn description() -> &'static str;- /// Check if a key+value would be valid in this config type.- fn is_valid_key(key: &str, value: &toml::Value) -> bool {- let mut table = toml::map::Map::new();- table.insert(key.to_string(), value.clone());- toml::Value::Table(table)- .try_into::<Self>()- .map(|c| !c.unknown().contains_key(key))- .unwrap_or(false)- }+ /// Check if a key would be valid in this config type.+ /// Uses JsonSchema-derived keys for validation.+ fn is_valid_key(key: &str) -> bool;}impl WorktrunkConfig for UserConfig {type Other = ProjectConfig;- fn unknown(&self) -> &HashMap<String, toml::Value> {- &self.unknown- }-fn description() -> &'static str {"user config"}++ fn is_valid_key(key: &str) -> bool {+ use std::sync::OnceLock;+ static VALID_KEYS: OnceLock<Vec<String>> = OnceLock::new();+ let valid_keys = VALID_KEYS.get_or_init(user::valid_user_config_keys);+ valid_keys.iter().any(|k| k == key)+ }}impl WorktrunkConfig for ProjectConfig {type Other = UserConfig;- fn unknown(&self) -> &HashMap<String, toml::Value> {- &self.unknown- }-fn description() -> &'static str {"project config"}++ fn is_valid_key(key: &str) -> bool {+ use std::sync::OnceLock;+ static VALID_KEYS: OnceLock<Vec<String>> = OnceLock::new();+ let valid_keys = VALID_KEYS.get_or_init(project::valid_project_config_keys);+ valid_keys.iter().any(|k| k == key)+ }}// Re-export public types@@ -140,7 +135,7 @@ mod tests {#[test]fn test_config_serialization_with_worktree_path() {let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("custom/{{ branch }}".to_string()),..Default::default()},@@ -155,7 +150,7 @@ mod tests {fn test_default_config() {let config = UserConfig::default();// worktree_path is None by default, but the getter returns the default- assert!(config.overrides.worktree_path.is_none());+ assert!(config.configs.worktree_path.is_none());assert_eq!(config.worktree_path(),"../{{ repo }}.{{ branch | sanitize }}"@@ -169,7 +164,7 @@ mod tests {fn test_format_worktree_path() {let test = test_repo();let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),..Default::default()},@@ -187,7 +182,7 @@ mod tests {fn test_format_worktree_path_custom_template() {let test = test_repo();let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("{{ main_worktree }}-{{ branch }}".to_string()),..Default::default()},@@ -205,7 +200,7 @@ mod tests {fn test_format_worktree_path_only_branch() {let test = test_repo();let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch }}".to_string()),..Default::default()},@@ -224,7 +219,7 @@ mod tests {let test = test_repo();// Use {{ branch | sanitize }} to replace slashes with dasheslet config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("{{ main_worktree }}.{{ branch | sanitize }}".to_string()),..Default::default()},@@ -242,7 +237,7 @@ mod tests {fn test_format_worktree_path_with_multiple_slashes() {let test = test_repo();let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),),@@ -263,7 +258,7 @@ mod tests {let test = test_repo();// Windows-style path separators should also be sanitizedlet config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),),@@ -284,7 +279,7 @@ mod tests {let test = test_repo();// {{ branch }} without filter gives raw branch namelet config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),..Default::default()},@@ -765,7 +760,7 @@ template-file = "~/file.txt"// Since we can't easily test load() without env vars, we verify the fields deserializeif let Ok(config) = config_result {let generation = config- .overrides+ .configs.commit.as_ref().and_then(|c| c.generation.as_ref());@@ -799,7 +794,7 @@ squash-template-file = "~/file.txt"// Since we can't easily test load() without env vars, we verify the fields deserializeif let Ok(config) = config_result {let generation = config- .overrides+ .configs.commit.as_ref().and_then(|c| c.generation.as_ref());@@ -894,6 +889,7 @@ lint = "cargo clippy"// Check post-createlet post_create = config+ .configs.hooks.post_create.expect("post-create should be present");@@ -902,7 +898,11 @@ lint = "cargo clippy"assert_eq!(commands[0].name.as_deref(), Some("log"));// Check pre-merge (multiple commands preserve order)- let pre_merge = config.hooks.pre_merge.expect("pre-merge should be present");+ let pre_merge = config+ .configs+ .hooks+ .pre_merge+ .expect("pre-merge should be present");let commands = pre_merge.commands();assert_eq!(commands.len(), 2);assert_eq!(commands[0].name.as_deref(), Some("test"));@@ -918,6 +918,7 @@ post-create = "npm install"let config: UserConfig = toml::from_str(toml_str).unwrap();let post_create = config+ .configs.hooks.post_create.expect("post-create should be present");diff --git a/src/config/project.rs b/src/config/project.rsindex 9dd1123c2..391f5b4ce 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -3,6 +3,7 @@//! Configuration that is checked into the repository and shared across all developers.use config::ConfigError;+use schemars::JsonSchema;use serde::{Deserialize, Serialize};use super::HooksConfig;@@ -18,7 +19,7 @@ use super::HooksConfig;/// [list]/// url = "http://localhost:{{ branch | hash_port }}"/// ```-#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]pub struct ProjectListConfig {/// URL template for dev server links shown in `wt list`.///@@ -43,7 +44,7 @@ pub struct ProjectListConfig {/// [ci]/// platform = "github" # or "gitlab"/// ```-#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]pub struct ProjectCiConfig {/// CI platform override. When set, skips URL-based platform detection.///@@ -94,7 +95,7 @@ impl ProjectConfig {////// - `{{ branch | sanitize }}` - Replace `/` and `\` with `-` (e.g., "feature-auth")/// - `{{ branch | hash_port }}` - Hash string to deterministic port (10000-19999)-#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]pub struct ProjectConfig {/// Project hooks (same keys as user hooks, flattened at top level)#[serde(flatten, default)]@@ -107,10 +108,6 @@ pub struct ProjectConfig {/// CI configuration (platform override)#[serde(default)]pub ci: Option<ProjectCiConfig>,-- /// Captures unknown fields for validation warnings- #[serde(flatten, default, skip_serializing)]- pub unknown: std::collections::HashMap<String, toml::Value>,}impl ProjectConfig {@@ -171,18 +168,39 @@ impl ProjectConfig {}}+/// Returns all valid top-level keys in project config, derived from the JsonSchema.+///+/// This includes keys from ProjectConfig and HooksConfig (flattened).+/// Public for use by the `WorktrunkConfig` trait implementation.+pub fn valid_project_config_keys() -> Vec<String> {+ use schemars::SchemaGenerator;++ let schema = SchemaGenerator::default().into_root_schema_for::<ProjectConfig>();++ schema+ .as_object()+ .and_then(|obj| obj.get("properties"))+ .and_then(|p| p.as_object())+ .map(|props| props.keys().cloned().collect())+ .unwrap_or_default()+}+/// Find unknown keys in project config TOML content////// Returns a map of unrecognized top-level keys (with their values) that will be ignored.-/// Uses serde deserialization with flatten to automatically detect unknown fields.+/// Compares against the known valid keys derived from the JsonSchema./// The values are included to allow checking if keys belong in the other config type.pub fn find_unknown_keys(contents: &str) -> std::collections::HashMap<String, toml::Value> {- // Deserialize into ProjectConfig - unknown fields are captured in the `unknown` map- let Ok(config) = toml::from_str::<ProjectConfig>(contents) else {+ let Ok(table) = contents.parse::<toml::Table>() else {return std::collections::HashMap::new();};- config.unknown+ let valid_keys = valid_project_config_keys();++ table+ .into_iter()+ .filter(|(key, _)| !valid_keys.contains(key))+ .collect()}#[cfg(test)]diff --git a/src/config/user.rs b/src/config/user.rsindex f1ead2159..51e836426 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -7,6 +7,7 @@ use std::sync::OnceLock;use config::{Case, Config, ConfigError, File};use fs2::FileExt;+use schemars::JsonSchema;use serde::{Deserialize, Serialize};use super::HooksConfig;@@ -86,6 +87,7 @@ use super::expansion::expand_template;clap::ValueEnum,serde::Serialize,serde::Deserialize,+ JsonSchema,)]#[serde(rename_all = "kebab-case")]pub enum StageMode {@@ -137,7 +139,7 @@ pub enum StageMode {////// Environment variables can override config file settings using `WORKTRUNK_` prefix with/// `__` separator for nested fields (e.g., `WORKTRUNK_COMMIT__GENERATION__COMMAND`).-#[derive(Debug, Default, Serialize, Deserialize)]+#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]pub struct UserConfig {/// **DEPRECATED**: Use `[commit.generation]` instead.///@@ -155,15 +157,9 @@ pub struct UserConfig {#[serde(default)]pub projects: std::collections::BTreeMap<String, UserProjectOverrides>,- /// Settings that can be overridden per-project (worktree-path, list, commit, merge, select)+ /// Settings that can be overridden per-project (worktree-path, list, commit, merge, select, hooks)#[serde(flatten, default)]- pub overrides: OverridableConfig,-- // =========================================================================- // User-level hooks (same syntax as project hooks, run before project hooks)- // =========================================================================- #[serde(flatten, default)]- pub hooks: HooksConfig,+ pub configs: OverridableConfig,/// Skip the first-run shell integration prompt#[serde(@@ -172,17 +168,13 @@ pub struct UserConfig {skip_serializing_if = "std::ops::Not::not")]pub skip_shell_integration_prompt: bool,-- /// Captures unknown fields for validation warnings- #[serde(flatten, default, skip_serializing)]- pub unknown: std::collections::HashMap<String, toml::Value>,}/// Configuration for commit message generation////// The command is a shell string executed via `sh -c`. Environment variables/// can be set inline (e.g., `MAX_THINKING_TOKENS=0 claude -p ...`).-#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]pub struct CommitGenerationConfig {/// Shell command to invoke for generating commit messages///@@ -279,7 +271,7 @@ impl Merge for CommitGenerationConfig {/// [projects."github.com/user/repo".merge]/// squash = false/// ```-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct UserProjectOverrides {/// Commands that have been approved for automatic execution in this project#[serde(@@ -317,7 +309,7 @@ impl UserProjectOverrides {}/// Configuration for the `wt list` command-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct ListConfig {/// Show CI and `main` diffstat by default#[serde(skip_serializing_if = "Option::is_none")]@@ -353,7 +345,7 @@ impl Merge for ListConfig {/// Configuration for the `wt step commit` command////// Also used by `wt merge` for shared settings like `stage`.-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct CommitConfig {/// What to stage before committing (default: all)/// Values: "all", "tracked", "none"@@ -384,7 +376,7 @@ impl Merge for CommitConfig {/// Configuration for the `wt merge` command////// Note: `stage` defaults from `[commit]` section, not here.-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct MergeConfig {/// Squash commits when merging (default: true)#[serde(skip_serializing_if = "Option::is_none")]@@ -422,7 +414,7 @@ impl Merge for MergeConfig {}/// Configuration for the `wt select` command-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct SelectConfig {/// Pager command with flags for diff preview///@@ -447,8 +439,20 @@ impl Merge for SelectConfig {/// This struct is flattened into both `UserConfig` (global) and `UserProjectOverrides`/// (per-project), ensuring new settings are automatically available in both/// contexts without manual synchronization.-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]+///+/// Note: Hooks use append semantics when merging global with per-project:+/// - Global hooks (top-level in TOML) are in `UserConfig.configs.hooks`+/// - Per-project hooks are in `UserProjectOverrides.overrides.hooks`+/// - The `UserConfig::hooks()` method merges both with global running first+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct OverridableConfig {+ /// Hooks configuration.+ ///+ /// At top level: global hooks that run for all projects.+ /// In `[projects."..."]`: per-project hooks that append to global hooks.+ #[serde(flatten, default)]+ pub hooks: HooksConfig,+/// Worktree path template#[serde(rename = "worktree-path",@@ -475,9 +479,12 @@ pub struct OverridableConfig {}impl OverridableConfig {- /// Returns true if all settings are None.+ /// Returns true if all settings are None/default.+ ///+ /// Includes hooks check for per-project configs where hooks are stored here.pub fn is_empty(&self) -> bool {- self.worktree_path.is_none()+ self.hooks == HooksConfig::default()+ && self.worktree_path.is_none()&& self.list.is_none()&& self.commit.is_none()&& self.merge.is_none()@@ -488,6 +495,7 @@ impl OverridableConfig {impl Merge for OverridableConfig {fn merge_with(&self, other: &Self) -> Self {Self {+ hooks: self.hooks.merge_with(&other.hooks), // Append semanticsworktree_path: other.worktree_path.clone()@@ -508,7 +516,7 @@ fn default_worktree_path() -> String {impl UserConfig {/// Returns the worktree path template, falling back to the default if not set.pub fn worktree_path(&self) -> String {- self.overrides+ self.configs.worktree_path.clone().unwrap_or_else(default_worktree_path)@@ -516,7 +524,7 @@ impl UserConfig {/// Returns true if the user has explicitly set a custom worktree-path.pub fn has_custom_worktree_path(&self) -> bool {- self.overrides.worktree_path.is_some()+ self.configs.worktree_path.is_some()}/// Returns the worktree path template for a specific project.@@ -542,7 +550,7 @@ impl UserConfig {pub fn commit_generation(&self, project: Option<&str>) -> CommitGenerationConfig {// Get global config: prefer new location, fall back to deprecatedlet global = self- .overrides+ .configs.commit.as_ref().and_then(|c| c.generation.as_ref())@@ -573,7 +581,7 @@ impl UserConfig {let project_config = project.and_then(|p| self.projects.get(p)).and_then(|c| c.overrides.list.as_ref());- merge_optional(self.overrides.list.as_ref(), project_config)+ merge_optional(self.configs.list.as_ref(), project_config)}/// Returns the commit config for a specific project.@@ -584,7 +592,7 @@ impl UserConfig {let project_config = project.and_then(|p| self.projects.get(p)).and_then(|c| c.overrides.commit.as_ref());- merge_optional(self.overrides.commit.as_ref(), project_config)+ merge_optional(self.configs.commit.as_ref(), project_config)}/// Returns the merge config for a specific project.@@ -595,7 +603,7 @@ impl UserConfig {let project_config = project.and_then(|p| self.projects.get(p)).and_then(|c| c.overrides.merge.as_ref());- merge_optional(self.overrides.merge.as_ref(), project_config)+ merge_optional(self.configs.merge.as_ref(), project_config)}/// Returns the select config for a specific project.@@ -606,7 +614,23 @@ impl UserConfig {let project_config = project.and_then(|p| self.projects.get(p)).and_then(|c| c.overrides.select.as_ref());- merge_optional(self.overrides.select.as_ref(), project_config)+ merge_optional(self.configs.select.as_ref(), project_config)+ }++ /// Returns effective hooks for a specific project.+ ///+ /// Merges global hooks with per-project hooks using append semantics.+ /// Both global and per-project hooks run (global first, then per-project).+ pub fn hooks(&self, project: Option<&str>) -> HooksConfig {+ let global = &self.configs.hooks;+ let project_hooks = project+ .and_then(|p| self.projects.get(p))+ .map(|c| &c.overrides.hooks);++ match project_hooks {+ Some(ph) => global.merge_with(ph),+ None => global.clone(),+ }}/// Load configuration from config file and environment variables.@@ -683,7 +707,7 @@ impl UserConfig {/// Validate configuration values.fn validate(&self) -> Result<(), ConfigError> {// Validate worktree path (only if explicitly set - default is always valid)- if let Some(ref path) = self.overrides.worktree_path {+ if let Some(ref path) = self.configs.worktree_path {if path.is_empty() {return Err(ConfigError::Message("worktree-path cannot be empty".into()));}@@ -1225,18 +1249,42 @@ pub fn get_config_path() -> Option<PathBuf> {}}+/// Returns all valid top-level keys in user config, derived from the JsonSchema.+///+/// This includes keys from UserConfig, OverridableConfig (flattened), and HooksConfig (flattened).+/// Public for use by the `WorktrunkConfig` trait implementation.+pub fn valid_user_config_keys() -> Vec<String> {+ use schemars::SchemaGenerator;++ let schema = SchemaGenerator::default().into_root_schema_for::<UserConfig>();++ // Extract property names from the schema+ // The schema flattens nested structs, so all top-level keys appear in properties+ schema+ .as_object()+ .and_then(|obj| obj.get("properties"))+ .and_then(|p| p.as_object())+ .map(|props| props.keys().cloned().collect())+ .unwrap_or_default()+}+/// Find unknown keys in user config TOML content.////// Returns a map of unrecognized top-level keys (with their values) that will be ignored.-/// Uses serde deserialization with flatten to automatically detect unknown fields.+/// Compares against the known valid keys derived from the JsonSchema rather than using+/// serde flatten catchall (which doesn't work reliably with nested flattens)./// The values are included to allow checking if keys belong in the other config type.pub fn find_unknown_keys(contents: &str) -> std::collections::HashMap<String, toml::Value> {- // Deserialize into UserConfig - unknown fields are captured in the `unknown` map- let Ok(config) = toml::from_str::<UserConfig>(contents) else {+ let Ok(table) = contents.parse::<toml::Table>() else {return std::collections::HashMap::new();};- config.unknown+ let valid_keys = valid_user_config_keys();++ table+ .into_iter()+ .filter(|(key, _)| !valid_keys.contains(key))+ .collect()}#[cfg(test)]@@ -1274,7 +1322,11 @@ mod tests {worktree-path = "../{{ main_worktree }}.{{ branch }}""#;let keys = find_unknown_keys(content);- assert!(keys.is_empty());+ assert!(+ keys.is_empty(),+ "Expected no unknown keys, found: {:?}",+ keys+ );}#[test]@@ -1436,7 +1488,7 @@ rename-tab = "echo 'switched'"#[test]fn test_worktree_path_for_project_falls_back_to_global() {let mut config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("../{{ repo }}-{{ branch | sanitize }}".to_string()),..Default::default()},@@ -1476,7 +1528,7 @@ rename-tab = "echo 'switched'"fn test_format_path_with_project_override() {let test = test_repo();let mut config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("../{{ repo }}.{{ branch | sanitize }}".to_string()),..Default::default()},@@ -1538,15 +1590,15 @@ rename-tab = "echo 'switched'"fn test_worktrunk_config_default() {let config = UserConfig::default();// worktree_path is None by default, but the getter returns the default- assert!(config.overrides.worktree_path.is_none());+ assert!(config.configs.worktree_path.is_none());assert_eq!(config.worktree_path(),"../{{ repo }}.{{ branch | sanitize }}");assert!(config.projects.is_empty());- assert!(config.overrides.list.is_none());- assert!(config.overrides.commit.is_none());- assert!(config.overrides.merge.is_none());+ assert!(config.configs.list.is_none());+ assert!(config.configs.commit.is_none());+ assert!(config.configs.merge.is_none());assert!(config.commit_generation.is_none());assert!(!config.skip_shell_integration_prompt);}@@ -1661,7 +1713,7 @@ rename-tab = "echo 'switched'"fn test_worktrunk_config_format_path_custom_template() {let test = test_repo();let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some(".worktrees/{{ branch }}".to_string()),..Default::default()},@@ -1982,7 +2034,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"#[test]fn test_effective_commit_generation_no_project() {let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {commit: Some(CommitConfig {stage: None,generation: Some(CommitGenerationConfig {@@ -2002,7 +2054,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"#[test]fn test_effective_commit_generation_with_project_override() {let mut config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {commit: Some(CommitConfig {stage: None,generation: Some(CommitGenerationConfig {@@ -2047,7 +2099,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"#[test]fn test_effective_merge_with_partial_override() {let mut config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {merge: Some(MergeConfig {squash: Some(true),commit: Some(true),@@ -2087,7 +2139,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"fn test_effective_list_project_only() {// No global list config, only project configlet mut config = UserConfig::default();- assert!(config.overrides.list.is_none());+ assert!(config.configs.list.is_none());config.projects.insert("github.com/user/repo".to_string(),@@ -2117,7 +2169,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"fn test_effective_select_with_project_override() {// Test that OverridableConfig merge works correctly for selectlet mut config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {select: Some(SelectConfig {pager: Some("delta".to_string()),}),@@ -2156,7 +2208,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"fn test_effective_commit_global_only() {// Only global config, no project configlet config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {commit: Some(CommitConfig {stage: Some(StageMode::Tracked),generation: None,@@ -2254,12 +2306,12 @@ squash = false// Global configassert_eq!(- config.overrides.worktree_path,+ config.configs.worktree_path,Some("../{{ repo }}.{{ branch | sanitize }}".to_string()));assert_eq!(config- .overrides+ .configs.commit.as_ref().unwrap()@@ -2539,7 +2591,7 @@ squash-template-file = "path/to/file"let config_path = dir.path().join("config.toml");let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {commit: Some(CommitConfig {stage: None,generation: Some(CommitGenerationConfig {@@ -2620,7 +2672,7 @@ squash-template-file = "path/to/file"let config_path = dir.path().join("config.toml");let config = UserConfig {- overrides: OverridableConfig {+ configs: OverridableConfig {worktree_path: Some("../{{ repo }}.{{ branch }}".to_string()),..Default::default()},@@ -2635,4 +2687,222 @@ squash-template-file = "path/to/file""Should contain worktree-path: {saved}");}++ // =========================================================================+ // Per-project hooks tests (append semantics)+ // =========================================================================++ /// Helper to parse hooks from TOML+ fn parse_hooks(toml_str: &str) -> HooksConfig {+ toml::from_str(toml_str).unwrap()+ }++ #[test]+ fn test_hooks_merge_append_semantics() {+ // Global has post-start, per-project has post-start+ // Both should run (global first, then per-project)+ let mut config = UserConfig {+ configs: OverridableConfig {+ hooks: parse_hooks("post-start = \"echo global\""),+ ..Default::default()+ },+ ..Default::default()+ };++ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectOverrides {+ overrides: OverridableConfig {+ hooks: parse_hooks("post-start = \"echo project\""),+ ..Default::default()+ },+ ..Default::default()+ },+ );++ let effective = config.hooks(Some("github.com/user/repo"));+ let post_start = effective.post_start.unwrap();+ let commands = post_start.commands();+ assert_eq!(commands.len(), 2);+ assert_eq!(commands[0].template, "echo global");+ assert_eq!(commands[1].template, "echo project");+ }++ #[test]+ fn test_hooks_no_project_override_uses_global() {+ // Global has hooks, project doesn't - global hooks used+ let config = UserConfig {+ configs: OverridableConfig {+ hooks: parse_hooks("post-start = \"echo global\""),+ ..Default::default()+ },+ ..Default::default()+ };++ let effective = config.hooks(Some("github.com/other/repo"));+ let post_start = effective.post_start.unwrap();+ let commands = post_start.commands();+ assert_eq!(commands.len(), 1);+ assert_eq!(commands[0].template, "echo global");+ }++ #[test]+ fn test_hooks_project_only_no_global() {+ // Project has hooks, global doesn't - project hooks used+ let mut config = UserConfig::default();++ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectOverrides {+ overrides: OverridableConfig {+ hooks: parse_hooks("post-start = \"echo project\""),+ ..Default::default()+ },+ ..Default::default()+ },+ );++ let effective = config.hooks(Some("github.com/user/repo"));+ let post_start = effective.post_start.unwrap();+ let commands = post_start.commands();+ assert_eq!(commands.len(), 1);+ assert_eq!(commands[0].template, "echo project");+ }++ #[test]+ fn test_hooks_different_hook_types_not_merged() {+ // Global has post-start, per-project has pre-commit+ // These should remain separate (different hook types)+ let mut config = UserConfig {+ configs: OverridableConfig {+ hooks: parse_hooks("post-start = \"echo global-start\""),+ ..Default::default()+ },+ ..Default::default()+ };++ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectOverrides {+ overrides: OverridableConfig {+ hooks: parse_hooks("pre-commit = \"echo project-commit\""),+ ..Default::default()+ },+ ..Default::default()+ },+ );++ let effective = config.hooks(Some("github.com/user/repo"));++ // post-start: only global+ let post_start = effective.post_start.unwrap();+ let start_commands = post_start.commands();+ assert_eq!(start_commands.len(), 1);+ assert_eq!(start_commands[0].template, "echo global-start");++ // pre-commit: only project+ let pre_commit = effective.pre_commit.unwrap();+ let commit_commands = pre_commit.commands();+ assert_eq!(commit_commands.len(), 1);+ assert_eq!(commit_commands[0].template, "echo project-commit");+ }++ #[test]+ fn test_hooks_none_project_uses_global() {+ // When no project is provided, only global hooks are used+ let config = UserConfig {+ configs: OverridableConfig {+ hooks: parse_hooks("post-start = \"echo global\""),+ ..Default::default()+ },+ ..Default::default()+ };++ let effective = config.hooks(None);+ let post_start = effective.post_start.unwrap();+ let commands = post_start.commands();+ assert_eq!(commands.len(), 1);+ assert_eq!(commands[0].template, "echo global");+ }++ #[test]+ fn test_hooks_in_overridable_config_is_empty() {+ // Default hooks should be considered empty+ let config = OverridableConfig::default();+ assert!(config.is_empty());++ // With hooks set, should not be empty+ let config = OverridableConfig {+ hooks: parse_hooks("post-start = \"echo test\""),+ ..Default::default()+ };+ assert!(!config.is_empty());+ }++ /// Validates that valid_user_config_keys() includes all hook types from HookType enum.+ ///+ /// The JsonSchema derivation should include all HooksConfig fields, which correspond+ /// to HookType variants. HookType uses strum's Display with kebab-case serialization,+ /// which matches the serde field names.+ #[test]+ fn test_valid_user_config_keys_includes_all_hook_types() {+ use crate::git::HookType;+ use strum::IntoEnumIterator;++ let valid_keys = valid_user_config_keys();++ for hook_type in HookType::iter() {+ let key = hook_type.to_string(); // e.g., "post-create", "pre-merge"+ assert!(+ valid_keys.contains(&key),+ "HookType::{hook_type:?} ({key}) is missing from valid_user_config_keys()"+ );+ }+ }++ /// Validates that all keys from valid_user_config_keys() are accepted by serde.+ ///+ /// Creates a TOML config with each key set to a valid value and verifies+ /// deserialization succeeds. This ensures the JsonSchema matches serde's expectations.+ #[test]+ fn test_valid_user_config_keys_all_deserialize() {+ let valid_keys = valid_user_config_keys();++ // Build a TOML string with all keys+ // Top-level scalar values must come before table sections+ let mut scalar_lines = Vec::new();+ let mut table_lines = Vec::new();++ for key in &valid_keys {+ match key.as_str() {+ "projects" => continue, // Skip - table type tested separately+ "skip-shell-integration-prompt" => {+ scalar_lines.push(format!("{key} = true"));+ }+ "worktree-path" => {+ scalar_lines.push(format!("{key} = \"test-value\""));+ }+ "list" | "commit" | "merge" | "select" | "commit-generation" => {+ // Table sections with minimal content+ table_lines.push(format!("[{key}]"));+ }+ // Hook keys take string values+ _ => {+ scalar_lines.push(format!("{key} = \"test-value\""));+ }+ };+ }++ // Scalars first, then tables+ scalar_lines.extend(table_lines);+ let toml_content = scalar_lines.join("\n");++ // Should deserialize without error+ let result: Result<UserConfig, _> = toml::from_str(&toml_content);+ assert!(+ result.is_ok(),+ "Failed to deserialize config with all valid keys:\n{toml_content}\nError: {:?}",+ result.err()+ );+ }}diff --git a/tests/integration_tests/select_config.rs b/tests/integration_tests/select_config.rsindex 0edd2de5f..515fbc9d8 100644--- a/tests/integration_tests/select_config.rs+++ b/tests/integration_tests/select_config.rs@@ -10,8 +10,8 @@ pager = "test-pager --custom-flag"let config: UserConfig = toml::from_str(config_content).unwrap();- assert!(config.overrides.select.is_some());- let select = config.overrides.select.unwrap();+ assert!(config.configs.select.is_some());+ let select = config.configs.select.unwrap();assert_eq!(select.pager, Some("test-pager --custom-flag".to_string()));}@@ -25,8 +25,8 @@ pager = ""let config: UserConfig = toml::from_str(config_content).unwrap();- assert!(config.overrides.select.is_some());- let select = config.overrides.select.unwrap();+ assert!(config.configs.select.is_some());+ let select = config.configs.select.unwrap();assert_eq!(select.pager, Some("".to_string()));}@@ -39,5 +39,5 @@ full = true"#;let config: UserConfig = toml::from_str(config_content).unwrap();- assert!(config.overrides.select.is_none());+ assert!(config.configs.select.is_none());}diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snapindex 8c76f0b4d..95e4abadc 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap@@ -154,12 +154,13 @@ Creates [2m~/.config/worktrunk/config.toml[0m with the following content:[2m#[0m[2m# #### Setting overrides (Experimental)[0m[2m#[0m- [2m# Override global settings for a specific project. Useful when one repo needs a different worktree layout or merge behavior.[0m+ [2m# Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run.[0m[2m#[0m[2m# [projects."github.com/user/repo"][0m[2m# worktree-path = ".worktrees/{{ branch | sanitize }}"[0m[2m# list.full = true[0m[2m# merge.squash = false[0m+ [2m# post-create.env = "cp .env.example .env"[0m[2m#[0m[2m# ### Custom prompt templates[0m[2m#[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex f4860f8b0..ac7fcf669 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -199,12 +199,13 @@ To reset, delete the entry or run [2mwt hook approvals clear[0m.[1mSetting overrides (Experimental)[0m-Override global settings for a specific project. Useful when one repo needs a different worktree layout or merge behavior.+Override global user config for a specific project. Scalar values (like [2mworktree-path[0m) replace the global value. Hooks append — both global and per-project hooks run.[2m[projects."github.com/user/repo"][0m[2mworktree-path = ".worktrees/{{ branch | sanitize }}"[0m[2mlist.full = true[0m[2mmerge.squash = false[0m+ [2mpost-create.env = "cp .env.example .env"[0m[32mCustom prompt templates[0m