Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: pipe JSON context to hook stdin (#109)
Maximilian Roos3c971f06240c
diff --git a/docs/content/config.md b/docs/content/config.mdindex 94405e316..a0921b448 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -144,7 +144,7 @@ test = "npm test"lint = "npm run lint"```-See [Hooks](@/hooks.md) for complete documentation on hook types, execution order, and template variables.+See [Hooks](@/hooks.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hooks.md#json-context).## Shell integrationdiff --git a/docs/content/hooks.md b/docs/content/hooks.mdindex 117fefd9c..3e099606d 100644--- a/docs/content/hooks.md+++ b/docs/content/hooks.md@@ -90,6 +90,48 @@ post-create = "echo '{{ short_commit }}' > .version"pre-merge = "echo 'Merging {{ branch }} into {{ target }}'"```+## JSON context++Hooks receive all context variables as JSON on stdin. This allows hooks written in any language to access worktree information.++```toml+# .config/wt.toml — paths are relative to the worktree root+post-create = "./scripts/setup.py"+```++```python+#!/usr/bin/env python3+# scripts/setup.py+import json, sys++ctx = json.load(sys.stdin)+print(f"Setting up {ctx['repo']} on branch {ctx['branch']}")+print(f"Worktree: {ctx['worktree']}")+print(f"Hook: {ctx['hook_type']} {ctx.get('hook_name', '(unnamed)')}")+```++The JSON contains all the same fields as template variables, plus hook metadata:++```json+{+ "repo": "my-project",+ "branch": "feature-foo",+ "worktree": "/path/to/my-project.feature-foo",+ "worktree_name": "my-project.feature-foo",+ "repo_root": "/path/to/my-project",+ "default_branch": "main",+ "commit": "abc123...",+ "short_commit": "abc123",+ "remote": "origin",+ "upstream": "origin/feature-foo",+ "target": "main",+ "hook_type": "post-create",+ "hook_name": "setup"+}+```++Optional fields (`default_branch`, `commit`, `short_commit`, `remote`, `upstream`, `target`, `hook_name`) are only present when available.+## Hook details### post-creatediff --git a/docs/content/step.md b/docs/content/step.mdindex c1ebc7172..483eb14d6 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -51,6 +51,8 @@ wt step push- `pre-merge` — Before pushing to target- `post-merge` — After merge cleanup+Hooks receive context as JSON on stdin and support template variables.+## See also- [wt merge](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automaticallydiff --git a/src/cli.rs b/src/cli.rsindex 04baac8d0..8b8e37594 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -815,7 +815,7 @@ test = "npm test"lint = "npm run lint"```-See [Hooks](@/hooks.md) for complete documentation on hook types, execution order, and template variables.+See [Hooks](@/hooks.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hooks.md#json-context).## Shell integration@@ -936,6 +936,8 @@ wt step push- `pre-merge` — Before pushing to target- `post-merge` — After merge cleanup+Hooks receive context as JSON on stdin and support template variables.+## See also- [wt merge](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automaticallydiff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 3f73fc914..03db49fec 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -1,6 +1,8 @@use std::collections::HashMap;use std::path::Path;-use worktrunk::config::{Command, CommandConfig, CommandPhase, WorktrunkConfig, expand_template};+use worktrunk::config::{+ Command, CommandConfig, CommandPhase, WorktrunkConfig, expand_template, sanitize_branch_name,+};use worktrunk::git::{Repository, WorktrunkError};use super::command_approval::approve_command_batch;@@ -9,6 +11,7 @@ use super::command_approval::approve_command_batch;pub struct PreparedCommand {pub name: Option<String>,pub expanded: String,+ pub context_json: String,}#[derive(Clone, Copy, Debug)]@@ -41,72 +44,89 @@ impl<'a> CommandContext<'a> {}}-/// Expand commands from a CommandConfig without approval+/// Build hook context as a HashMap for JSON serialization and template expansion.///-/// This is the canonical command expansion implementation.-/// Returns cloned commands with their expanded forms filled in.-fn expand_commands(- commands: &[Command],+/// The resulting HashMap is passed to hook commands as JSON on stdin,+/// and used directly for template variable expansion.+fn build_hook_context(ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],-) -> anyhow::Result<Vec<Command>> {- if commands.is_empty() {- return Ok(Vec::new());- }-+) -> HashMap<String, String> {let repo_root = ctx.repo_root;let repo_name = repo_root.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");- let mut extras_owned = HashMap::new();- extras_owned.insert(- "worktree".to_string(),- ctx.worktree_path.to_string_lossy().to_string(),- );- extras_owned.insert(- "repo_root".to_string(),- repo_root.to_string_lossy().to_string(),- );+ let worktree = ctx.worktree_path.to_string_lossy();+ let worktree_name = ctx+ .worktree_path+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("unknown");++ let mut map = HashMap::new();+ map.insert("repo".into(), repo_name.into());+ map.insert("branch".into(), sanitize_branch_name(ctx.branch));+ map.insert("worktree".into(), worktree.into());+ map.insert("worktree_name".into(), worktree_name.into());+ map.insert("repo_root".into(), repo_root.to_string_lossy().into());+if let Ok(default_branch) = ctx.repo.default_branch() {- extras_owned.insert("default_branch".to_string(), default_branch);+ map.insert("default_branch".into(), default_branch);}- // Git ref variablesif let Ok(commit) = ctx.repo.run_command(&["rev-parse", "HEAD"]) {let commit = commit.trim();- extras_owned.insert("commit".to_string(), commit.to_string());- // Short commit is first 7 characters+ map.insert("commit".into(), commit.into());if commit.len() >= 7 {- extras_owned.insert("short_commit".to_string(), commit[..7].to_string());+ map.insert("short_commit".into(), commit[..7].into());}}- // Remote variablesif let Ok(remote) = ctx.repo.primary_remote() {- extras_owned.insert("remote".to_string(), remote.clone());- // Upstream tracking branch (if configured)+ map.insert("remote".into(), remote);if let Ok(Some(upstream)) = ctx.repo.upstream_branch(ctx.branch) {- extras_owned.insert("upstream".to_string(), upstream);+ map.insert("upstream".into(), upstream);}}- // Worktree name (basename of worktree path)- if let Some(name) = ctx.worktree_path.file_name().and_then(|n| n.to_str()) {- extras_owned.insert("worktree_name".to_string(), name.to_string());+ // Add extra vars (e.g., target branch for merge)+ for (k, v) in extra_vars {+ map.insert((*k).into(), (*v).into());}- for &(key, value) in extra_vars {- extras_owned.insert(key.to_string(), value.to_string());+ map+}++/// Expand commands from a CommandConfig without approval+///+/// This is the canonical command expansion implementation.+/// Returns cloned commands with their expanded forms filled in, each with per-command JSON context.+fn expand_commands(+ commands: &[Command],+ ctx: &CommandContext<'_>,+ extra_vars: &[(&str, &str)],+) -> anyhow::Result<Vec<(Command, String)>> {+ if commands.is_empty() {+ return Ok(Vec::new());}- let extras_ref: HashMap<&str, &str> = extras_owned+ let base_context = build_hook_context(ctx, extra_vars);++ let repo_name = ctx+ .repo_root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("unknown");++ // Convert to &str references for expand_template+ let extras_ref: HashMap<&str, &str> = base_context.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();- let mut expanded_commands = Vec::new();+ let mut result = Vec::new();for cmd in commands {let expanded_str = expand_template(&cmd.template, repo_name, ctx.branch, &extras_ref)@@ -117,15 +137,28 @@ fn expand_commands(e)})?;- expanded_commands.push(Command::with_expansion(- cmd.name.clone(),- cmd.template.clone(),- expanded_str,- cmd.phase,++ // Build per-command JSON with hook_type and hook_name+ let mut cmd_context = base_context.clone();+ cmd_context.insert("hook_type".into(), cmd.phase.to_string());+ if let Some(ref name) = cmd.name {+ cmd_context.insert("hook_name".into(), name.clone());+ }+ let context_json = serde_json::to_string(&cmd_context)+ .expect("HashMap<String, String> serialization should never fail");++ result.push((+ Command::with_expansion(+ cmd.name.clone(),+ cmd.template.clone(),+ expanded_str,+ cmd.phase,+ ),+ context_json,));}- Ok(expanded_commands)+ Ok(result)}/// Prepare project commands for execution with approval@@ -133,7 +166,7 @@ fn expand_commands(/// This function:/// 1. Expands command templates with context variables/// 2. Requests user approval for unapproved commands (unless auto_trust or force)-/// 3. Returns prepared commands ready for execution+/// 3. Returns prepared commands ready for execution, each with JSON context for stdin////// Returns `Err(WorktrunkError::CommandNotApproved)` if the user declines approval.pub fn prepare_project_commands(@@ -151,7 +184,13 @@ pub fn prepare_project_commands(let project_id = ctx.repo.project_identifier()?;// Expand commands before approval for transparency- let expanded_commands = expand_commands(&commands, ctx, extra_vars)?;+ let expanded_with_json = expand_commands(&commands, ctx, extra_vars)?;++ // Extract just the commands for approval+ let expanded_commands: Vec<_> = expanded_with_json+ .iter()+ .map(|(cmd, _)| cmd.clone())+ .collect();// Flush stdout before prompting on stderr to ensure correct output ordering// This prevents the approval prompt from appearing before previous success messages@@ -170,11 +209,12 @@ pub fn prepare_project_commands(return Err(WorktrunkError::CommandNotApproved.into());}- Ok(expanded_commands+ Ok(expanded_with_json.into_iter()- .map(|cmd| PreparedCommand {+ .map(|(cmd, context_json)| PreparedCommand {name: cmd.name,expanded: cmd.expanded,+ context_json,}).collect())}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 88682e4e2..3fd5828fa 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -63,9 +63,11 @@ impl<'a> HookPipeline<'a> {crate::output::progress(format!("{label}:"))?;crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;- if let Err(err) =- execute_command_in_worktree(self.ctx.worktree_path, &prepared.expanded)- {+ if let Err(err) = execute_command_in_worktree(+ self.ctx.worktree_path,+ &prepared.expanded,+ Some(&prepared.context_json),+ ) {// Extract raw message and exit code from errorlet (err_msg, exit_code) =if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {@@ -153,6 +155,7 @@ impl<'a> HookPipeline<'a> {&prepared.expanded,self.ctx.branch,&operation,+ Some(&prepared.context_json),) {let err_msg = err.to_string();let message = match &prepared.name {diff --git a/src/commands/process.rs b/src/commands/process.rsindex a74523d24..f25b35afc 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -19,6 +19,7 @@ use worktrunk::path::format_path_for_display;/// * `command` - Shell command to execute/// * `branch` - Branch name for log organization/// * `name` - Operation identifier (e.g., "post-start-npm", "remove")+/// * `context_json` - Optional JSON context to pipe to command's stdin////// # Returns/// Path to the log file where output is being written@@ -28,6 +29,7 @@ pub fn spawn_detached(command: &str,branch: &str,name: &str,+ context_json: Option<&str>,) -> anyhow::Result<std::path::PathBuf> {// Get the git common directory (shared across all worktrees)let git_common_dir = repo.git_common_dir()?;@@ -58,12 +60,12 @@ pub fn spawn_detached(#[cfg(unix)]{- spawn_detached_unix(worktree_path, command, log_file)?;+ spawn_detached_unix(worktree_path, command, log_file, context_json)?;}#[cfg(windows)]{- spawn_detached_windows(worktree_path, command, log_file)?;+ spawn_detached_windows(worktree_path, command, log_file, context_json)?;}Ok(log_path)@@ -74,6 +76,7 @@ fn spawn_detached_unix(worktree_path: &Path,command: &str,log_file: fs::File,+ context_json: Option<&str>,) -> anyhow::Result<()> {// Detachment using nohup and background execution (&):// - nohup makes the process immune to SIGHUP (continues after parent exits)@@ -82,11 +85,35 @@ fn spawn_detached_unix(// - We wait for the outer shell to exit (happens immediately after backgrounding)// - This prevents zombie process accumulation under high concurrency// - Output redirected to log file for debugging++ // Build the command, optionally piping JSON context to stdin+ let full_command = match context_json {+ Some(json) => {+ // Use printf to pipe JSON to the command's stdin+ // printf is more portable than echo for arbitrary content+ // Wrap command in braces to ensure proper grouping with &&, ||, etc.+ // Only add semicolon if command doesn't already end with newline or semicolon+ // (shell syntax: `{ cmd\n }` is valid, but `{ cmd\n; }` is not)+ let separator = if command.ends_with('\n') || command.ends_with(';') {+ ""+ } else {+ ";"+ };+ format!(+ "printf '%s' {} | {{ {}{} }}",+ shell_escape::escape(json.into()),+ command,+ separator+ )+ }+ None => command.to_string(),+ };+let mut child = Command::new("sh").arg("-c").arg(format!("nohup sh -c {} &",- shell_escape::escape(command.into())+ shell_escape::escape(full_command.into()))).current_dir(worktree_path).stdin(Stdio::null())@@ -112,6 +139,7 @@ fn spawn_detached_windows(worktree_path: &Path,command: &str,log_file: fs::File,+ context_json: Option<&str>,) -> anyhow::Result<()> {use std::os::windows::process::CommandExt;@@ -120,9 +148,24 @@ fn spawn_detached_windows(const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;const DETACHED_PROCESS: u32 = 0x00000008;- Command::new("cmd")- .args(["/C", command])- .current_dir(worktree_path)+ // Build the command, optionally piping JSON context to stdin+ let full_command = match context_json {+ Some(json) => {+ // PowerShell single-quote escaping:+ // - Single quotes prevent variable expansion ($)+ // - Backticks need escaping even in single quotes (`` ` `` → ``` `` ```)+ // - Single quotes need doubling (`'` → `''`)+ let escaped_json = json.replace('`', "``").replace('\'', "''");+ // Pipe JSON to the command via PowerShell script block+ format!("'{}' | & {{ {} }}", escaped_json, command)+ }+ None => command.to_string(),+ };++ let mut cmd = Command::new("powershell");+ cmd.args(["-NoProfile", "-Command", &full_command]);++ cmd.current_dir(worktree_path).stdin(Stdio::null()).stdout(Stdio::from(log_filediff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 183bec633..666b613d1 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -470,7 +470,14 @@ fn handle_removed_worktree_output("Removing worktree in background (detached HEAD, no branch to delete)",)?;let remove_command = build_remove_command(worktree_path, None);- spawn_detached(&repo, main_path, &remove_command, "detached", "remove")?;+ spawn_detached(+ &repo,+ main_path,+ &remove_command,+ "detached",+ "remove",+ None,+ )?;} else {let target_repo = worktrunk::git::Repository::at(worktree_path);let _ = target_repo.run_command(&["fsmonitor--daemon", "stop"]);@@ -566,7 +573,14 @@ fn handle_removed_worktree_output(build_remove_command(worktree_path, should_delete_branch.then_some(branch_name));// Spawn the removal in background - runs from main_path (where we cd'd to)- spawn_detached(&repo, main_path, &remove_command, branch_name, "remove")?;+ spawn_detached(+ &repo,+ main_path,+ &remove_command,+ branch_name,+ "remove",+ None,+ )?;super::flush()?;Ok(())@@ -625,6 +639,8 @@ fn handle_removed_worktree_output(/// stdout into stderr. This ensures deterministic output ordering (all output flows through stderr)./// Per CLAUDE.md: child process output goes to stderr, worktrunk output goes to stdout.///+/// If `stdin_content` is provided, it will be piped to the command's stdin (used for hook context JSON).+////// Returns error if command exits with non-zero status.////// ## Signal Handling (Unix)@@ -638,7 +654,9 @@ pub(crate) fn execute_streaming(command: &str,working_dir: &std::path::Path,redirect_stdout_to_stderr: bool,+ stdin_content: Option<&str>,) -> anyhow::Result<()> {+ use std::io::Write;use std::process::Command;use worktrunk::git::WorktrunkError;@@ -650,11 +668,17 @@ pub(crate) fn execute_streaming(command.to_string()};+ let stdin_mode = if stdin_content.is_some() {+ std::process::Stdio::piped()+ } else {+ std::process::Stdio::null()+ };+let mut child = Command::new("sh").arg("-c").arg(&command_to_run).current_dir(working_dir)- .stdin(std::process::Stdio::null()) // Null stdin - child gets EOF immediately+ .stdin(stdin_mode).stdout(std::process::Stdio::inherit()) // Preserve TTY for output.stderr(std::process::Stdio::inherit()) // Preserve TTY for errors// Prevent vergen "overridden" warning in nested cargo builds when run via `cargo run`.@@ -667,6 +691,19 @@ pub(crate) fn execute_streaming(})})?;+ // Write stdin content if provided (used for hook context JSON)+ // We ignore write errors here because:+ // 1. The child may have already exited (broken pipe)+ // 2. Hooks that don't read stdin will still work+ // 3. Hooks that need stdin will fail with their own error message+ if let Some(content) = stdin_content+ && let Some(mut stdin) = child.stdin.take()+ {+ // Write and close stdin immediately so the child doesn't block waiting for more input+ let _ = stdin.write_all(content.as_bytes());+ // stdin is dropped here, closing the pipe+ }+// Wait for command to completelet status = child.wait().map_err(|e| {anyhow::Error::from(worktrunk::git::GitError::Other {@@ -704,6 +741,9 @@ pub(crate) fn execute_streaming(/// Merges stdout into stderr using shell redirection (1>&2) to ensure deterministic output ordering./// Per CLAUDE.md guidelines: child process output goes to stderr, worktrunk output goes to stdout.///+/// If `stdin_content` is provided, it will be piped to the command's stdin. This is used to pass+/// hook context as JSON to hook commands.+////// ## Color Bleeding Prevention////// This function explicitly resets ANSI codes on stderr before executing child commands.@@ -722,6 +762,7 @@ pub(crate) fn execute_streaming(pub fn execute_command_in_worktree(worktree_path: &std::path::Path,command: &str,+ stdin_content: Option<&str>,) -> anyhow::Result<()> {use std::io::Write;use worktrunk::styling::{eprint, stderr};@@ -737,7 +778,7 @@ pub fn execute_command_in_worktree(stderr().flush().ok(); // Ignore flush errors - reset is best-effort, command execution should proceed// Execute with stdout→stderr redirect for deterministic ordering- execute_streaming(command, worktree_path, true)?;+ execute_streaming(command, worktree_path, true, stdin_content)?;// Flush to ensure all output appears before we continuesuper::flush()?;diff --git a/src/output/interactive.rs b/src/output/interactive.rsindex 9bdf3e1c7..4a790c8b8 100644--- a/src/output/interactive.rs+++ b/src/output/interactive.rs@@ -82,7 +82,7 @@ impl OutputHandler for InteractiveOutput {fn execute(&mut self, command: String) -> anyhow::Result<()> {// On non-Unix platforms, fall back to spawn-and-waitlet exec_dir = self.target_dir.as_deref().unwrap_or_else(|| Path::new("."));- execute_streaming(&command, exec_dir, false)?;+ execute_streaming(&command, exec_dir, false, None)?;Ok(())}diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex ca7dcb29a..3a2be4d80 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -363,6 +363,256 @@ fn test_post_create_upstream_template() {);}+/// Test that hooks receive JSON context on stdin+#[test]+fn test_post_create_json_stdin() {+ use crate::common::wt_command;++ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with a command that reads JSON from stdin+ // Use cat to capture stdin to a file+ repo.write_project_config(r#"post-create = "cat > context.json""#);++ repo.commit("Add config");++ // Pre-approve the command+ repo.write_test_config(+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"++[projects."repo"]+approved-commands = ["cat > context.json"]+"#,+ );++ // Create worktree - this should pipe JSON to the hook's stdin+ let temp_home = TempDir::new().unwrap();+ let output = wt_command()+ .args(["switch", "--create", "feature-json"])+ .current_dir(repo.root_path())+ .env("HOME", temp_home.path())+ .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())+ .output()+ .expect("failed to run wt switch");++ assert!(+ output.status.success(),+ "wt switch should succeed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ // Find the worktree and read the JSON+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature-json");+ let json_file = worktree_path.join("context.json");++ assert!(+ json_file.exists(),+ "context.json should have been created from stdin"+ );++ let contents = fs::read_to_string(&json_file).unwrap();++ // Parse and verify the JSON contains expected fields+ let json: serde_json::Value = serde_json::from_str(&contents)+ .unwrap_or_else(|e| panic!("Should be valid JSON: {}\nContents: {}", e, contents));++ assert!(+ json.get("repo").is_some(),+ "JSON should contain 'repo' field"+ );+ assert!(+ json.get("branch").is_some(),+ "JSON should contain 'branch' field"+ );+ assert_eq!(+ json["branch"].as_str(),+ Some("feature-json"),+ "Branch should be sanitized (feature-json)"+ );+ assert!(+ json.get("worktree").is_some(),+ "JSON should contain 'worktree' field"+ );+ assert!(+ json.get("repo_root").is_some(),+ "JSON should contain 'repo_root' field"+ );+ assert_eq!(+ json["hook_type"].as_str(),+ Some("post-create"),+ "JSON should contain hook_type"+ );+}++/// Test that an actual script file can read JSON from stdin+#[test]+fn test_post_create_script_reads_json() {+ use crate::common::wt_command;+ use std::os::unix::fs::PermissionsExt;++ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create a scripts directory and a Python script that reads JSON from stdin+ let scripts_dir = repo.root_path().join("scripts");+ fs::create_dir_all(&scripts_dir).unwrap();++ let script_content = r#"#!/usr/bin/env python3+import json+import sys++ctx = json.load(sys.stdin)+with open('hook_output.txt', 'w') as f:+ f.write(f"repo={ctx['repo']}\n")+ f.write(f"branch={ctx['branch']}\n")+ f.write(f"hook_type={ctx['hook_type']}\n")+ f.write(f"hook_name={ctx.get('hook_name', 'unnamed')}\n")+"#;+ let script_path = scripts_dir.join("setup.py");+ fs::write(&script_path, script_content).unwrap();+ fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755)).unwrap();++ // Create project config that runs the script+ repo.write_project_config(+ r#"[post-create]+setup = "./scripts/setup.py"+"#,+ );++ repo.commit("Add setup script and config");++ // Pre-approve the command+ repo.write_test_config(+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"++[projects."repo"]+approved-commands = ["./scripts/setup.py"]+"#,+ );++ // Create worktree+ let temp_home = TempDir::new().unwrap();+ let output = wt_command()+ .args(["switch", "--create", "feature-script"])+ .current_dir(repo.root_path())+ .env("HOME", temp_home.path())+ .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())+ .output()+ .expect("failed to run wt switch");++ assert!(+ output.status.success(),+ "wt switch should succeed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ // Find the worktree and verify the script wrote the expected output+ let worktree_path = repo+ .root_path()+ .parent()+ .unwrap()+ .join("repo.feature-script");+ let output_file = worktree_path.join("hook_output.txt");++ assert!(+ output_file.exists(),+ "Script should have created hook_output.txt"+ );++ let contents = fs::read_to_string(&output_file).unwrap();+ assert!(+ contents.contains("repo=repo"),+ "Output should contain repo name: {}",+ contents+ );+ assert!(+ contents.contains("branch=feature-script"),+ "Output should contain branch: {}",+ contents+ );+ assert!(+ contents.contains("hook_type=post-create"),+ "Output should contain hook_type: {}",+ contents+ );+ assert!(+ contents.contains("hook_name=setup"),+ "Output should contain hook_name: {}",+ contents+ );+}++/// Test that background hooks also receive JSON context on stdin+#[test]+fn test_post_start_json_stdin() {+ use crate::common::wt_command;++ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with a background command that reads JSON from stdin+ repo.write_project_config(r#"post-start = "cat > context.json""#);++ repo.commit("Add config");++ // Pre-approve the command+ repo.write_test_config(+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"++[projects."repo"]+approved-commands = ["cat > context.json"]+"#,+ );++ // Create worktree+ let temp_home = TempDir::new().unwrap();+ let output = wt_command()+ .args(["switch", "--create", "bg-json"])+ .current_dir(repo.root_path())+ .env("HOME", temp_home.path())+ .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())+ .output()+ .expect("failed to run wt switch");++ assert!(+ output.status.success(),+ "wt switch should succeed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ // Find the worktree and wait for the background command to write the file+ let worktree_path = repo.root_path().parent().unwrap().join("repo.bg-json");+ let json_file = worktree_path.join("context.json");++ // Wait for file to exist and have content (cat creates empty file immediately)+ wait_for_file(&json_file, Duration::from_secs(5));++ // Give time for printf to pipe through+ thread::sleep(Duration::from_millis(500));++ let contents = fs::read_to_string(&json_file).unwrap();++ // Parse and verify the JSON+ let json: serde_json::Value = serde_json::from_str(&contents)+ .unwrap_or_else(|e| panic!("Should be valid JSON: {}\nContents: {}", e, contents));++ assert_eq!(+ json["branch"].as_str(),+ Some("bg-json"),+ "Background hook should receive JSON with branch"+ );+ assert!(+ json.get("repo").is_some(),+ "Background hook should receive JSON with repo"+ );+ assert_eq!(+ json["hook_type"].as_str(),+ Some("post-start"),+ "Background hook should receive hook_type"+ );+}+// ============================================================================// Post-Start Command Tests (parallel, background)// ============================================================================diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 45d9e4bdc..34464da6a 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -156,7 +156,7 @@ Create [2m.config/wt.toml[0m in the repository root:[2mtest = "npm test"[0m[2mlint = "npm run lint"[0m-See Hooks for complete documentation on hook types, execution order, and template variables.+See Hooks for complete documentation on hook types, execution order, template variables, and JSON context.[32mShell integration[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snapindex 6e719ee0f..d2899e287 100644--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap@@ -83,6 +83,8 @@ Manual merge workflow with review between steps:- [2mpre-merge[0m — Before pushing to target- [2mpost-merge[0m — After merge cleanup+Hooks receive context as JSON on stdin and support template variables.+[32mSee also[0m- wt merge — Runs commit → squash → rebase → hooks → push → cleanup automatically