Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Build the commit prompt from the worktree being committed (#3996)
Maximilian Roos38c8100527c1
diff --git a/docs/src/content/docs/step.md b/docs/src/content/docs/step.mdindex 692184b2d..aec54033f 100644--- a/docs/src/content/docs/step.md+++ b/docs/src/content/docs/step.md@@ -113,7 +113,7 @@ See [LLM-generated commit messages](/llm-commits/) for configuration and prompt$ wt step commit --branch feature```-The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It has no effect on `--dry-run`, which always previews the current worktree.+The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It selects the previewed worktree the same way, so `--dry-run` describes the commit the same flags would make.### Hooksdiff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.mdindex bd4eccc59..54a8e5a97 100644--- a/plugins/worktrunk/skills/worktrunk/reference/step.md+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md@@ -101,7 +101,7 @@ See [LLM-generated commit messages](https://worktrunk.dev/llm-commits/) for conf$ wt step commit --branch feature```-The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It has no effect on `--dry-run`, which always previews the current worktree.+The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It selects the previewed worktree the same way, so `--dry-run` describes the commit the same flags would make.### Hooksdiff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex bd4eccc59..54a8e5a97 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -101,7 +101,7 @@ See [LLM-generated commit messages](https://worktrunk.dev/llm-commits/) for conf$ wt step commit --branch feature```-The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It has no effect on `--dry-run`, which always previews the current worktree.+The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It selects the previewed worktree the same way, so `--dry-run` describes the commit the same flags would make.### Hooksdiff --git a/src/cli/step.rs b/src/cli/step.rsindex 43c59f0ca..eb915fefd 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -79,7 +79,7 @@ pub enum StepCommand {$ wt step commit --branch feature```-The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It has no effect on `--dry-run`, which always previews the current worktree.+The branch must have a checked-out worktree. `--branch` re-roots the whole command: staging, hooks, and the commit all happen there. It selects the previewed worktree the same way, so `--dry-run` describes the commit the same flags would make.## Hooksdiff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 67a25cb57..6ca9a03c1 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -148,9 +148,7 @@ impl<'a> CommitGenerator<'a> {}if show_progress {- let stats_parts = wt- .repo()- .diff_stats_summary(&["diff", "--staged", "--shortstat"]);+ let stats_parts = wt.diff_stats_summary(&["diff", "--staged", "--shortstat"]);let changes_type = match stage_mode {StageMode::Tracked => "tracked changes",@@ -184,8 +182,11 @@ impl<'a> CommitGenerator<'a> {}self.emit_hint_if_needed();+ // `wt` — not the invoking worktree: `--branch <b>` and `step relocate+ // --commit` both commit elsewhere, and the prompt must describe the+ // diff that is about to be committed.let commit_message =- crate::llm::generate_commit_message(self.config, None, self.project_append)?;+ crate::llm::generate_commit_message(self.config, wt, None, self.project_append)?;let formatted_message = self.format_message_for_display(&commit_message);eprintln!("{}", format_with_gutter(&formatted_message, None));diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsindex d7987e2c5..a318f632a 100644--- a/src/commands/step/commit.rs+++ b/src/commands/step/commit.rs@@ -26,7 +26,7 @@ pub fn step_commit(// mirrors --stage against a temp index so the previewed prompt matches what a real// run would send the LLM. Neither path produces a CommitOutcome.if show_prompt || dry_run {- preview_commit(stage, dry_run, yes)?;+ preview_commit(branch.as_deref(), stage, dry_run, yes)?;return Ok(None);}@@ -35,10 +35,7 @@ pub fn step_commit(// One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = match branch {- Some(ref b) => CommandEnv::for_selector(config, b)?,- None => CommandEnv::for_action(config)?,- };+ let env = resolve_env(config, branch.as_deref())?;let ctx = env.context(yes);// CLI flag overrides config value@@ -65,6 +62,16 @@ pub fn step_commit(Ok(Some(outcome))}+/// Resolve the environment `wt step commit` acts in: the worktree named by+/// `--branch`, or the invoking one. `for_selector` re-roots `repo` at that+/// worktree, so the commit, its hooks, and its project config all follow.+fn resolve_env(config: UserConfig, branch: Option<&str>) -> anyhow::Result<CommandEnv> {+ match branch {+ Some(b) => CommandEnv::for_selector(config, b),+ None => CommandEnv::for_action(config),+ }+}+/// Handle `wt step commit` in `--show-prompt` or `--dry-run` mode.////// Both modes skip hooks and the commit itself. `--show-prompt` outputs only the@@ -72,9 +79,18 @@ pub fn step_commit(/// `--stage` against a temp index — so the previewed prompt matches what a real run/// would send — then calls the LLM and prints the command and message in three labeled/// sections. The user's real index is never modified.-fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow::Result<()> {- let env = CommandEnv::for_action(UserConfig::load().context("Failed to load config")?)?;+///+/// `branch` selects the previewed worktree exactly as it selects the committed+/// one, so a preview describes the commit the same flags would make.+fn preview_commit(+ branch: Option<&str>,+ stage: Option<StageMode>,+ dry_run: bool,+ yes: bool,+) -> anyhow::Result<()> {+ let env = resolve_env(UserConfig::load().context("Failed to load config")?, branch)?;let commit_config = env.resolved().commit_generation.clone();+ let wt = env.repo.worktree_at(&env.worktree_path);// For --dry-run, stage to a copy of the index so the preview reflects what a real// run would send. --show-prompt skips this — it's the cheap "what's already staged"@@ -83,7 +99,7 @@ fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow:let temp_index = if dry_run {(stage_mode != StageMode::None).then(|| {- let temp = env.repo.current_worktree().temp_index()?;+ let temp = wt.temp_index()?;temp.stage(stage_mode)?;Ok::<_, anyhow::Error>(temp)})@@ -96,14 +112,19 @@ fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow:let ctx = env.context(yes);let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;- let prompt =- crate::llm::build_commit_prompt(&commit_config, index_override, project_append.as_deref())?;+ let prompt = crate::llm::build_commit_prompt(+ &commit_config,+ &wt,+ index_override,+ project_append.as_deref(),+ )?;if !dry_run {println!("{}", prompt);return Ok(());}let message = crate::llm::generate_commit_message(&commit_config,+ &wt,index_override,project_append.as_deref(),)?;diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex 9dcbda591..cedb70fea 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -226,9 +226,9 @@ pub fn handle_squash(// Get total stats (commits + any working tree changes)let total_stats = if has_staged {- repo.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])+ wt.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])} else {- repo.diff_stats_summary(&["diff", "--shortstat", &range])+ wt.diff_stats_summary(&["diff", "--shortstat", &range])};let with_changes = if has_staged {diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex 4150fa4ec..54ce02bc4 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -197,7 +197,7 @@ impl MergeContext {let commit_count = repo.count_commits(&target_branch, "HEAD")?;let stats_summary = if commit_count > 0 {- repo.diff_stats_summary(&[+ repo.current_worktree().diff_stats_summary(&["diff","--shortstat","--end-of-options",diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex 1e1ce6ee4..a4e438295 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -159,6 +159,60 @@ impl<'repo> WorkingTree<'repo> {index.register_untracked()?;Ok(PreparedDiff::with_temp_index(index, revisions))}++ /// Get recent commit subjects for style reference.+ ///+ /// Returns up to `count` commit subjects (first line of message), excluding merges.+ /// If `start_ref` is provided, gets commits starting from that ref.+ /// Returns `None` if no commits are found or the command fails.+ ///+ /// Lives on the worktree, not the repository: without `start_ref` this+ /// walks back from HEAD, and HEAD is per-worktree. Asking the repository+ /// would answer for whichever worktree it was discovered from — the+ /// invoking one, which is the wrong branch's history whenever the command+ /// acts on another worktree (`wt step commit --branch <b>`).+ pub fn recent_commit_subjects(+ &self,+ start_ref: Option<&str>,+ count: usize,+ ) -> Option<Vec<String>> {+ let count_str = count.to_string();+ let mut args = vec![+ "log",+ "--pretty=format:%s",+ "--no-show-signature",+ "-n",+ &count_str,+ "--no-merges",+ ];+ if let Some(ref_name) = start_ref {+ args.push("--end-of-options");+ args.push(ref_name);+ }+ self.run_command(&args).ok().and_then(|output| {+ if output.trim().is_empty() {+ None+ } else {+ Some(output.lines().map(String::from).collect())+ }+ })+ }++ /// Get formatted diff stats summary for display.+ ///+ /// Returns a vector of formatted strings like ["3 files", "+45", "-12"].+ /// Returns empty vector if diff command fails or produces no output.+ ///+ /// Callers pass args including `--shortstat` which produces a single summary line.+ ///+ /// Worktree-scoped for the same reason as [`Self::recent_commit_subjects`]:+ /// every caller diffs the index or HEAD, both of which are per-worktree.+ pub fn diff_stats_summary(&self, args: &[&str]) -> Vec<String> {+ self.run_command(args)+ .ok()+ .map(|output| DiffStats::from_shortstat(&output).format_summary())+ .unwrap_or_default()+ }}/// Subject and body for one commit in a range.@@ -338,38 +392,6 @@ impl Repository {parse_commit_message_details_output(&output)}- /// Get recent commit subjects for style reference.- ///- /// Returns up to `count` commit subjects (first line of message), excluding merges.- /// If `start_ref` is provided, gets commits starting from that ref.- /// Returns `None` if no commits are found or the command fails.- pub fn recent_commit_subjects(- &self,- start_ref: Option<&str>,- count: usize,- ) -> Option<Vec<String>> {- let count_str = count.to_string();- let mut args = vec![- "log",- "--pretty=format:%s",- "--no-show-signature",- "-n",- &count_str,- "--no-merges",- ];- if let Some(ref_name) = start_ref {- args.push("--end-of-options");- args.push(ref_name);- }- self.run_command(&args).ok().and_then(|output| {- if output.trim().is_empty() {- None- } else {- Some(output.lines().map(String::from).collect())- }- })- }-/// Get the merge base between two commits.////// Returns `Ok(Some(sha))` if a merge base exists, `Ok(None)` for orphan branches@@ -596,23 +618,20 @@ impl Repository {}Ok(result)}-- /// Get formatted diff stats summary for display.- ///- /// Returns a vector of formatted strings like ["3 files", "+45", "-12"].- /// Returns empty vector if diff command fails or produces no output.- ///- /// Callers pass args including `--shortstat` which produces a single summary line.- pub fn diff_stats_summary(&self, args: &[&str]) -> Vec<String> {- self.run_command(args)- .ok()- .map(|output| DiffStats::from_shortstat(&output).format_summary())- .unwrap_or_default()- }}#[cfg(test)]mod tests {+ use crate::testing::TestRepo;++ #[test]+ fn recent_commit_subjects_with_zero_count_is_none() {+ let test_repo = TestRepo::with_initial_commit();+ let wt = test_repo.repo.current_worktree();++ assert_eq!(wt.recent_commit_subjects(None, 0), None);+ }+#[test]fn parse_commit_message_details_output_rejects_odd_field_count() {let err =diff --git a/src/llm.rs b/src/llm.rsindex 1e2642363..a870715e2 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -5,7 +5,7 @@ use std::fmt;use std::path::Path;use std::sync::Arc;use worktrunk::config::CommitGenerationConfig;-use worktrunk::git::{CommandError, CommitMessageDetail, ErrorExt, Repository};+use worktrunk::git::{CommandError, CommitMessageDetail, ErrorExt, Repository, WorkingTree};use worktrunk::shell_exec::{Cmd, ShellConfig};use minijinja::Environment;@@ -692,6 +692,11 @@ fn build_prompt(Ok(rendered)}+/// `wt` is the worktree being committed — the diff, branch, and history all+/// come from there. It is not always the invoking worktree: `wt step commit+/// --branch <b>` and `wt step relocate --commit` commit somewhere else, and+/// reading the diff from the cwd instead handed the LLM an empty diff.+////// `index_override` is forwarded to git operations that read the staging area, so/// `--dry-run` can preview against a temp index without touching the user's real one.///@@ -702,6 +707,7 @@ fn build_prompt(/// separately into `<user-guidance>`.pub(crate) fn generate_commit_message(commit_generation_config: &CommitGenerationConfig,+ wt: &WorkingTree<'_>,index_override: Option<&Path>,project_append: Option<&str>,) -> anyhow::Result<String> {@@ -711,7 +717,8 @@ pub(crate) fn generate_commit_message(// Prompt-build failures (git plumbing) propagate as-is; only a// failure of the LLM command itself gets the `LlmCommandFailed`// wrapper — mirroring `generate_squash_message`.- let prompt = build_commit_prompt(commit_generation_config, index_override, project_append)?;+ let prompt =+ build_commit_prompt(commit_generation_config, wt, index_override, project_append)?;// A slow or hung command is otherwise silent (stdout is captured); the// watchdog surfaces a "still waiting" status. Held until this function// returns, clearing the block before the caller prints the message.@@ -731,10 +738,9 @@ pub(crate) fn generate_commit_message(}// Fallback: generate a descriptive commit message based on changed files- let repo = Repository::current()?;let file_list = run_git_capture(&["diff", "--staged", "--name-only", "-z"],- repo.discovery_path(),+ wt.path(),index_override,)?;let staged_files = file_list@@ -793,16 +799,19 @@ fn run_git_capture(/// the prompt template. Used by normal commit generation, `--show-prompt`, and/// `--dry-run`.///+/// Every input is read from `wt`, the worktree being committed — which is not+/// always the invoking one (see [`generate_commit_message`]).+////// `index_override` points git at an alternate index via `GIT_INDEX_FILE` — used by/// `--dry-run` to preview what `git add` per the user's `--stage` flag would produce/// without modifying the real index.pub(crate) fn build_commit_prompt(config: &CommitGenerationConfig,+ wt: &WorkingTree<'_>,index_override: Option<&Path>,project_append: Option<&str>,) -> anyhow::Result<String> {- let repo = Repository::current()?;- let cwd = repo.discovery_path();+ let cwd = wt.path();let mut diff_args: Vec<&str> = DIFF_PREFIX_OVERRIDES.to_vec();diff_args.extend(["--no-pager", "diff", "--staged"]);@@ -816,8 +825,7 @@ pub(crate) fn build_commit_prompt(// Prepare diff (may filter if too large)let prepared = prepare_diff(diff_output, diff_stat);- // Get current branch and repo root- let wt = repo.current_worktree();+ // Get the committed branch and its worktree rootlet current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());let repo_root = wt.root()?;let repo_name = repo_root@@ -825,7 +833,7 @@ pub(crate) fn build_commit_prompt(.and_then(|n| n.to_str()).unwrap_or("repo");- let recent_commits = repo.recent_commit_subjects(None, 5);+ let recent_commits = wt.recent_commit_subjects(None, 5);let context = PromptContext {git_diff: &prepared.diff,@@ -913,7 +921,9 @@ pub(crate) fn build_squash_prompt(// Prepare diff (may filter if too large)let prepared = prepare_diff(diff_output, diff_stat);- let recent_commits = repo.recent_commit_subjects(Some(merge_base), 5);+ let recent_commits = repo+ .current_worktree()+ .recent_commit_subjects(Some(merge_base), 5);let context = PromptContext {git_diff: &prepared.diff,git_diff_stat: &prepared.stat,@@ -1032,6 +1042,29 @@ mod tests {);}+ /// Git failures while constructing a configured prompt surface directly;+ /// they must not be mislabeled as a failure of the configured LLM command.+ #[test]+ fn test_generate_commit_message_propagates_prompt_error() {+ let test_repo = worktrunk::testing::TestRepo::with_initial_commit();+ let missing_path = test_repo.path().join("missing-worktree");+ let wt = test_repo.repo.worktree_at(missing_path);+ let config = CommitGenerationConfig {+ command: Some("exit 99".to_string()),+ ..Default::default()+ };++ let err = generate_commit_message(&config, &wt, None, None).unwrap_err();++ assert!(+ !matches!(+ err.downcast_ref::<worktrunk::git::GitError>(),+ Some(worktrunk::git::GitError::LlmCommandFailed { .. })+ ),+ "prompt-construction error was mislabeled as an LLM command failure: {err:#}"+ );+ }+/// A failing LLM command must surface as a typed [`CommandError`] carrying/// the exit code and captured output — `LlmCommandFailed` and the summary/// pane read the detail via `display_message`.diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 169f4d038..619f99f73 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -3154,6 +3154,92 @@ command = "cat >/dev/null; echo 'simulated LLM failure' >&2 && exit 1");}+// =============================================================================+// --branch (commit another worktree) tests+// =============================================================================++/// `wt step commit --branch <b>` commits `<b>`'s worktree, so every prompt+/// input must come from there. Reading the diff from the invoking worktree —+/// clean, since the changes are in `<b>` — sent the generator an empty+/// `<diff>`, and the model's "I don't see any staged changes" reply became the+/// commit message over a full set of files.+#[rstest]+fn test_step_commit_branch_prompt_reads_target_worktree(mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");++ // The work is in the feature worktree only; the invoking worktree stays clean.+ fs::write(feature_wt.join("feature_only.txt"), "line one\nline two\n").unwrap();++ // The mock generator saves its prompt outside both worktrees, so `--stage=all`+ // can't sweep the capture into the commit under test.+ let captured = repo.home_path().join("captured-prompt.txt");+ repo.write_test_config(&format!(+ r#"+[commit.generation]+command = "cat > {} && echo 'feat: mock message'"+"#,+ captured.to_slash_lossy()+ ));++ let output = repo+ .wt_command()+ .args(["step", "commit", "--branch", "feature", "--no-hooks"])+ .output()+ .expect("wt step commit --branch failed to spawn");+ assert!(+ output.status.success(),+ "commit failed; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr),+ );++ let prompt = fs::read_to_string(&captured).expect("generator received no prompt");+ assert!(+ prompt.contains("feature_only.txt") && prompt.contains("+line one"),+ "the prompt must carry the target worktree's staged diff; got:\n{prompt}"+ );+ assert!(+ prompt.contains("Branch: feature"),+ "the prompt must name the committed branch; got:\n{prompt}"+ );++ // The generated message landed on the commit the prompt described.+ let message = repo+ .git_command()+ .args(["log", "-1", "--format=%s"])+ .current_dir(&feature_wt)+ .run()+ .unwrap();+ assert_eq!(+ String::from_utf8_lossy(&message.stdout).trim(),+ "feat: mock message"+ );+}++/// `--show-prompt` previews what a real run would send, so `--branch` selects+/// the previewed worktree exactly as it selects the committed one.+#[rstest]+fn test_step_commit_show_prompt_branch_previews_target_worktree(mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");++ // --show-prompt previews the existing index, so stage in the target worktree.+ fs::write(feature_wt.join("feature_only.txt"), "line one\n").unwrap();+ repo.run_git_in(&feature_wt, &["add", "feature_only.txt"]);++ let output = make_snapshot_cmd(+ &repo,+ "step",+ &["commit", "--show-prompt", "--branch", "feature"],+ None,+ )+ .output()+ .expect("wt step commit --show-prompt --branch failed to spawn");+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("feature_only.txt") && stdout.contains("Branch: feature"),+ "the preview must describe the target worktree; got:\n{stdout}"+ );+}+// =============================================================================// step rebase tests// =============================================================================diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rsindex 9375b3ba6..e8e94754e 100644--- a/tests/integration_tests/step_relocate.rs+++ b/tests/integration_tests/step_relocate.rs@@ -2,6 +2,7 @@use crate::common::{TestRepo, configure_directive_file, directive_file, make_snapshot_cmd, repo};use insta_cmd::assert_cmd_snapshot;+use path_slash::PathExt as _;use rstest::rstest;use std::fs;use std::path::Path;@@ -304,11 +305,18 @@ fn test_relocate_dirty_with_commit(repo: TestRepo) {// Make uncommitted changesfs::write(wrong_path.join("dirty.txt"), "uncommitted changes").unwrap();- // Configure mock LLM command via config file- let worktrunk_config = r#"+ // Configure mock LLM command via config file. It saves the prompt so the+ // assertion below can check which worktree the diff came from: `relocate`+ // commits worktrees other than the invoking one, and reading the diff from+ // the cwd (clean here) would describe nothing.+ let captured = repo.home_path().join("captured-prompt.txt");+ let worktrunk_config = format!(+ r#"[commit.generation]-command = "cat >/dev/null && echo 'chore: auto-commit before relocate'"-"#;+command = "cat > {} && echo 'chore: auto-commit before relocate'"+"#,+ captured.to_slash_lossy()+ );fs::write(repo.test_config_path(), worktrunk_config).unwrap();// Relocate with --commit should commit then move@@ -331,6 +339,13 @@ command = "cat >/dev/null && echo 'chore: auto-commit before relocate'""Old worktree path should no longer exist: {}",wrong_path.display());++ // The generator described the committed worktree, not the invoking one.+ let prompt = fs::read_to_string(&captured).expect("generator received no prompt");+ assert!(+ prompt.contains("dirty.txt") && prompt.contains("+uncommitted changes"),+ "the prompt must carry the committed worktree's diff; got:\n{prompt}"+ );}/// Create a worktree for `branch` at `path`, stopped on an unresolved