Skip to content

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

feat: Add LLM integration for squash commit messages

Maximilian Roos67d0a4c9a295
diff --git a/fish-functions/README.md b/fish-functions/README.md
new file mode 100644
index 000000000..30a37117a
--- /dev/null
+++ b/fish-functions/README.md
@@ -0,0 +1,4 @@
+# Reference Fish Functions
+
+These fish functions are reference implementations showing the prior work that inspired the Rust `wt` tool.
+They are not part of the main project and have external dependencies on other fish functions not included here.
diff --git a/src/config.rs b/src/config.rs
index 59dc32892..fc0e999da 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -3,7 +3,7 @@ use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
-/// Configuration for worktree path formatting.
+/// Configuration for worktree path formatting and LLM integration.
///
/// The `worktree-path` template is relative to the repository root and supports:
/// - `{repo}` - Repository name
@@ -23,6 +23,11 @@ use std::path::PathBuf;
///
/// # Repository-namespaced shared directory (avoids conflicts)
/// worktree-path = "../worktrees/{repo}/{branch}"
+///
+/// # LLM configuration for commit message generation
+/// [llm]
+/// command = "llm" # Command to invoke LLM (e.g., "llm", "claude")
+/// args = ["-s"] # Arguments to pass to the command
/// ```
///
/// Config file location:
@@ -35,12 +40,37 @@ use std::path::PathBuf;
pub struct WorktrunkConfig {
#[serde(rename = "worktree-path")]
pub worktree_path: String,
+
+ #[serde(default)]
+ pub llm: LlmConfig,
+}
+
+/// Configuration for LLM integration
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct LlmConfig {
+ /// Command to invoke LLM (e.g., "llm", "claude")
+ #[serde(default)]
+ pub command: Option<String>,
+
+ /// Arguments to pass to the LLM command
+ #[serde(default)]
+ pub args: Vec<String>,
+}
+
+impl Default for LlmConfig {
+ fn default() -> Self {
+ Self {
+ command: None,
+ args: vec![],
+ }
+ }
}
impl Default for WorktrunkConfig {
fn default() -> Self {
Self {
worktree_path: "../{repo}.{branch}".to_string(),
+ llm: LlmConfig::default(),
}
}
}
@@ -52,7 +82,10 @@ fn get_config_path() -> Option<PathBuf> {
pub fn load_config() -> Result<WorktrunkConfig, ConfigError> {
let defaults = WorktrunkConfig::default();
- let mut builder = Config::builder().set_default("worktree-path", defaults.worktree_path)?;
+ let mut builder = Config::builder()
+ .set_default("worktree-path", defaults.worktree_path)?
+ .set_default("llm.command", defaults.llm.command.unwrap_or_default())?
+ .set_default("llm.args", defaults.llm.args)?;
// Add config file if it exists
if let Some(config_path) = get_config_path()
diff --git a/src/main.rs b/src/main.rs
index 8ceca20f3..e986fac6f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -796,6 +796,71 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
Ok(())
}
+fn generate_squash_message(
+ target_branch: &str,
+ subjects: &[String],
+ llm_config: &worktrunk::config::LlmConfig,
+) -> String {
+ // Try LLM generation if configured
+ if let Some(ref command) = llm_config.command {
+ if let Ok(llm_message) =
+ try_generate_llm_message(target_branch, subjects, command, &llm_config.args)
+ {
+ return llm_message;
+ }
+ // If LLM fails, fall through to deterministic approach
+ eprintln!("Warning: LLM generation failed, using deterministic message");
+ }
+
+ // Fallback: deterministic commit message
+ let mut commit_message = format!("Squash commits from {}\n\n", target_branch);
+ commit_message.push_str("Combined commits:\n");
+ for subject in subjects.iter().rev() {
+ // Reverse so they're in chronological order
+ commit_message.push_str(&format!("- {}\n", subject));
+ }
+ commit_message
+}
+
+fn try_generate_llm_message(
+ target_branch: &str,
+ subjects: &[String],
+ command: &str,
+ args: &[String],
+) -> Result<String, Box<dyn std::error::Error>> {
+ // Build context prompt
+ let mut context = format!(
+ "Squashing commits on current branch since branching from {}\n\n",
+ target_branch
+ );
+ context.push_str("Commits being combined:\n");
+ for subject in subjects.iter().rev() {
+ context.push_str(&format!("- {}\n", subject));
+ }
+
+ let prompt = "Generate a conventional commit message (feat/fix/docs/style/refactor) that combines these changes into one cohesive message. Output only the commit message without any explanation.";
+ let full_prompt = format!("{}\n\n{}", context, prompt);
+
+ // Execute LLM command
+ let output = process::Command::new(command)
+ .args(args)
+ .arg(&full_prompt)
+ .output()?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("LLM command failed: {}", stderr).into());
+ }
+
+ let message = String::from_utf8_lossy(&output.stdout).trim().to_string();
+
+ if message.is_empty() {
+ return Err("LLM returned empty message".into());
+ }
+
+ Ok(message)
+}
+
fn handle_squash(target_branch: &str) -> Result<(), GitError> {
// Get merge base with target branch
let merge_base = get_merge_base_in(Path::new("."), "HEAD", target_branch)?;
@@ -836,13 +901,10 @@ fn handle_squash(target_branch: &str) -> Result<(), GitError> {
let range = format!("{}..HEAD", merge_base);
let subjects = get_commit_subjects_in(Path::new("."), &range)?;
- // Build deterministic commit message
- let mut commit_message = format!("Squash commits from {}\n\n", target_branch);
- commit_message.push_str("Combined commits:\n");
- for subject in subjects.iter().rev() {
- // Reverse so they're in chronological order
- commit_message.push_str(&format!("- {}\n", subject));
- }
+ // Load config and generate commit message
+ let config = load_config()
+ .map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))?;
+ let commit_message = generate_squash_message(target_branch, &subjects, &config.llm);
// Reset to merge base (soft reset stages all changes)
let reset_result = process::Command::new("git")
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index aa36715bf..b1407f7c9 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -11,6 +11,24 @@ fn snapshot_merge(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&
});
}
+/// Helper to create snapshot with custom environment (for LLM testing)
+fn snapshot_merge_with_env(
+ test_name: &str,
+ repo: &TestRepo,
+ args: &[&str],
+ cwd: Option<&std::path::Path>,
+ env_vars: &[(&str, &str)],
+) {
+ let settings = setup_snapshot_settings(repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(repo, "merge", args, cwd);
+ for (key, value) in env_vars {
+ cmd.env(key, value);
+ }
+ assert_cmd_snapshot!(test_name, cmd);
+ });
+}
+
#[test]
fn test_merge_fast_forward() {
let mut repo = TestRepo::new();
@@ -229,3 +247,234 @@ fn test_merge_error_detached_head() {
Some(repo.root_path()),
);
}
+
+#[test]
+fn test_merge_squash_deterministic() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make multiple commits
+ let feature_wt = repo.add_worktree("feature", "feature");
+
+ std::fs::write(feature_wt.join("file1.txt"), "content 1").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file1.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "feat: add file 1"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ std::fs::write(feature_wt.join("file2.txt"), "content 2").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file2.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "fix: update logic"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ std::fs::write(feature_wt.join("file3.txt"), "content 3").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file3.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "docs: update readme"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Merge with squash (no LLM configured - should use deterministic message)
+ snapshot_merge(
+ "merge_squash_deterministic",
+ &repo,
+ &["main", "--squash"],
+ Some(&feature_wt),
+ );
+}
+
+#[test]
+fn test_merge_squash_with_llm() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make multiple commits
+ let feature_wt = repo.add_worktree("feature", "feature");
+
+ std::fs::write(feature_wt.join("auth.txt"), "auth module").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "auth.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "feat: add authentication"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ std::fs::write(feature_wt.join("auth.txt"), "auth module updated")
+ .expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "auth.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "fix: handle edge case"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Configure mock LLM command via environment variable
+ // Use echo to return a fixed message
+ snapshot_merge_with_env(
+ "merge_squash_with_llm",
+ &repo,
+ &["main", "--squash"],
+ Some(&feature_wt),
+ &[
+ ("WORKTRUNK_LLM__COMMAND", "echo"),
+ (
+ "WORKTRUNK_LLM__ARGS",
+ "feat: implement user authentication system",
+ ),
+ ],
+ );
+}
+
+#[test]
+fn test_merge_squash_llm_fallback() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make multiple commits
+ let feature_wt = repo.add_worktree("feature", "feature");
+
+ std::fs::write(feature_wt.join("file1.txt"), "content 1").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file1.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "feat: new feature"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ std::fs::write(feature_wt.join("file2.txt"), "content 2").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file2.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "fix: bug fix"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Configure LLM command that will fail (non-existent command)
+ // Should fall back to deterministic message and print warning
+ snapshot_merge_with_env(
+ "merge_squash_llm_fallback",
+ &repo,
+ &["main", "--squash"],
+ Some(&feature_wt),
+ &[("WORKTRUNK_LLM__COMMAND", "nonexistent-llm-command")],
+ );
+}
+
+#[test]
+fn test_merge_squash_single_commit() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree with only one commit
+ let feature_wt = repo.add_worktree("feature", "feature");
+
+ std::fs::write(feature_wt.join("file1.txt"), "content").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file1.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "feat: single commit"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Merge with squash - should skip squashing since there's only one commit
+ snapshot_merge(
+ "merge_squash_single_commit",
+ &repo,
+ &["main", "--squash"],
+ Some(&feature_wt),
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_squash_deterministic.snap b/tests/snapshots/integration__integration_tests__merge__merge_squash_deterministic.snap
new file mode 100644
index 000000000..b5a090239
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_squash_deterministic.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--squash"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Squashing 3 commits into one...
+Successfully squashed 3 commits into one
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Cleaning up worktree...
+Moved to primary worktree and removed worktree
+Path: [REPO]
+Note: Use 'wt remove' (with shell integration) for automatic cd
+
+----- stderr -----
+Warning: LLM generation failed, using deterministic message
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_squash_llm_fallback.snap b/tests/snapshots/integration__integration_tests__merge__merge_squash_llm_fallback.snap
new file mode 100644
index 000000000..2f75c24fa
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_squash_llm_fallback.snap
@@ -0,0 +1,36 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--squash"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+ WORKTRUNK_LLM__COMMAND: nonexistent-llm-command
+---
+success: true
+exit_code: 0
+----- stdout -----
+Squashing 2 commits into one...
+Successfully squashed 2 commits into one
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Cleaning up worktree...
+Moved to primary worktree and removed worktree
+Path: [REPO]
+Note: Use 'wt remove' (with shell integration) for automatic cd
+
+----- stderr -----
+Warning: LLM generation failed, using deterministic message
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_squash_single_commit.snap b/tests/snapshots/integration__integration_tests__merge__merge_squash_single_commit.snap
new file mode 100644
index 000000000..318bdc9cf
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_squash_single_commit.snap
@@ -0,0 +1,33 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--squash"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Only 1 commit since 'main' - no squashing needed
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Cleaning up worktree...
+Moved to primary worktree and removed worktree
+Path: [REPO]
+Note: Use 'wt remove' (with shell integration) for automatic cd
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_squash_with_llm.snap b/tests/snapshots/integration__integration_tests__merge__merge_squash_with_llm.snap
new file mode 100644
index 000000000..e27f3f8fc
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_squash_with_llm.snap
@@ -0,0 +1,37 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--squash"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+ WORKTRUNK_LLM__ARGS: "feat: implement user authentication system"
+ WORKTRUNK_LLM__COMMAND: echo
+---
+success: true
+exit_code: 0
+----- stdout -----
+Squashing 2 commits into one...
+Successfully squashed 2 commits into one
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Cleaning up worktree...
+Moved to primary worktree and removed worktree
+Path: [REPO]
+Note: Use 'wt remove' (with shell integration) for automatic cd
+
+----- stderr -----
+Warning: LLM generation failed, using deterministic message