Skip to main content

vtcode_core/git/
reconciler.rs

1//! Worktree reconciliation: diff, verify, merge.
2//!
3//! After a worktree-isolated subagent finishes, the `WorktreeReconciler`
4//! captures the branch diff, asks a [`DiffVerifier`]
5//! to approve or reject it, and merges approved changes back into the main
6//! branch.
7
8use anyhow::{Context, Result, anyhow};
9use std::path::{Path, PathBuf};
10
11use super::worktree::git_command_at;
12use super::{DiffVerifier, WorktreeManager};
13
14/// Reject branch/revision inputs that could escape their git argv slot.
15///
16/// Refs flow verbatim into `git diff/log/merge` argv, where a leading `-`
17/// parses as a flag (`--output=` is a file-write primitive). Only the strict
18/// subset needed for branch names, tags, and SHAs is accepted.
19fn 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// ─── ReconcileResult ────────────────────────────────────────────────────────
37
38/// Outcome of a reconcile cycle.
39#[derive(Debug, Clone)]
40pub struct ReconcileResult {
41    /// Whether the verifier approved the change.
42    pub approved: bool,
43    /// Whether the branch was successfully merged into main.
44    pub merged: bool,
45    /// Concrete issues identified by the verifier (empty if approved).
46    pub issues: Vec<String>,
47    /// Free-text reasoning from the verifier or error description.
48    pub reasoning: String,
49}
50
51// ─── WorktreeReconciler ─────────────────────────────────────────────────────
52
53/// Orchestrates the diff → verify → merge cycle for a completed worktree.
54///
55/// The reconciler is internal infrastructure: git runs through the shared
56/// handle-bound [`git_command_at`] helper (same as `WorktreeManager`), and
57/// every ref input is validated before reaching argv.
58pub struct WorktreeReconciler {
59    workspace_root: PathBuf,
60    main_branch: String,
61}
62
63impl WorktreeReconciler {
64    /// Create a reconciler for the given workspace.
65    ///
66    /// `main_branch` defaults to `"main"` if empty.
67    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    /// The branch name for a given worktree name (convention: `loop/{name}`).
79    pub fn branch_name(worktree_name: &str) -> String {
80        format!("loop/{worktree_name}")
81    }
82
83    // ── Git helpers ──────────────────────────────────────────────────────
84
85    /// Run a `git diff` variant with extra args and return stdout.
86    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    /// Run `git diff {base}...{head}` and return the unified diff text.
106    pub fn git_diff(&self, base: &str, head: &str) -> Result<String> {
107        self.run_git_diff(base, head, &[])
108    }
109
110    /// Run `git diff --name-only {base}...{head}` and return changed file paths.
111    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    /// Run `git diff --stat {base}...{head}` and return the summary text.
121    pub fn git_diff_stat(&self, base: &str, head: &str) -> Result<String> {
122        self.run_git_diff(base, head, &["--stat"])
123    }
124
125    /// Check whether a branch has any commits ahead of the base.
126    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    /// Merge a branch into the workspace. Prefers `--ff-only`; falls back
145    /// to a standard merge if fast-forward is not possible.
146    pub fn git_merge(&self, branch: &str) -> Result<()> {
147        validate_git_ref(branch, "branch")?;
148        // Try fast-forward first.
149        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        // Fall back to standard merge.
160        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            // Abort the failed merge to leave the repo clean.
165            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    /// Delete a local branch (must be fully merged).
187    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    /// Check whether a worktree working directory is clean (no uncommitted changes).
204    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    // ── Core reconcile ───────────────────────────────────────────────────
220
221    /// Reconcile a completed worktree: diff → verify → merge → cleanup.
222    ///
223    /// 1. Verify the worktree is clean.
224    /// 2. Check the branch has commits ahead of main.
225    /// 3. Capture the diff and changed files.
226    /// 4. Ask `verifier` to approve or reject the diff.
227    /// 5. If approved, merge the branch and clean up the worktree.
228    /// 6. If rejected, return the result without merging.
229    ///
230    /// `verifier` receives `(diff_text, changed_files)` and returns a verdict.
231    /// This decouples the reconciler from `SubagentController` to keep the git
232    /// module free of subagent dependencies.
233    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        // 1. Pre-flight: worktree must be clean.
243        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        // 2. Check for commits.
253        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        // 3. Capture diff.
263        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        // 4. Verify.
276        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        // 5. Merge.
286        self.git_merge(&branch).context("Failed to merge approved branch")?;
287
288        // 6. Cleanup: delete branch and remove worktree.
289        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// ─── Tests ──────────────────────────────────────────────────────────────────
302
303#[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}