mana-core 0.3.2

Core library for mana — task tracker for AI coding agents
Documentation
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! Git worktree detection and merge utilities.
//!
//! This module provides functions to detect if the current directory is within
//! a git worktree, and to merge changes back to the main branch.

use anyhow::{anyhow, Result};
use std::path::PathBuf;
use std::process::Command;

/// Result of a merge operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergeResult {
    /// Merge completed successfully
    Success,
    /// Merge had conflicts that need resolution
    Conflict { files: Vec<String> },
    /// Nothing to commit (no changes)
    NothingToCommit,
}

/// Information about a git worktree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeInfo {
    /// Path to the main worktree
    pub main_path: PathBuf,
    /// Current worktree path
    pub worktree_path: PathBuf,
    /// Branch name of current worktree
    pub branch: String,
}

/// Parsed worktree entry from `git worktree list --porcelain` output.
#[derive(Debug)]
struct WorktreeEntry {
    path: PathBuf,
    branch: Option<String>,
}

/// Parse the output of `git worktree list --porcelain`.
///
/// Format:
/// ```text
/// worktree /path/to/worktree
/// HEAD abc123
/// branch refs/heads/main
///
/// worktree /path/to/another
/// HEAD def456
/// branch refs/heads/feature
/// ```
fn parse_worktree_list(output: &str) -> Vec<WorktreeEntry> {
    let mut entries = Vec::new();
    let mut current_path: Option<PathBuf> = None;
    let mut current_branch: Option<String> = None;

    for line in output.lines() {
        if let Some(path) = line.strip_prefix("worktree ") {
            // Save previous entry if exists
            if let Some(path) = current_path.take() {
                entries.push(WorktreeEntry {
                    path,
                    branch: current_branch.take(),
                });
            }
            current_path = Some(PathBuf::from(path));
            current_branch = None;
        } else if let Some(branch_ref) = line.strip_prefix("branch ") {
            // Extract branch name from refs/heads/...
            current_branch = Some(
                branch_ref
                    .strip_prefix("refs/heads/")
                    .unwrap_or(branch_ref)
                    .to_string(),
            );
        }
        // Ignore HEAD and other lines
    }

    // Don't forget the last entry
    if let Some(path) = current_path {
        entries.push(WorktreeEntry {
            path,
            branch: current_branch,
        });
    }

    entries
}

