Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(step): gate copy-ignored self-lower on WORKTRUNK_FOREGROUND=-1 (#2358)
Worktrunk Botea505bebf9b4
diff --git a/docs/content/step.md b/docs/content/step.mdindex c65de8b67..659286452 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -367,10 +367,16 @@ Reflink copies share disk blocks until modified — no data is actually copied.| `cp -R` (full copy) | 2m || `cp -Rc` / `wt step copy-ignored` | 20s |-Uses per-file reflink (like `cp -Rc`) — copy time scales with file count. On Unix, the process is automatically reniced to lowest priority (nice 19) so it yields to interactive work.+Uses per-file reflink (like `cp -Rc`) — copy time scales with file count.Use the `post-start` hook so the copy runs in the background. Use `pre-start` instead if subsequent hooks or `--execute` command need the copied files immediately.+### Background-hook priority (experimental)++When invoked from a background hook pipeline (`post-*` hooks), `wt step copy-ignored` self-lowers its CPU and I/O priority — `taskpolicy -b` on macOS, `nice -n 19` plus `ionice -c 3` on Linux — so it yields to interactive work. Foreground callers (`pre-*` hooks, direct interactive use) run at normal priority so the user isn't waiting on a throttled copy.++wt signals background-hook context by exporting `WORKTRUNK_FOREGROUND=-1` into every detached hook pipeline; `copy-ignored` inspects that variable on entry. The variable name is experimental and may change.+### Language-specific notes#### Rustdiff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex 876d642a4..454da1c83 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -381,10 +381,16 @@ Reflink copies share disk blocks until modified — no data is actually copied.| `cp -R` (full copy) | 2m || `cp -Rc` / `wt step copy-ignored` | 20s |-Uses per-file reflink (like `cp -Rc`) — copy time scales with file count. On Unix, the process is automatically reniced to lowest priority (nice 19) so it yields to interactive work.+Uses per-file reflink (like `cp -Rc`) — copy time scales with file count.Use the `post-start` hook so the copy runs in the background. Use `pre-start` instead if subsequent hooks or `--execute` command need the copied files immediately.+### Background-hook priority (experimental)++When invoked from a background hook pipeline (`post-*` hooks), `wt step copy-ignored` self-lowers its CPU and I/O priority — `taskpolicy -b` on macOS, `nice -n 19` plus `ionice -c 3` on Linux — so it yields to interactive work. Foreground callers (`pre-*` hooks, direct interactive use) run at normal priority so the user isn't waiting on a throttled copy.++wt signals background-hook context by exporting `WORKTRUNK_FOREGROUND=-1` into every detached hook pipeline; `copy-ignored` inspects that variable on entry. The variable name is experimental and may change.+### Language-specific notes#### Rustdiff --git a/src/cli/step.rs b/src/cli/step.rsindex 3c0fc697f..67f1e41de 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -299,10 +299,16 @@ Reflink copies share disk blocks until modified — no data is actually copied.| `cp -R` (full copy) | 2m || `cp -Rc` / `wt step copy-ignored` | 20s |-Uses per-file reflink (like `cp -Rc`) — copy time scales with file count. On Unix, the process is automatically reniced to lowest priority (nice 19) so it yields to interactive work.+Uses per-file reflink (like `cp -Rc`) — copy time scales with file count.Use the `post-start` hook so the copy runs in the background. Use `pre-start` instead if subsequent hooks or `--execute` command need the copied files immediately.+## Background-hook priority (experimental)++When invoked from a background hook pipeline (`post-*` hooks), `wt step copy-ignored` self-lowers its CPU and I/O priority — `taskpolicy -b` on macOS, `nice -n 19` plus `ionice -c 3` on Linux — so it yields to interactive work. Foreground callers (`pre-*` hooks, direct interactive use) run at normal priority so the user isn't waiting on a throttled copy.++wt signals background-hook context by exporting `WORKTRUNK_FOREGROUND=-1` into every detached hook pipeline; `copy-ignored` inspects that variable on entry. The variable name is experimental and may change.+## Language-specific notes### Rustdiff --git a/src/commands/process.rs b/src/commands/process.rsindex dd8fcab82..eb305ec82 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -319,6 +319,12 @@ fn spawn_detached_windows(////// Used for structured child processes like `wt hook run-pipeline` where the parent/// passes data via stdin rather than through a temp file or shell arguments.+///+/// When `hook_log` is [`HookLog::Hook`], the spawn is treated as a background+/// hook pipeline: the child (and every process it later spawns) receives+/// [`worktrunk::priority::FOREGROUND_ENV_VAR`] =+/// [`worktrunk::priority::BACKGROUND_HOOK_VALUE`] so nested `wt` invocations+/// can tell they're running inside a background hook.pub fn spawn_detached_exec(repo: &Repository,worktree_path: &Path,@@ -337,6 +343,8 @@ pub fn spawn_detached_exec(log_path.file_name().unwrap_or_default().to_string_lossy());+ let is_background_hook = matches!(hook_log, HookLog::Hook { .. });+#[cfg(unix)]{let low_priority = matches!(hook_log, HookLog::Internal(_));@@ -347,17 +355,36 @@ pub fn spawn_detached_exec(log_file,stdin_bytes,low_priority,+ is_background_hook,)?;}#[cfg(windows)]{- spawn_detached_exec_windows(worktree_path, program, args, log_file, stdin_bytes)?;+ spawn_detached_exec_windows(+ worktree_path,+ program,+ args,+ log_file,+ stdin_bytes,+ is_background_hook,+ )?;}Ok(log_path)}+/// Apply [`worktrunk::priority::FOREGROUND_ENV_VAR`] to a+/// [`std::process::Command`] when spawning a background hook pipeline.+fn set_background_hook_env(cmd: &mut std::process::Command, is_background_hook: bool) {+ if is_background_hook {+ cmd.env(+ worktrunk::priority::FOREGROUND_ENV_VAR,+ worktrunk::priority::BACKGROUND_HOOK_VALUE,+ );+ }+}+#[cfg(unix)]fn spawn_detached_exec_unix(worktree_path: &Path,@@ -366,6 +393,7 @@ fn spawn_detached_exec_unix(log_file: fs::File,stdin_bytes: &[u8],low_priority: bool,+ is_background_hook: bool,) -> anyhow::Result<()> {use std::io::Write;use std::os::unix::process::CommandExt;@@ -383,6 +411,7 @@ fn spawn_detached_exec_unix(.stderr(Stdio::from(log_file)).process_group(0);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);+ set_background_hook_env(&mut cmd, is_background_hook);let mut child = cmd.spawn().context("Failed to spawn detached process")?;if let Some(mut stdin) = child.stdin.take() {@@ -400,6 +429,7 @@ fn spawn_detached_exec_windows(args: &[&str],log_file: fs::File,stdin_bytes: &[u8],+ is_background_hook: bool,) -> anyhow::Result<()> {use std::io::Write;use std::os::windows::process::CommandExt;@@ -419,6 +449,7 @@ fn spawn_detached_exec_windows(.stderr(Stdio::from(log_file)).creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);+ set_background_hook_env(&mut cmd, is_background_hook);let mut child = cmd.spawn().context("Failed to spawn detached process")?;if let Some(mut stdin) = child.stdin.take() {diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 6d7a86e53..be4d8890f 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -704,7 +704,14 @@ pub fn step_copy_ignored(dry_run: bool,force: bool,) -> anyhow::Result<()> {- worktrunk::priority::lower_current_process();+ // Self-lower only when we're running inside a background hook pipeline+ // (parent `wt` sets `WORKTRUNK_FOREGROUND=-1` on the detached runner).+ // Foreground callers — interactive `wt step copy-ignored` and synchronous+ // `pre-*` hook pipelines — are the UI the user is waiting on and must not+ // be I/O-throttled by `taskpolicy -b` on macOS.+ if worktrunk::priority::in_background_hook() {+ worktrunk::priority::lower_current_process();+ }let repo = Repository::current()?;let copy_ignored_config = resolve_copy_ignored_config(&repo)?;diff --git a/src/priority.rs b/src/priority.rsindex 3b91fe25f..910e63ba2 100644--- a/src/priority.rs+++ b/src/priority.rs@@ -35,6 +35,17 @@//! `ionice … nice … <cmd>`. Used for detached background spawns where we//! want the wrapper tool itself to apply the policy and then exec the real//! work.+//!+//! ## Background-hook context signalling+//!+//! When wt spawns a background hook pipeline (detached `wt hook run-pipeline`),+//! it exports [`FOREGROUND_ENV_VAR`] = [`BACKGROUND_HOOK_VALUE`] (`-1`) into+//! that process's environment. The variable is inherited by every child the+//! pipeline spawns (shell, user command, any nested `wt` invocation). Commands+//! that want to yield priority only when they're running inside a background+//! hook — rather than always — check it via [`in_background_hook`]. This is+//! an experimental hook-vs-foreground signal; the variable name and value are+//! not yet a stable contract.use std::ffi::OsStr;use std::process::Command;@@ -48,6 +59,32 @@ use std::sync::LazyLock;#[cfg(all(unix, not(target_os = "macos")))]static HAS_IONICE: LazyLock<bool> = LazyLock::new(|| which::which("ionice").is_ok());+/// Environment variable wt sets on background hook pipelines so descendants+/// can tell whether they're running in the foreground or inside a background+/// hook. Experimental; see the [module docs](self) for context.+pub const FOREGROUND_ENV_VAR: &str = "WORKTRUNK_FOREGROUND";++/// Value written to [`FOREGROUND_ENV_VAR`] when the enclosing context is a+/// background hook pipeline. Positive and zero values are reserved for future+/// use (e.g., signalling foreground hook nesting levels); only `-1` currently+/// has an observer.+pub const BACKGROUND_HOOK_VALUE: &str = "-1";++/// Returns `true` when wt detects that the current process is running inside+/// a background hook pipeline. Checks [`FOREGROUND_ENV_VAR`] against+/// [`BACKGROUND_HOOK_VALUE`]; any other value (including unset) returns+/// `false` so interactive and foreground-hook invocations stay at normal+/// priority.+pub fn in_background_hook() -> bool {+ is_background_hook_value(std::env::var_os(FOREGROUND_ENV_VAR).as_deref())+}++/// Extracted comparison so tests can exercise the match without mutating+/// process-global environment state (forbidden per `tests/CLAUDE.md`).+fn is_background_hook_value(value: Option<&OsStr>) -> bool {+ value == Some(OsStr::new(BACKGROUND_HOOK_VALUE))+}+/// Lower the current process's scheduling and I/O priority.////// Non-fatal: if a helper binary is missing or fails, we proceed at normal@@ -138,6 +175,26 @@ mod tests {cmd.get_args().map(|a| a.to_str().unwrap()).collect()}+ #[test]+ fn foreground_env_var_name_and_value() {+ assert_eq!(FOREGROUND_ENV_VAR, "WORKTRUNK_FOREGROUND");+ assert_eq!(BACKGROUND_HOOK_VALUE, "-1");+ }++ #[test]+ fn background_hook_value_matches_sentinel_only() {+ // Only the exact sentinel counts as "inside a background hook".+ // Unset, empty, and other numeric-looking values all stay foreground+ // so interactive and `pre-*` hook callers run at normal priority.+ assert!(is_background_hook_value(Some(OsStr::new("-1"))));+ assert!(!is_background_hook_value(None));+ assert!(!is_background_hook_value(Some(OsStr::new(""))));+ assert!(!is_background_hook_value(Some(OsStr::new("0"))));+ assert!(!is_background_hook_value(Some(OsStr::new("1"))));+ assert!(!is_background_hook_value(Some(OsStr::new("-2"))));+ assert!(!is_background_hook_value(Some(OsStr::new(" -1"))));+ }+#[test]fn command_no_lower_returns_bare() {let cmd = command("echo", false);diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 5e35aba46..684355851 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -205,6 +205,50 @@ bg = "echo 'USER_POST_START_RAN' > user_bg_marker.txt");}+#[rstest]+fn test_background_hook_sees_worktrunk_foreground_env_var(repo: TestRepo) {+ // Background hooks run via the detached `wt hook run-pipeline` runner; wt+ // sets WORKTRUNK_FOREGROUND=-1 on that process so descendants (shell,+ // user command, nested `wt` invocations) can tell they're backgrounded.+ // `pre-*` hooks run synchronously in the foreground `wt` process, so they+ // must NOT see the sentinel.+ repo.write_test_config(+ r#"[post-start]+capture-bg = "echo \"bg=$WORKTRUNK_FOREGROUND\" > post_start_env.txt"++[pre-start]+capture-fg = "echo \"fg=$WORKTRUNK_FOREGROUND\" > pre_start_env.txt"+"#,+ );++ snapshot_switch(+ "background_hook_env_var_visible",+ &repo,+ &["--create", "feature"],+ );++ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");++ // pre-start wrote its marker synchronously; post-start runs in the+ // background, so poll for the file.+ let bg_marker = worktree_path.join("post_start_env.txt");+ wait_for_file_content(&bg_marker);+ let bg = fs::read_to_string(&bg_marker).unwrap();+ assert_eq!(+ bg.trim(),+ "bg=-1",+ "post-start (background) hook should see WORKTRUNK_FOREGROUND=-1, got {bg:?}"+ );++ let fg_marker = worktree_path.join("pre_start_env.txt");+ let fg = fs::read_to_string(&fg_marker).unwrap();+ assert_eq!(+ fg.trim(),+ "fg=",+ "pre-start (foreground) hook should NOT see WORKTRUNK_FOREGROUND set, got {fg:?}"+ );+}+#[rstest]fn test_user_post_start_skipped_with_no_hooks(repo: TestRepo) {// Write user config with post-start hookdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__background_hook_env_var_visible.snap b/tests/snapshots/integration__integration_tests__user_hooks__background_hook_env_var_visible.snapnew file mode 100644index 000000000..294e2ed38--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__background_hook_env_var_visible.snap@@ -0,0 +1,54 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning pre-start [1muser:capture-fg[22m @ [1m_REPO_.feature[22m[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m"fg=[0m[2m[36m$[0m[2mWORKTRUNK_FOREGROUND"[0m[2m [0m[2m[36m>[0m[2m pre_start_env.txt+[0m[32m✓[39m [32mCreated branch [1mfeature[22m from [1mmain[22m and worktree @ [1m_REPO_.feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-start: [1muser:capture-bg[22m @ [1m_REPO_.feature[22m[39m