1use anyhow::{Context, Result, anyhow};
9use std::path::{Path, PathBuf};
10
11use super::worktree::git_command_at;
12use super::{DiffVerifier, WorktreeManager};
13
14fn validate_git_ref(value: &str, role: &str) -> Result<()> {
20 let bad = value.is_empty()
21 || value == "."
22 || value.starts_with('-')
23 || value.starts_with('/')
24 || value.starts_with("./")
25 || value.contains("..")
26 || value.ends_with('/')
27 || value.ends_with(".lock")
28 || value.chars().any(|c| c.is_whitespace() || c.is_control())
29 || value.chars().any(|c| matches!(c, ':' | '?' | '*' | '[' | '~' | '^' | '\\'));
30 if bad {
31 return Err(anyhow!("invalid git {role}: {value:?}"));
32 }
33 Ok(())
34}
35
36#[derive(Debug, Clone)]
40pub struct ReconcileResult {
41 pub approved: bool,
43 pub merged: bool,
45 pub issues: Vec<String>,
47 pub reasoning: String,
49}
50
51pub struct WorktreeReconciler {
59 workspace_root: PathBuf,
60 main_branch: String,
61}
62
63impl WorktreeReconciler {
64 pub fn new(workspace_root: impl Into<PathBuf>, main_branch: &str) -> Self {
68 Self {
69 workspace_root: workspace_root.into(),
70 main_branch: if main_branch.is_empty() {
71 "main".to_string()
72 } else {
73 main_branch.to_string()
74 },
75 }
76 }
77
78 pub fn branch_name(worktree_name: &str) -> String {
80 format!("loop/{worktree_name}")
81 }
82
83 fn run_git_diff(&self, base: &str, head: &str, extra_args: &[&str]) -> Result<String> {
87 validate_git_ref(base, "base")?;
88 validate_git_ref(head, "head")?;
89 let range = format!("{base}...{head}");
90 let mut args = vec!["diff"];
91 args.extend_from_slice(extra_args);
92 args.push(&range);
93
94 let (_dir_handle, mut command) = git_command_at(&self.workspace_root)?;
95 let output = command.args(&args).output().context("Failed to run git diff")?;
96
97 if !output.status.success() {
98 let stderr = String::from_utf8_lossy(&output.stderr);
99 return Err(anyhow!("git diff failed: {}", stderr.trim()));
100 }
101
102 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
103 }
104
105 pub fn git_diff(&self, base: &str, head: &str) -> Result<String> {
107 self.run_git_diff(base, head, &[])
108 }
109
110 pub fn git_diff_name_only(&self, base: &str, head: &str) -> Result<Vec<PathBuf>> {
112 let stdout = self.run_git_diff(base, head, &["--name-only"])?;
113 Ok(stdout
114 .lines()
115 .filter(|l| !l.trim().is_empty())
116 .map(|l| PathBuf::from(l.trim()))
117 .collect())
118 }
119
120 pub fn git_diff_stat(&self, base: &str, head: &str) -> Result<String> {
122 self.run_git_diff(base, head, &["--stat"])
123 }
124
125 pub fn branch_has_commits(&self, base: &str, head: &str) -> Result<bool> {
127 validate_git_ref(base, "base")?;
128 validate_git_ref(head, "head")?;
129 let range = format!("{base}..{head}");
130 let (_dir_handle, mut command) = git_command_at(&self.workspace_root)?;
131 let output = command
132 .args(["log", "--oneline", &range])
133 .output()
134 .context("Failed to run git log")?;
135
136 if !output.status.success() {
137 let stderr = String::from_utf8_lossy(&output.stderr);
138 return Err(anyhow!("git log failed: {}", stderr.trim()));
139 }
140
141 Ok(!output.stdout.is_empty())
142 }
143
144 pub fn git_merge(&self, branch: &str) -> Result<()> {
147 validate_git_ref(branch, "branch")?;
148 let (_dir_handle, mut command) = git_command_at(&self.workspace_root)?;
150 let ff_output = command
151 .args(["merge", "--ff-only", branch])
152 .output()
153 .context("Failed to run git merge --ff-only")?;
154
155 if ff_output.status.success() {
156 return Ok(());
157 }
158
159 let (_dir_handle, mut command) = git_command_at(&self.workspace_root)?;
161 let output = command.args(["merge", branch]).output().context("Failed to run git merge")?;
162
163 if !output.status.success() {
164 let (_dir_handle, mut command) = git_command_at(&self.workspace_root)?;
166 let abort_output = command.args(["merge", "--abort"]).output();
167 match abort_output {
168 Ok(o) if !o.status.success() => {
169 tracing::warn!(
170 stderr = %String::from_utf8_lossy(&o.stderr),
171 "git merge --abort failed; repo may be in a dirty state"
172 );
173 }
174 Err(e) => {
175 tracing::warn!(error = %e, "Failed to spawn git merge --abort");
176 }
177 _ => {}
178 }
179 let stderr = String::from_utf8_lossy(&output.stderr);
180 return Err(anyhow!("git merge failed: {}", stderr.trim()));
181 }
182
183 Ok(())
184 }
185
186 pub fn git_branch_delete(&self, branch: &str) -> Result<()> {
188 validate_git_ref(branch, "branch")?;
189 let (_dir_handle, mut command) = git_command_at(&self.workspace_root)?;
190 let output = command
191 .args(["branch", "-d", branch])
192 .output()
193 .context("Failed to run git branch -d")?;
194
195 if !output.status.success() {
196 let stderr = String::from_utf8_lossy(&output.stderr);
197 return Err(anyhow!("git branch -d failed: {}", stderr.trim()));
198 }
199
200 Ok(())
201 }
202
203 pub fn is_worktree_clean(&self, worktree_path: &Path) -> Result<bool> {
205 let (_dir_handle, mut command) = git_command_at(worktree_path)?;
206 let output = command
207 .args(["status", "--porcelain"])
208 .output()
209 .context("Failed to run git status")?;
210
211 if !output.status.success() {
212 let stderr = String::from_utf8_lossy(&output.stderr);
213 return Err(anyhow!("git status failed: {}", stderr.trim()));
214 }
215
216 Ok(output.stdout.is_empty())
217 }
218
219 pub fn reconcile(
234 &self,
235 worktree_name: &str,
236 worktree_path: &Path,
237 verifier: &(dyn DiffVerifier + Send + Sync),
238 ) -> Result<ReconcileResult> {
239 let branch = Self::branch_name(worktree_name);
240 validate_git_ref(&branch, "branch")?;
241
242 if !self.is_worktree_clean(worktree_path)? {
244 return Ok(ReconcileResult {
245 approved: false,
246 merged: false,
247 issues: vec!["Worktree has uncommitted changes".to_string()],
248 reasoning: "Subagent did not commit all changes before completing.".to_string(),
249 });
250 }
251
252 if !self.branch_has_commits(&self.main_branch, &branch)? {
254 return Ok(ReconcileResult {
255 approved: true,
256 merged: false,
257 issues: Vec::new(),
258 reasoning: "No commits on branch; nothing to merge.".to_string(),
259 });
260 }
261
262 let diff_text = self.git_diff(&self.main_branch, &branch)?;
264 let changed_files = self.git_diff_name_only(&self.main_branch, &branch)?;
265
266 if diff_text.trim().is_empty() {
267 return Ok(ReconcileResult {
268 approved: true,
269 merged: false,
270 issues: Vec::new(),
271 reasoning: "Empty diff; nothing to merge.".to_string(),
272 });
273 }
274
275 let verdict = verifier.verify(&diff_text, &changed_files)?;
277 let approved = verdict.approved;
278 let issues = verdict.issues;
279 let reasoning = verdict.reasoning;
280
281 if !approved {
282 return Ok(ReconcileResult { approved: false, merged: false, issues, reasoning });
283 }
284
285 self.git_merge(&branch).context("Failed to merge approved branch")?;
287
288 if let Err(e) = self.git_branch_delete(&branch) {
290 tracing::warn!(error = %e, branch = %branch, "Failed to delete branch after merge");
291 }
292 let wm = WorktreeManager::new(&self.workspace_root);
293 if let Err(e) = wm.remove(worktree_name) {
294 tracing::warn!(error = %e, worktree = %worktree_name, "Failed to remove worktree after merge");
295 }
296
297 Ok(ReconcileResult { approved: true, merged: true, issues, reasoning })
298 }
299}
300
301#[cfg(test)]
304mod tests {
305 use super::*;
306
307 #[test]
308 fn branch_name_format() {
309 assert_eq!(WorktreeReconciler::branch_name("my-loop"), "loop/my-loop");
310 assert_eq!(WorktreeReconciler::branch_name("test_1"), "loop/test_1");
311 }
312
313 #[test]
314 fn reconciler_defaults_main_branch() {
315 let r = WorktreeReconciler::new("/tmp/ws", "");
316 assert_eq!(r.main_branch, "main");
317 }
318
319 #[test]
320 fn reconciler_custom_main_branch() {
321 let r = WorktreeReconciler::new("/tmp/ws", "develop");
322 assert_eq!(r.main_branch, "develop");
323 }
324
325 #[test]
326 fn git_ref_validation_accepts_branches_tags_and_shas() {
327 for valid in ["main", "loop/worker-1", "feature/x", "v1.2.3", "abc123def456"] {
328 validate_git_ref(valid, "test").expect("valid ref accepted");
329 }
330 }
331
332 #[test]
333 fn git_ref_validation_rejects_flag_injection_and_traversal() {
334 for invalid in [
335 "",
336 ".",
337 "./x",
338 "--output=x",
339 "-h",
340 "../escape",
341 "a b",
342 "a\tb",
343 "a:b",
344 "a?b",
345 "a*b",
346 "a~b",
347 "a^b",
348 "a.lock",
349 "trail/",
350 ] {
351 assert!(validate_git_ref(invalid, "test").is_err(), "{invalid:?} must be rejected");
352 }
353 }
354
355 #[cfg(unix)]
356 mod integration {
357 use super::super::WorktreeReconciler;
358 use crate::git::{HeuristicDiffVerifier, WorktreeManager};
359 use std::process::Command as ProcCommand;
360 use tempfile::TempDir;
361 use vtcode_commons::canonicalize;
362
363 fn git(dir: &std::path::Path, args: &[&str]) {
364 let output = ProcCommand::new("git").args(args).current_dir(dir).output().expect("spawn git");
365 assert!(output.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
366 }
367
368 fn commit_all(dir: &std::path::Path, message: &str) {
369 git(dir, &["add", "."]);
370 git(
371 dir,
372 &[
373 "-c",
374 "user.name=Test",
375 "-c",
376 "user.email=test@example.invalid",
377 "commit",
378 "--quiet",
379 "-m",
380 message,
381 ],
382 );
383 }
384
385 fn init_repo() -> TempDir {
386 let dir = TempDir::new().expect("temp dir");
387 git(dir.path(), &["init", "--quiet", "-b", "main"]);
388 std::fs::write(dir.path().join("README.md"), "seed\n").expect("write seed");
389 commit_all(dir.path(), "seed");
390 dir
391 }
392
393 #[test]
394 fn reconcile_merges_benign_worktree_change() {
395 let repo = init_repo();
396 let root = canonicalize(repo.path()).expect("canonicalize repo");
397 let manager = WorktreeManager::new(&root);
398 let worktree_path = manager.create("loop-ok").expect("create");
399
400 std::fs::write(worktree_path.join("feature.txt"), "benign\n").expect("write feature");
401 commit_all(&worktree_path, "add feature");
402
403 let reconciler = WorktreeReconciler::new(&root, "main");
404 let result = reconciler
405 .reconcile("loop-ok", &worktree_path, &HeuristicDiffVerifier)
406 .expect("reconcile");
407
408 assert!(result.approved, "benign diff must be approved: {:?}", result.issues);
409 assert!(result.merged);
410 assert_eq!(std::fs::read_to_string(root.join("feature.txt")).expect("read merged"), "benign\n");
411 }
412
413 #[test]
414 fn reconcile_rejects_dangerous_worktree_change_without_merging() {
415 let repo = init_repo();
416 let root = canonicalize(repo.path()).expect("canonicalize repo");
417 let manager = WorktreeManager::new(&root);
418 let worktree_path = manager.create("loop-bad").expect("create");
419
420 std::fs::write(worktree_path.join("cleanup.sh"), "rm -rf /tmp/build\n").expect("write script");
421 commit_all(&worktree_path, "add cleanup");
422
423 let reconciler = WorktreeReconciler::new(&root, "main");
424 let result = reconciler
425 .reconcile("loop-bad", &worktree_path, &HeuristicDiffVerifier)
426 .expect("reconcile");
427
428 assert!(!result.approved, "dangerous diff must be rejected");
429 assert!(!result.merged);
430 assert!(!result.issues.is_empty());
431 assert!(!root.join("cleanup.sh").exists(), "rejected change must not reach main");
432 }
433 }
434}