dirge-agent 0.12.6

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Debug, Clone)]
pub struct WorktreeInfo {
    pub branch: String,
    pub worktree_path: PathBuf,
    pub main_repo_path: PathBuf,
}

pub fn detect() -> Option<WorktreeInfo> {
    let output = Command::new("git")
        .args(["rev-parse", "--git-common-dir"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let common_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();

    let output = Command::new("git")
        .args(["rev-parse", "--git-dir"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let git_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();

    let worktree_path: PathBuf = Path::new(&git_dir).canonicalize().ok()?;

    if common_dir == git_dir {
        return None;
    }

    let main_repo_path: PathBuf = Path::new(&common_dir).parent().map(|p| p.to_path_buf())?;
    let main_repo_path = main_repo_path.canonicalize().ok()?;

    let branch = current_branch().unwrap_or_default();

    Some(WorktreeInfo {
        branch,
        worktree_path: worktree_path
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or(worktree_path),
        main_repo_path,
    })
}

pub fn current_branch() -> Option<String> {
    let output = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if branch == "HEAD" { None } else { Some(branch) }
}

pub fn default_branch(repo_path: &Path) -> Option<String> {
    for name in &["main", "master"] {
        let output = Command::new("git")
            .arg("-C")
            .arg(repo_path)
            .args(["rev-parse", "--verify", name])
            .output()
            .ok();
        if let Some(out) = output
            && out.status.success()
        {
            return Some(name.to_string());
        }
    }
    None
}

/// Reject branch names that would be unsafe or ambiguous as a `git
/// worktree add -b <name>` argument. EXT-8: pre-flight check against
/// the obviously-hostile shapes before invoking git; combined with the
/// `--` argv separator below, this defangs both flag-injection
/// (`--exec=…`) and the assorted git ref-name traversal / metachar
/// foot-guns (`..`, `~`, `:`, `HEAD`, control bytes).
fn validate_branch_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("branch name must not be empty".to_string());
    }
    if name.starts_with('-') {
        // Leading `-` would be parsed by git as a flag even though
        // it sits in the positional slot — covered also by `--` below,
        // but reject early for a clearer error.
        return Err(format!(
            "branch name {name:?} must not start with '-' (looks like a git flag)"
        ));
    }
    if name == "HEAD" || name == "@" {
        return Err(format!("branch name {name:?} is a reserved git ref"));
    }
    if name.contains("..") {
        return Err(format!(
            "branch name {name:?} must not contain '..' (git ref-name rule)"
        ));
    }
    for bad in ['~', ':', '^', '?', '*', '['] {
        if name.contains(bad) {
            return Err(format!(
                "branch name {name:?} must not contain '{bad}' (git ref-name rule)"
            ));
        }
    }
    if name
        .chars()
        .any(|c| c == '\0' || (c.is_control() && c != '\t'))
    {
        return Err(format!(
            "branch name {name:?} must not contain null bytes or control characters"
        ));
    }
    Ok(())
}

pub fn create(name: &str) -> Result<(PathBuf, WorktreeInfo), String> {
    validate_branch_name(name)?;
    let target = format!("../{}", name);

    // EXT-8: insert `--` before the positional args so a maliciously-
    // crafted but technically-valid name can't be re-interpreted as
    // a flag by git's option parser. `validate_branch_name` already
    // rejects the obvious shapes; `--` is belt-and-suspenders.
    let output = Command::new("git")
        .args(["worktree", "add", "-b", name, "--", &target])
        .output()
        .map_err(|e| format!("failed to run git: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("git worktree add failed: {}", stderr.trim()));
    }

    // dirge-ivel: `git worktree add` has already created the worktree on
    // disk. If a later step (canonicalize / cwd lookup) fails we must NOT
    // leave it stranded — remove it before returning the error.
    let cleanup = |reason: String| -> String {
        let _ = Command::new("git")
            .args(["worktree", "remove", "--force", "--", &target])
            .output();
        reason
    };

    let wt_path = match PathBuf::from(&target).canonicalize() {
        Ok(p) => p,
        Err(e) => return Err(cleanup(format!("failed to resolve worktree path: {}", e))),
    };

    let main_repo = match std::env::current_dir() {
        Ok(p) => p,
        Err(e) => return Err(cleanup(format!("failed to get current dir: {}", e))),
    };

    Ok((
        wt_path.clone(),
        WorktreeInfo {
            branch: name.to_string(),
            worktree_path: wt_path,
            main_repo_path: main_repo,
        },
    ))
}

/// Run a git subcommand in `repo`, returning trimmed stdout on success
/// or a trimmed-stderr error on failure. Always inserts `-C <repo>`.
fn git_in(repo: &Path, args: &[&str]) -> Result<String, String> {
    let output = Command::new("git")
        // Set the child's cwd to `repo` (not just `-C repo`): git calls
        // getcwd() at startup, so if the PARENT process cwd has been removed
        // the child would fail with "cannot access current directory" even
        // though `-C` points elsewhere. Pinning the child cwd to the repo
        // makes the call robust (and fixes a parallel-test flake where a
        // sibling test deletes the shared process cwd).
        .current_dir(repo)
        .arg("-C")
        .arg(repo)
        .args(args)
        .output()
        .map_err(|e| format!("failed to run git: {e}"))?;
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
    }
}

/// True if `repo`'s working tree has uncommitted changes (staged,
/// unstaged, or untracked).
fn is_dirty(repo: &Path) -> Result<bool, String> {
    Ok(!git_in(repo, &["status", "--porcelain"])?.is_empty())
}

/// Merge the worktree's branch into `target` in the main repo —
/// programmatically and conflict-safe (dirge-2qke). Replaces the prior
/// design that handed the whole merge (including "push and delete the
/// worktree") to an unconstrained LLM prompt.
///
/// Guarantees:
///   - Refuses if the worktree OR the main repo has uncommitted changes
///     (a conflicting merge against a dirty tree risks losing work).
///   - On a merge conflict the merge is **aborted** (`git merge --abort`)
///     so the repo is left exactly as it was — nothing half-merged.
///   - Never pushes and never deletes the worktree; the caller decides
///     what to do after a clean merge. So a failure can't strand work.
///
/// Returns `Ok(())` only when `target` cleanly contains the branch.
pub fn merge_worktree(info: &WorktreeInfo, target: &str) -> Result<(), String> {
    validate_branch_name(target)?;
    validate_branch_name(&info.branch)?;
    let main = info.main_repo_path.as_path();

    if is_dirty(&info.worktree_path)? {
        return Err(format!(
            "worktree '{}' has uncommitted changes — commit or discard them before merging",
            info.branch
        ));
    }
    if is_dirty(main)? {
        return Err(format!(
            "main repo at {} has uncommitted changes — commit or stash them before merging",
            main.display()
        ));
    }

    // Switch the main repo to the target branch (prefer `switch`, fall
    // back to `checkout` on older git). NOTE: no `--` separator here —
    // for `switch`/`checkout`/`merge` a `--` forces the following token to
    // be read as a PATHSPEC, not a branch/ref (e.g. `git checkout -- main`
    // restores a file named `main` instead of switching branches), and its
    // handling is git-version-dependent. `validate_branch_name` above
    // already rejects flag-shaped / metachar names, so the bare ref is safe.
    git_in(main, &["switch", target])
        .or_else(|_| git_in(main, &["checkout", target]))
        .map_err(|e| format!("failed to switch main repo to '{target}': {e}"))?;

    // --no-ff keeps the worktree's history explicit. On any failure
    // (conflict or otherwise) abort so the index/working tree are
    // restored to the pre-merge state.
    if let Err(e) = git_in(main, &["merge", "--no-ff", &info.branch]) {
        let _ = git_in(main, &["merge", "--abort"]);
        return Err(format!(
            "merge of '{}' into '{target}' could not complete cleanly and was aborted — \
             nothing was changed. Resolve it manually in {} (git merge {}). Details: {e}",
            info.branch,
            main.display(),
            info.branch
        ));
    }
    Ok(())
}

/// Remove a (merged) worktree from the main repo. Best-effort: callers
/// treat failure as non-fatal since the merge already succeeded. Must be
/// invoked with the cwd OUTSIDE the worktree being removed.
pub fn remove_worktree(main_repo: &Path, worktree_path: &Path) -> Result<(), String> {
    git_in(
        main_repo,
        &["worktree", "remove", "--", &worktree_path.to_string_lossy()],
    )
    .map(|_| ())
}

pub fn repo_name(path: &Path) -> String {
    path.file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| "unknown".to_string())
}

#[cfg(test)]
mod merge_tests {
    //! dirge-2qke: `merge_worktree` is conflict-safe and never strands work.
    use super::*;

    /// Run git in `dir` with a fixed identity (so commits work without a
    /// global git config), panicking on failure with stderr.
    fn git(dir: &Path, args: &[&str]) -> String {
        let mut full = vec![
            "-c",
            "user.email=test@dirge",
            "-c",
            "user.name=dirge",
            "-c",
            "commit.gpgsign=false",
            "-c",
            "init.defaultBranch=main",
        ];
        full.extend_from_slice(args);
        let out = Command::new("git")
            // Pin the child cwd to `dir` so a concurrent test deleting the
            // shared process cwd can't make git fail getcwd() (parallel-test
            // isolation; mirrors git_in).
            .current_dir(dir)
            .arg("-C")
            .arg(dir)
            .args(&full)
            .output()
            .expect("git runs");
        assert!(
            out.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    fn write(p: &Path, contents: &str) {
        std::fs::write(p, contents).unwrap();
    }

    /// A main repo on `main` with one commit, plus a sibling worktree on
    /// branch `feature`. Returns (info, tmp_root) — tmp_root is removed by
    /// the caller.
    fn setup() -> (WorktreeInfo, PathBuf) {
        // Unique per invocation: a process-wide atomic counter, NOT just a
        // timestamp — tests run in parallel and `as_nanos()` collided on
        // coarse clocks / same-instant samples, so two tests shared a temp
        // dir and the second `git init` failed with "File exists".
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let root =
            std::env::temp_dir().join(format!("dirge-wt-merge-test-{}-{}", std::process::id(), n));
        let _ = std::fs::remove_dir_all(&root);
        let main = root.join("repo");
        std::fs::create_dir_all(&main).unwrap();
        git(&main, &["init"]);
        // Persist a repo-LOCAL identity into .git/config (shared across
        // worktrees). merge_worktree's internal git calls don't pass `-c`,
        // and CI runners have no global git identity, so without this the
        // `--no-ff` merge commit fails with "Committer identity unknown".
        git(&main, &["config", "user.email", "test@dirge.local"]);
        git(&main, &["config", "user.name", "dirge-test"]);
        git(&main, &["config", "commit.gpgsign", "false"]);
        write(&main.join("file.txt"), "base\n");
        git(&main, &["add", "."]);
        git(&main, &["commit", "-m", "base"]);
        // Worktree on a new branch `feature`.
        let wt = root.join("feature");
        git(
            &main,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                "--",
                wt.to_str().unwrap(),
            ],
        );
        let info = WorktreeInfo {
            branch: "feature".to_string(),
            worktree_path: wt,
            main_repo_path: main,
        };
        (info, root)
    }

    #[test]
    fn clean_merge_lands_feature_in_main() {
        let (info, root) = setup();
        // Distinct, non-conflicting change committed on the worktree.
        write(&info.worktree_path.join("new.txt"), "from feature\n");
        git(&info.worktree_path, &["add", "."]);
        git(&info.worktree_path, &["commit", "-m", "feature work"]);

        merge_worktree(&info, "main").expect("clean merge should succeed");

        // The feature file is now present in the main repo on `main`.
        assert_eq!(
            git(&info.main_repo_path, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "main"
        );
        assert!(
            info.main_repo_path.join("new.txt").exists(),
            "merged file present in main"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn conflicting_merge_aborts_and_leaves_repo_clean() {
        let (info, root) = setup();
        // Conflicting edits to the SAME line on both branches.
        write(&info.main_repo_path.join("file.txt"), "main change\n");
        git(&info.main_repo_path, &["commit", "-am", "main edit"]);
        write(&info.worktree_path.join("file.txt"), "feature change\n");
        git(&info.worktree_path, &["commit", "-am", "feature edit"]);

        let err = merge_worktree(&info, "main").expect_err("conflicting merge must fail");
        assert!(
            err.contains("aborted"),
            "error should say it aborted: {err}"
        );
        // The merge was aborted: no MERGE_HEAD, clean tree, main's content intact.
        assert!(
            !info.main_repo_path.join(".git/MERGE_HEAD").exists(),
            "merge must be aborted (no MERGE_HEAD)"
        );
        assert!(
            git(&info.main_repo_path, &["status", "--porcelain"]).is_empty(),
            "main working tree must be clean after abort"
        );
        assert_eq!(
            std::fs::read_to_string(info.main_repo_path.join("file.txt")).unwrap(),
            "main change\n",
            "main's content is untouched by the aborted merge"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn dirty_worktree_is_refused() {
        let (info, root) = setup();
        // Uncommitted change in the worktree.
        write(&info.worktree_path.join("file.txt"), "uncommitted\n");
        let err = merge_worktree(&info, "main").expect_err("dirty worktree must be refused");
        assert!(
            err.contains("uncommitted"),
            "error names the dirty state: {err}"
        );
        let _ = std::fs::remove_dir_all(&root);
    }
}