Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

feat: add copy_files and init_script config for worktree initialization (#5)

Pablo Speciale1930897f9829
diff --git a/CLAUDE.md b/CLAUDE.md
index d0cb429..81ee39b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -61,7 +61,7 @@ Backlog β†’ Planning β†’ Running β†’ Review β†’ Done
```
- **Backlog**: Task ideas, not started
-- **Planning**: Creates git worktree at `.agtx/worktrees/{slug}`, starts Claude Code in planning mode
+- **Planning**: Creates git worktree at `.agtx/worktrees/{slug}`, copies configured files, runs init script, starts Claude Code in planning mode
- **Running**: Claude is implementing (sends "proceed with implementation")
- **Review**: Optionally create PR. Tmux window stays open. Can resume to address feedback
- **Done**: Cleanup worktree + tmux window (branch kept locally)
diff --git a/README.md b/README.md
index 93762a5..d25191d 100644
--- a/README.md
+++ b/README.md
@@ -102,6 +102,22 @@ color_accent = "#00FFFF"
color_description = "#E8909C"
```
+### Project Configuration
+
+Per-project settings can be placed in `.agtx/config.toml` at the project root:
+
+```toml
+# Files to copy from project root into each new worktree (comma-separated)
+# Paths are relative and preserve directory structure
+copy_files = ".env, .env.local, web/.env.local"
+
+# Shell command to run inside the worktree after creation and file copying
+init_script = "scripts/init_worktree.sh"
+```
+
+Both options run during the Backlog β†’ Planning transition, after `git worktree add`
+and before the agent session starts.
+
## How It Works
### Architecture
diff --git a/src/config/mod.rs b/src/config/mod.rs
index bb6b732..d521ead 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -183,6 +183,12 @@ pub struct ProjectConfig {
/// GitHub URL for this project
pub github_url: Option<String>,
+
+ /// Comma-separated list of files to copy from project root into worktrees
+ pub copy_files: Option<String>,
+
+ /// Shell command to run inside the worktree after creation and file copying
+ pub init_script: Option<String>,
}
impl GlobalConfig {
@@ -266,6 +272,8 @@ pub struct MergedConfig {
pub base_branch: String,
pub github_url: Option<String>,
pub theme: ThemeConfig,
+ pub copy_files: Option<String>,
+ pub init_script: Option<String>,
}
impl MergedConfig {
@@ -284,6 +292,8 @@ impl MergedConfig {
.unwrap_or_else(|| global.worktree.base_branch.clone()),
github_url: project.github_url.clone(),
theme: global.theme.clone(),
+ copy_files: project.copy_files.clone(),
+ init_script: project.init_script.clone(),
}
}
}
diff --git a/src/git/worktree.rs b/src/git/worktree.rs
index 45d121b..d5a6fd5 100644
--- a/src/git/worktree.rs
+++ b/src/git/worktree.rs
@@ -56,6 +56,85 @@ pub fn create_worktree(project_path: &Path, task_slug: &str) -> Result<PathBuf>
Ok(worktree_path)
}
+/// Initialize a worktree by copying files and running an init script.
+///
+/// Returns a Vec of warning messages for any issues encountered.
+/// Does not fail fatally β€” errors are collected and returned for the caller to display.
+pub fn initialize_worktree(
+ project_path: &Path,
+ worktree_path: &Path,
+ copy_files: Option<&str>,
+ init_script: Option<&str>,
+) -> Vec<String> {
+ let mut warnings = Vec::new();
+
+ if let Some(files_str) = copy_files {
+ for entry in files_str.split(',') {
+ let file_name = entry.trim();
+ if file_name.is_empty() {
+ continue;
+ }
+ let src = project_path.join(file_name);
+ let dst = worktree_path.join(file_name);
+
+ if let Some(parent) = dst.parent() {
+ if !parent.exists() {
+ if let Err(e) = std::fs::create_dir_all(parent) {
+ warnings.push(format!(
+ "Failed to create directory for '{}': {}",
+ file_name, e
+ ));
+ continue;
+ }
+ }
+ }
+
+ if !src.exists() {
+ warnings.push(format!(
+ "copy_files: '{}' not found in project root, skipping",
+ file_name
+ ));
+ continue;
+ }
+
+ if src.is_dir() {
+ warnings.push(format!(
+ "copy_files: '{}' is a directory, only individual files are supported",
+ file_name
+ ));
+ continue;
+ }
+
+ if let Err(e) = std::fs::copy(&src, &dst) {
+ warnings.push(format!("Failed to copy '{}' to worktree: {}", file_name, e));
+ }
+ }
+ }
+
+ if let Some(script) = init_script {
+ let script = script.trim();
+ if !script.is_empty() {
+ match Command::new("sh").arg("-c").arg(script).current_dir(worktree_path).output() {
+ Ok(result) => {
+ if !result.status.success() {
+ let stderr = String::from_utf8_lossy(&result.stderr);
+ warnings.push(format!(
+ "init_script exited with {}: {}",
+ result.status,
+ stderr.trim()
+ ));
+ }
+ }
+ Err(e) => {
+ warnings.push(format!("Failed to run init_script: {}", e));
+ }
+ }
+ }
+ }
+
+ warnings
+}
+
/// Detect the main branch name (main or master)
fn detect_main_branch(project_path: &Path) -> Result<String> {
// Check if 'main' exists
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 8023194..4e8e814 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -2250,6 +2250,17 @@ impl App {
};
let worktree_path_str = worktree_path.to_string_lossy().to_string();
+ // Initialize worktree: copy files and run init script
+ let init_warnings = git::initialize_worktree(
+ &project_path,
+ &worktree_path,
+ self.state.config.copy_files.as_deref(),
+ self.state.config.init_script.as_deref(),
+ );
+ for warning in &init_warnings {
+ eprintln!("Worktree init: {}", warning);
+ }
+
// Build the prompt from task title and description
// Instruct Claude to plan first and wait for approval
let task_content = if let Some(desc) = &task.description {
diff --git a/tests/config_tests.rs b/tests/config_tests.rs
index 953c133..8845817 100644
--- a/tests/config_tests.rs
+++ b/tests/config_tests.rs
@@ -74,6 +74,8 @@ fn test_project_config_default() {
assert!(config.default_agent.is_none());
assert!(config.base_branch.is_none());
assert!(config.github_url.is_none());
+ assert!(config.copy_files.is_none());
+ assert!(config.init_script.is_none());
}
// === MergedConfig Tests ===
@@ -89,6 +91,8 @@ fn test_merged_config_uses_global_defaults() {
assert_eq!(merged.base_branch, "main");
assert!(merged.worktree_enabled);
assert!(merged.auto_cleanup);
+ assert!(merged.copy_files.is_none());
+ assert!(merged.init_script.is_none());
}
#[test]
@@ -98,6 +102,8 @@ fn test_merged_config_project_overrides() {
default_agent: Some("codex".to_string()),
base_branch: Some("develop".to_string()),
github_url: Some("https://github.com/user/repo".to_string()),
+ copy_files: Some(".env, .env.local".to_string()),
+ init_script: Some("npm install".to_string()),
};
let merged = MergedConfig::merge(&global, &project);
@@ -105,4 +111,6 @@ fn test_merged_config_project_overrides() {
assert_eq!(merged.default_agent, "codex");
assert_eq!(merged.base_branch, "develop");
assert_eq!(merged.github_url, Some("https://github.com/user/repo".to_string()));
+ assert_eq!(merged.copy_files, Some(".env, .env.local".to_string()));
+ assert_eq!(merged.init_script, Some("npm install".to_string()));
}
diff --git a/tests/git_tests.rs b/tests/git_tests.rs
index b53fff6..8ed76eb 100644
--- a/tests/git_tests.rs
+++ b/tests/git_tests.rs
@@ -407,3 +407,161 @@ fn test_worktree_info_task_id_edge_cases() {
};
assert_eq!(info3.task_id(), None);
}
+
+// =============================================================================
+// initialize_worktree tests
+// =============================================================================
+
+#[test]
+fn test_initialize_worktree_no_config() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-none").unwrap();
+
+ let warnings = git::initialize_worktree(temp_dir.path(), &worktree_path, None, None);
+ assert!(warnings.is_empty());
+}
+
+#[test]
+fn test_initialize_worktree_copy_files() {
+ let temp_dir = setup_git_repo();
+ std::fs::write(temp_dir.path().join(".env"), "DB_URL=localhost").unwrap();
+ std::fs::write(temp_dir.path().join(".env.local"), "SECRET=abc").unwrap();
+
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-copy").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some(".env, .env.local"),
+ None,
+ );
+ assert!(warnings.is_empty());
+ assert_eq!(
+ std::fs::read_to_string(worktree_path.join(".env")).unwrap(),
+ "DB_URL=localhost"
+ );
+ assert_eq!(
+ std::fs::read_to_string(worktree_path.join(".env.local")).unwrap(),
+ "SECRET=abc"
+ );
+}
+
+#[test]
+fn test_initialize_worktree_copy_missing_file() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-missing").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some(".nonexistent"),
+ None,
+ );
+ assert_eq!(warnings.len(), 1);
+ assert!(warnings[0].contains(".nonexistent"));
+}
+
+#[test]
+fn test_initialize_worktree_init_script_success() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-script-ok").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ None,
+ Some("touch initialized.marker"),
+ );
+ assert!(warnings.is_empty());
+ assert!(worktree_path.join("initialized.marker").exists());
+}
+
+#[test]
+fn test_initialize_worktree_init_script_failure() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-script-fail").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ None,
+ Some("exit 1"),
+ );
+ assert_eq!(warnings.len(), 1);
+ assert!(warnings[0].contains("init_script"));
+}
+
+#[test]
+fn test_initialize_worktree_copy_then_script() {
+ let temp_dir = setup_git_repo();
+ std::fs::write(temp_dir.path().join(".env"), "KEY=value").unwrap();
+
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-order").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some(".env"),
+ Some("cat .env > verified.txt"),
+ );
+ assert!(warnings.is_empty());
+ assert_eq!(
+ std::fs::read_to_string(worktree_path.join("verified.txt")).unwrap(),
+ "KEY=value"
+ );
+}
+
+#[test]
+fn test_initialize_worktree_copy_nested_path() {
+ let temp_dir = setup_git_repo();
+ let web_dir = temp_dir.path().join("web");
+ std::fs::create_dir_all(&web_dir).unwrap();
+ std::fs::write(web_dir.join(".env.local"), "NEXT_PUBLIC_KEY=123").unwrap();
+
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-nested").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some("web/.env.local"),
+ None,
+ );
+ assert!(warnings.is_empty());
+ assert_eq!(
+ std::fs::read_to_string(worktree_path.join("web").join(".env.local")).unwrap(),
+ "NEXT_PUBLIC_KEY=123"
+ );
+}
+
+#[test]
+fn test_initialize_worktree_empty_copy_files() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-empty").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some(", , "),
+ None,
+ );
+ assert!(warnings.is_empty());
+}
+
+#[test]
+fn test_initialize_worktree_copy_directory_rejected() {
+ let temp_dir = setup_git_repo();
+ let config_dir = temp_dir.path().join("config");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ std::fs::write(config_dir.join("app.toml"), "key = 1").unwrap();
+
+ let worktree_path = git::create_worktree(temp_dir.path(), "init-dir").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some("config"),
+ None,
+ );
+ assert_eq!(warnings.len(), 1);
+ assert!(warnings[0].contains("directory"));
+}