/// Detect if the given directory is within a git worktree.
///
/// Uses the provided `cwd` path to determine which worktree (if any)
/// the directory belongs to. This avoids relying on process-global
/// `std::env::current_dir()` which is unsafe in multi-threaded tests.
///
/// Returns:
/// - `Ok(None)` if not in a git repo or in the main worktree
/// - `Ok(Some(WorktreeInfo))` if in a secondary worktree
/// - `Err` if there's an error running git commands
pub fn detect_worktree(cwd: &std::path::Path) -> Result<Option<WorktreeInfo>> {
    // Run git worktree list --porcelain from the given directory
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(cwd)
        .output();

    let output = match output {
        Ok(o) => o,
        Err(_) => return Ok(None), // git not available
    };

    if !output.status.success() {
        // Not in a git repo or git error
        return Ok(None);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries = parse_worktree_list(&stdout);

    if entries.is_empty() {
        return Ok(None);
    }

    // First entry is always the main worktree
    let main_entry = &entries[0];
    let main_path = &main_entry.path;

    // Find which worktree we're in by checking if cwd starts with any worktree path
    // We need to find the most specific match (longest path)
    let mut current_entry: Option<&WorktreeEntry> = None;
    for entry in &entries {
        if cwd.starts_with(&entry.path) {
            match current_entry {
                None => current_entry = Some(entry),
                Some(prev) if entry.path.as_os_str().len() > prev.path.as_os_str().len() => {
                    current_entry = Some(entry)
                }
                _ => {}
            }
        }
    }

    let current_entry = match current_entry {
        Some(e) => e,
        None => return Ok(None), // Not in any known worktree
    };

    // If we're in the main worktree, return None
    if current_entry.path == *main_path {
        return Ok(None);
    }

    // We're in a secondary worktree
    Ok(Some(WorktreeInfo {
        main_path: main_path.clone(),
        worktree_path: current_entry.path.clone(),
        branch: current_entry.branch.clone().unwrap_or_default(),
    }))
}

/// Commit the specified paths in the worktree directory.
///
/// Uses a temporary index seeded from `HEAD`, stages only the requested paths
/// into that temporary index, creates a commit from that tree, and moves `HEAD`
/// to the new commit. This records additions/modifications/deletions for the
/// target paths without including or disturbing unrelated pre-staged changes in
/// the real index. Paths must be relative to the repository root.
pub fn commit_worktree_paths(
    cwd: &std::path::Path,
    message: &str,
    paths: &[String],
) -> Result<bool> {
    commit_worktree_paths_preserve_index(cwd, message, paths)
}

/// Commit the specified paths without including or disturbing the real index.
pub fn commit_worktree_paths_preserve_index(
    cwd: &std::path::Path,
    message: &str,
    paths: &[String],
) -> Result<bool> {
    if paths.is_empty() {
        return Ok(false);
    }

    let repo_root = git_stdout(cwd, &["rev-parse", "--show-toplevel"])?;
    let index_path = std::env::temp_dir().join(format!(
        "mana-targeted-index-{}-{}",
        std::process::id(),
        unique_suffix()
    ));

    let result = commit_with_temp_index(cwd, PathBuf::from(repo_root), &index_path, message, paths);
    cleanup_temp_index(&index_path);
    result
}

fn commit_with_temp_index(
    cwd: &std::path::Path,
    repo_root: PathBuf,
    index_path: &std::path::Path,
    message: &str,
    paths: &[String],
) -> Result<bool> {
    let index = index_path.to_string_lossy().to_string();
    git_status(
        cwd,
        &["read-tree", "HEAD"],
        Some((&index, repo_root.as_path())),
        "git read-tree failed",
    )?;

    let add_output = git_command_with_env(cwd, Some((&index, repo_root.as_path())))
        .arg("add")
        .arg("-A")
        .arg("--")
        .args(paths)
        .output()?;
    if !add_output.status.success() {
        return Err(anyhow!(
            "git add failed: {}",
            String::from_utf8_lossy(&add_output.stderr)
        ));
    }

    let tree = git_stdout_with_env(
        cwd,
        &["write-tree"],
        Some((&index, repo_root.as_path())),
        "git write-tree failed",
    )?;
    let head_tree = git_stdout(cwd, &["rev-parse", "HEAD^{tree}"])?;
    if tree == head_tree {
        return Ok(false);
    }

    let commit_output = Command::new("git")
        .arg("commit-tree")
        .arg(&tree)
        .arg("-p")
        .arg("HEAD")
        .arg("-m")
        .arg(message)
        .current_dir(cwd)
        .output()?;
    if !commit_output.status.success() {
        return Err(anyhow!(
            "git commit-tree failed: {}",
            String::from_utf8_lossy(&commit_output.stderr)
        ));
    }
    let new_head = String::from_utf8_lossy(&commit_output.stdout)
        .trim()
        .to_string();
    if new_head.is_empty() {
        return Err(anyhow!("git commit-tree produced an empty commit id"));
    }

    git_status(
        cwd,
        &[
            "update-ref",
            "-m",
            &format!("commit: {message}"),
            "HEAD",
            &new_head,
        ],
        None,
        "git update-ref failed",
    )?;

    Ok(true)
}

fn git_command_with_env(
    cwd: &std::path::Path,
    temp_index: Option<(&str, &std::path::Path)>,
) -> Command {
    let mut command = Command::new("git");
    command.current_dir(cwd);
    if let Some((index, work_tree)) = temp_index {
        command
            .env("GIT_INDEX_FILE", index)
            .env("GIT_WORK_TREE", work_tree);
    }
    command
}

fn git_status(
    cwd: &std::path::Path,
    args: &[&str],
    temp_index: Option<(&str, &std::path::Path)>,
    context: &str,
) -> Result<()> {
    let output = git_command_with_env(cwd, temp_index).args(args).output()?;
    if output.status.success() {
        return Ok(());
    }
    Err(anyhow!(
        "{}: {}",
        context,
        String::from_utf8_lossy(&output.stderr)
    ))
}

fn git_stdout(cwd: &std::path::Path, args: &[&str]) -> Result<String> {
    git_stdout_with_env(cwd, args, None, "git command failed")
}

fn git_stdout_with_env(
    cwd: &std::path::Path,
    args: &[&str],
    temp_index: Option<(&str, &std::path::Path)>,
    context: &str,
) -> Result<String> {
    let output = git_command_with_env(cwd, temp_index).args(args).output()?;
    if !output.status.success() {
        return Err(anyhow!(
            "{}: {}",
            context,
            String::from_utf8_lossy(&output.stderr)
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

fn cleanup_temp_index(path: &std::path::Path) {
    let _ = std::fs::remove_file(path);
    let _ = std::fs::remove_file(path.with_extension("lock"));
}

fn unique_suffix() -> u128 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or(0)
}

/// Commit all changes in the specified worktree directory.
///
/// Runs `git add -A` followed by `git commit -m <message>` in the given directory.
/// Uses an explicit `cwd` to avoid relying on the process-global current directory.
///
/// Returns:
/// - `Ok(true)` if a commit was made
/// - `Ok(false)` if there was nothing to commit
/// - `Err` if git commands fail
pub fn commit_worktree_changes(cwd: &std::path::Path, message: &str) -> Result<bool> {
    // Stage all changes
    let add_output = Command::new("git")
        .args(["add", "-A"])
        .current_dir(cwd)
        .output()?;

    if !add_output.status.success() {
        return Err(anyhow!(
            "git add failed: {}",
            String::from_utf8_lossy(&add_output.stderr)
        ));
    }

    commit_staged_changes(cwd, message)
}

fn commit_staged_changes(cwd: &std::path::Path, message: &str) -> Result<bool> {
    // Commit changes
    let commit_output = Command::new("git")
        .args(["commit", "-m", message])
        .current_dir(cwd)
        .output()?;

    if commit_output.status.success() {
        return Ok(true);
    }

    // Check if it failed because there was nothing to commit
    let stderr = String::from_utf8_lossy(&commit_output.stderr);
    let stdout = String::from_utf8_lossy(&commit_output.stdout);
    if stderr.contains("nothing to commit")
        || stdout.contains("nothing to commit")
        || stderr.contains("no changes added")
        || stdout.contains("no changes added")
    {
        return Ok(false);
    }

    Err(anyhow!("git commit failed: {}", stderr))
}

/// Merge the worktree branch to main.
///
/// Performs a no-fast-forward merge from the worktree's branch to the main branch.
/// If there are conflicts, aborts the merge and returns the conflicting files.
///
/// # Arguments
/// * `info` - Information about the worktree
/// * `unit_id` - Unit ID to include in the commit message
///
/// Returns:
/// - `Ok(MergeResult::Success)` if merge completed
/// - `Ok(MergeResult::Conflict { files })` if there were conflicts
/// - `Ok(MergeResult::NothingToCommit)` if branch is already merged
/// - `Err` if git commands fail unexpectedly
pub fn merge_to_main(info: &WorktreeInfo, unit_id: &str) -> Result<MergeResult> {
    let main_path = &info.main_path;
    let branch = &info.branch;

    if branch.is_empty() {
        return Err(anyhow!("Worktree has no branch (detached HEAD?)"));
    }

    // Perform the merge from the main worktree
    let merge_message = format!("Merge branch '{}' (unit {})", branch, unit_id);
    let merge_output = Command::new("git")
        .args(["-C", main_path.to_str().unwrap_or(".")])
        .args(["merge", branch, "--no-ff", "-m", &merge_message])
        .output()?;

    if merge_output.status.success() {
        return Ok(MergeResult::Success);
    }

    let stderr = String::from_utf8_lossy(&merge_output.stderr);
    let stdout = String::from_utf8_lossy(&merge_output.stdout);

    // Check if already up-to-date
    if stdout.contains("Already up to date") || stderr.contains("Already up to date") {
        return Ok(MergeResult::NothingToCommit);
    }

    // Check for conflicts
    if stdout.contains("CONFLICT") || stderr.contains("CONFLICT") {
        // Get list of conflicting files
        let conflicts = parse_conflict_files(&stdout, &stderr);

        // Abort the merge
        let _ = Command::new("git")
            .args(["-C", main_path.to_str().unwrap_or(".")])
            .args(["merge", "--abort"])
            .output();

        return Ok(MergeResult::Conflict { files: conflicts });
    }

    Err(anyhow!("git merge failed: {}", stderr))
}

/// Parse conflicting files from merge output.
fn parse_conflict_files(stdout: &str, stderr: &str) -> Vec<String> {
    let combined = format!("{}\n{}", stdout, stderr);
    let mut files = Vec::new();

    for line in combined.lines() {
        // Match lines like "CONFLICT (content): Merge conflict in <file>"
        if let Some(idx) = line.find("Merge conflict in ") {
            let file = line[idx + "Merge conflict in ".len()..].trim();
            files.push(file.to_string());
        }
        // Match lines like "CONFLICT (add/add): Merge conflict in <file>"
        // or "CONFLICT (modify/delete): <file> deleted in ..."
        else if line.starts_with("CONFLICT") {
            // Try to extract filename from various CONFLICT formats
            if let Some(colon_idx) = line.find("):") {
                let rest = &line[colon_idx + 2..].trim();
                // Get first word which might be the filename
                if let Some(word) = rest.split_whitespace().next() {
                    if !word.is_empty() && word != "Merge" && !files.contains(&word.to_string()) {
                        files.push(word.to_string());
                    }
                }
            }
        }
    }

    files
}

/// Clean up a worktree and its branch.
///
/// Removes the worktree directory and deletes the associated branch.
///
/// # Arguments
/// * `info` - Information about the worktree to clean up
pub fn cleanup_worktree(info: &WorktreeInfo) -> Result<()> {
    let main_path = &info.main_path;
    let worktree_path = &info.worktree_path;
    let branch = &info.branch;

    // Remove the worktree
    let remove_output = Command::new("git")
        .args(["-C", main_path.to_str().unwrap_or(".")])
        .args(["worktree", "remove", worktree_path.to_str().unwrap_or(".")])
        .output()?;

    if !remove_output.status.success() {
        // Try force remove if normal remove fails
        let force_output = Command::new("git")
            .args(["-C", main_path.to_str().unwrap_or(".")])
            .args([
                "worktree",
                "remove",
                "--force",
                worktree_path.to_str().unwrap_or("."),
            ])
            .output()?;

        if !force_output.status.success() {
            return Err(anyhow!(
                "Failed to remove worktree: {}",
                String::from_utf8_lossy(&force_output.stderr)
            ));
        }
    }

    // Delete the branch (only if we have a branch name)
    if !branch.is_empty() {
        let delete_output = Command::new("git")
            .args(["-C", main_path.to_str().unwrap_or(".")])
            .args(["branch", "-d", branch])
            .output()?;

        if !delete_output.status.success() {
            // Try force delete if normal delete fails (branch not fully merged)
            let force_delete = Command::new("git")
                .args(["-C", main_path.to_str().unwrap_or(".")])
                .args(["branch", "-D", branch])
                .output()?;

            if !force_delete.status.success() {
                return Err(anyhow!(
                    "Failed to delete branch '{}': {}",
                    branch,
                    String::from_utf8_lossy(&force_delete.stderr)
                ));
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_worktree_list_single() {
        let output = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n";
        let entries = parse_worktree_list(output);

        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].path, PathBuf::from("/home/user/project"));
        assert_eq!(entries[0].branch, Some("main".to_string()));
    }

    #[test]
    fn test_parse_worktree_list_multiple() {
        let output = r#"worktree /home/user/project
HEAD abc123
branch refs/heads/main

worktree /home/user/project-feature
HEAD def456
branch refs/heads/feature-x
"#;
        let entries = parse_worktree_list(output);

        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].path, PathBuf::from("/home/user/project"));
        assert_eq!(entries[0].branch, Some("main".to_string()));
        assert_eq!(entries[1].path, PathBuf::from("/home/user/project-feature"));
        assert_eq!(entries[1].branch, Some("feature-x".to_string()));
    }

    #[test]
    fn test_parse_worktree_list_detached_head() {
        let output = "worktree /home/user/project\nHEAD abc123\ndetached\n";
        let entries = parse_worktree_list(output);

        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].path, PathBuf::from("/home/user/project"));
        assert_eq!(entries[0].branch, None);
    }

    #[test]
    fn detect_worktree_runs_without_panic() {
        // This test just ensures the function doesn't panic
        // The actual result depends on the environment
        let cwd = std::env::current_dir().unwrap();
        let result = detect_worktree(&cwd);
        assert!(result.is_ok());
    }

    // Merge-related tests
    mod merge {
        use super::*;

        #[test]
        fn test_merge_result_variants() {
            // Test that MergeResult variants can be constructed and compared
            let success = MergeResult::Success;
            let conflict = MergeResult::Conflict {
                files: vec!["file1.txt".to_string(), "file2.txt".to_string()],
            };
            let nothing = MergeResult::NothingToCommit;

            assert_eq!(success, MergeResult::Success);
            assert_eq!(nothing, MergeResult::NothingToCommit);

            if let MergeResult::Conflict { files } = conflict {
                assert_eq!(files.len(), 2);
                assert!(files.contains(&"file1.txt".to_string()));
            } else {
                unreachable!("Expected Conflict variant");
            }
        }

        #[test]
        fn test_parse_conflict_files_content_conflict() {
            let stdout =
                "Auto-merging src/lib.rs\nCONFLICT (content): Merge conflict in src/lib.rs\n";
            let stderr = "";
            let files = parse_conflict_files(stdout, stderr);
            assert_eq!(files, vec!["src/lib.rs"]);
        }

        #[test]
        fn test_parse_conflict_files_multiple() {
            let stdout = r#"Auto-merging file1.txt
CONFLICT (content): Merge conflict in file1.txt
Auto-merging file2.txt
CONFLICT (content): Merge conflict in file2.txt
"#;
            let files = parse_conflict_files(stdout, "");
            assert_eq!(files.len(), 2);
            assert!(files.contains(&"file1.txt".to_string()));
            assert!(files.contains(&"file2.txt".to_string()));
        }

        #[test]
        fn test_parse_conflict_files_empty() {
            let files = parse_conflict_files("", "");
            assert!(files.is_empty());
        }

        #[test]
        fn test_parse_conflict_files_no_conflicts() {
            let stdout = "Already up to date.\n";
            let files = parse_conflict_files(stdout, "");
            assert!(files.is_empty());
        }

        #[test]
        fn test_worktree_info_for_merge() {
            // Test that WorktreeInfo can be used with merge functions
            let info = WorktreeInfo {
                main_path: PathBuf::from("/home/user/project"),
                worktree_path: PathBuf::from("/home/user/project-feature"),
                branch: "feature-branch".to_string(),
            };

            assert_eq!(info.branch, "feature-branch");
            assert_eq!(info.main_path, PathBuf::from("/home/user/project"));
            assert_eq!(
                info.worktree_path,
                PathBuf::from("/home/user/project-feature")
            );
        }

        #[test]
        fn test_merge_to_main_requires_branch() {
            // Test that merge_to_main fails with empty branch
            let info = WorktreeInfo {
                main_path: PathBuf::from("/tmp/nonexistent"),
                worktree_path: PathBuf::from("/tmp/nonexistent-wt"),
                branch: String::new(), // Empty branch
            };

            let result = merge_to_main(&info, "test-unit");
            assert!(result.is_err());
            let err = result.unwrap_err();
            assert!(err.to_string().contains("no branch"));
        }

        #[test]
        fn test_commit_worktree_changes_type_signature() {
            // This test verifies the function signature and return type
            // by calling it - it will likely fail (not in git repo) but
            // shouldn't panic
            let cwd = std::env::current_dir().unwrap();
            let result = commit_worktree_changes(&cwd, "test message");
            // Result should be Ok or Err, not panic
            let _ = result;
        }

        #[test]
        fn test_cleanup_worktree_type_signature() {
            // This test verifies the function signature works correctly
            let info = WorktreeInfo {
                main_path: PathBuf::from("/tmp/nonexistent-main"),
                worktree_path: PathBuf::from("/tmp/nonexistent-wt"),
                branch: "test-branch".to_string(),
            };

            // This will fail because the paths don't exist, but shouldn't panic
            let result = cleanup_worktree(&info);
            assert!(result.is_err()); // Expected to fail with nonexistent paths
        }
    }
}