crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI development
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
// Swarm merge orchestration: discover worktrees, detect conflicts,
// compute merge order, and apply diffs.

use anyhow::{bail, Context, Result};
use std::path::Path;

use super::io::*;
use super::types::*;
use crate::sync::SyncManager;

/// Default base refs to try, in priority order.
const BASE_REFS: &[&str] = &["develop", "main", "origin/develop", "origin/main"];

/// Detect the base branch by checking which ref exists in the given directory.
///
/// Tries `develop`, `main`, `origin/develop`, `origin/main` in order and
/// returns the first one that resolves. Returns `None` if none exist.
fn detect_base_branch(repo_dir: &Path) -> Option<String> {
    for base in BASE_REFS {
        let ok = std::process::Command::new("git")
            .current_dir(repo_dir)
            .args(["rev-parse", "--verify", base])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success());
        if ok {
            return Some((*base).to_string());
        }
    }
    None
}

/// Discover agent worktrees that have commits beyond the base branch.
fn discover_worktrees(repo_root: &Path) -> Result<Vec<MergeSource>> {
    let worktrees_dir = repo_root.join(".worktrees");
    if !worktrees_dir.is_dir() {
        return Ok(Vec::new());
    }

    let mut sources = Vec::new();
    let mut entries: Vec<_> = std::fs::read_dir(&worktrees_dir)
        .context("Failed to read .worktrees")?
        .filter_map(std::result::Result::ok)
        .collect();
    entries.sort_by_key(std::fs::DirEntry::file_name);

    for entry in entries {
        let wt_path = entry.path();
        if !wt_path.is_dir() {
            continue;
        }

        let slug = entry.file_name().to_string_lossy().to_string();

        // Get changed files relative to the base branch.
        let Some(base) = detect_base_branch(&wt_path) else {
            continue;
        };

        let diff_output = std::process::Command::new("git")
            .current_dir(&wt_path)
            .args(["diff", "--name-only", &format!("{base}...HEAD")])
            .output();

        let changed_files: Vec<String> = diff_output
            .ok()
            .filter(|o| o.status.success())
            .map(|o| {
                String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .filter(|l| !l.is_empty())
                    .map(ToString::to_string)
                    .collect()
            })
            .unwrap_or_default();

        if changed_files.is_empty() {
            continue;
        }

        // Count commits beyond base branch
        let commit_count = std::process::Command::new("git")
            .current_dir(&wt_path)
            .args(["log", "--oneline", &format!("{base}..HEAD")])
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map_or(0, |o| String::from_utf8_lossy(&o.stdout).lines().count());

        sources.push(MergeSource {
            agent_slug: slug,
            worktree_path: wt_path,
            changed_files,
            commit_count,
        });
    }

    Ok(sources)
}

/// Extract line ranges modified by a diff for a specific file in a worktree.
///
/// Tries multiple base refs (develop, main, origin/develop, origin/main) to handle
/// worktrees created from different bases, matching `discover_worktrees` behavior.
fn extract_diff_ranges(worktree: &Path, file: &str) -> Result<Vec<(usize, usize)>> {
    let base = detect_base_branch(worktree)
        .ok_or_else(|| anyhow::anyhow!("No base ref available for diff"))?;
    let output = std::process::Command::new("git")
        .current_dir(worktree)
        .args(["diff", &format!("{base}...HEAD"), "--", file])
        .output()
        .context("Failed to run git diff")?;

    if !output.status.success() {
        return Ok(Vec::new());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut ranges = Vec::new();

    for line in stdout.lines() {
        // Parse unified diff hunk headers: @@ -start,count +start,count @@
        if let Some(rest) = line.strip_prefix("@@ ") {
            // Extract the +start,count part (new file ranges)
            if let Some(plus_part) = rest.split(' ').find(|s| s.starts_with('+')) {
                let nums = plus_part.trim_start_matches('+');
                let parts: Vec<&str> = nums.split(',').collect();
                if let Ok(start) = parts[0].parse::<usize>() {
                    let count = if parts.len() > 1 {
                        parts[1]
                            .split_whitespace()
                            .next()
                            .and_then(|s| s.parse::<usize>().ok())
                            .unwrap_or(1)
                    } else {
                        1
                    };
                    if count > 0 {
                        ranges.push((start, start + count - 1));
                    }
                }
            }
        }
    }

    Ok(ranges)
}

/// Check if two sets of line ranges overlap.
pub(super) fn ranges_overlap(a: &[(usize, usize)], b: &[(usize, usize)]) -> bool {
    for &(a_start, a_end) in a {
        for &(b_start, b_end) in b {
            if a_start <= b_end && b_start <= a_end {
                return true;
            }
        }
    }
    false
}

/// Detect file conflicts between multiple merge sources.
pub(super) fn detect_file_conflicts(sources: &[MergeSource]) -> Vec<FileConflict> {
    // Build map: file -> list of agent slugs that modified it
    let mut file_agents: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();

    for source in sources {
        for file in &source.changed_files {
            file_agents
                .entry(file.clone())
                .or_default()
                .push(source.agent_slug.clone());
        }
    }

    let mut conflicts = Vec::new();

    for (file, agents) in &file_agents {
        if agents.len() < 2 {
            continue;
        }

        // Build a lookup for worktree paths by agent slug
        let slug_to_source: std::collections::HashMap<&str, &MergeSource> =
            sources.iter().map(|s| (s.agent_slug.as_str(), s)).collect();

        // Check if we can determine overlap by inspecting diff ranges
        let mut all_ranges: Vec<(&str, Vec<(usize, usize)>)> = Vec::new();
        let mut range_extraction_ok = true;

        for agent_slug in agents {
            if let Some(source) = slug_to_source.get(agent_slug.as_str()) {
                match extract_diff_ranges(&source.worktree_path, file) {
                    Ok(ranges) if !ranges.is_empty() => {
                        all_ranges.push((agent_slug.as_str(), ranges));
                    }
                    Ok(_) => {
                        // Empty ranges could mean the file was created or binary
                        range_extraction_ok = false;
                        break;
                    }
                    Err(_) => {
                        range_extraction_ok = false;
                        break;
                    }
                }
            }
        }

        let conflict_type = if range_extraction_ok {
            // Check pairwise for overlapping ranges
            let mut has_overlap = false;
            'outer: for i in 0..all_ranges.len() {
                for j in (i + 1)..all_ranges.len() {
                    if ranges_overlap(&all_ranges[i].1, &all_ranges[j].1) {
                        has_overlap = true;
                        break 'outer;
                    }
                }
            }
            if has_overlap {
                ConflictType::Overlapping
            } else {
                ConflictType::NonOverlapping
            }
        } else {
            // If we can't extract ranges, check if file is new in any worktree
            ConflictType::CreateModify
        };

        conflicts.push(FileConflict {
            file: file.clone(),
            agents: agents.clone(),
            conflict_type,
        });
    }

    conflicts
}

/// Compute merge order: non-conflicting agents first, then non-overlapping, then overlapping.
pub(super) fn compute_merge_order(
    sources: &[MergeSource],
    conflicts: &[FileConflict],
) -> Vec<String> {
    // Classify each agent's worst conflict level
    let mut agent_worst: std::collections::BTreeMap<&str, u8> = std::collections::BTreeMap::new();

    // Start all agents at level 0 (no conflicts)
    for source in sources {
        agent_worst.insert(&source.agent_slug, 0);
    }

    for conflict in conflicts {
        let level = match conflict.conflict_type {
            ConflictType::NonOverlapping => 1,
            ConflictType::CreateModify => 2,
            ConflictType::Overlapping => 3,
        };
        for agent in &conflict.agents {
            if let Some(current) = agent_worst.get_mut(agent.as_str()) {
                if level > *current {
                    *current = level;
                }
            }
        }
    }

    // Sort: lowest conflict level first, then alphabetically for stability
    let mut order: Vec<(&str, u8)> = agent_worst.into_iter().collect();
    order.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(b.0)));

    order.iter().map(|(slug, _)| slug.to_string()).collect()
}

/// Orchestrate merging agent worktree changes into a single branch.
pub fn merge(
    crosslink_dir: &Path,
    branch: &str,
    base_branch: Option<&str>,
    dry_run: bool,
    agents_filter: Option<&str>,
) -> Result<()> {
    let repo_root = crosslink_dir
        .parent()
        .ok_or_else(|| anyhow::anyhow!("Cannot determine repo root"))?;

    // Resolve the base branch — explicit flag, or auto-detect from repo
    let resolved_base = base_branch
        .map(ToString::to_string)
        .or_else(|| detect_base_branch(repo_root))
        .ok_or_else(|| {
            anyhow::anyhow!(
                "No base branch found (tried develop, main). \
                 Use --base <ref> to specify one."
            )
        })?;

    // Discover agent worktrees with changes
    let mut sources = discover_worktrees(repo_root)?;

    if sources.is_empty() {
        println!("No agent worktrees with changes found.");
        return Ok(());
    }

    // Filter by agent slugs if --agents provided
    if let Some(filter) = agents_filter {
        let slugs: std::collections::HashSet<&str> = filter.split(',').map(str::trim).collect();
        sources.retain(|s| slugs.contains(s.agent_slug.as_str()));
        if sources.is_empty() {
            bail!("No matching agent worktrees found for filter: {filter}");
        }
    }

    // Detect file conflicts
    let conflicts = detect_file_conflicts(&sources);

    // Compute merge order
    let merge_order = compute_merge_order(&sources, &conflicts);

    // Build the merge plan
    let plan = MergePlan {
        target_branch: branch.to_string(),
        agents: sources.clone(),
        conflicts: conflicts.clone(),
        merge_order: merge_order.clone(),
    };

    // Print summary
    println!("Merge Plan");
    println!("==========");
    println!("Target branch: {branch}");
    println!(
        "Agents:        {} ({} total commits)",
        sources.len(),
        sources.iter().map(|s| s.commit_count).sum::<usize>()
    );
    println!();

    // Agent details table
    println!("Agent Worktrees:");
    for source in &sources {
        println!(
            "  {}{} file{}, {} commit{}",
            source.agent_slug,
            source.changed_files.len(),
            if source.changed_files.len() == 1 {
                ""
            } else {
                "s"
            },
            source.commit_count,
            if source.commit_count == 1 { "" } else { "s" },
        );
    }
    println!();

    // Conflict analysis
    if conflicts.is_empty() {
        println!("Conflicts:     none detected");
    } else {
        println!(
            "Conflicts:     {} file{}",
            conflicts.len(),
            if conflicts.len() == 1 { "" } else { "s" }
        );
        for conflict in &conflicts {
            let type_label = match conflict.conflict_type {
                ConflictType::NonOverlapping => "non-overlapping",
                ConflictType::Overlapping => "OVERLAPPING",
                ConflictType::CreateModify => "create/modify",
            };
            println!(
                "  {} [{}] — agents: {}",
                conflict.file,
                type_label,
                conflict.agents.join(", ")
            );
        }

        let overlapping_count = conflicts
            .iter()
            .filter(|c| c.conflict_type == ConflictType::Overlapping)
            .count();
        if overlapping_count > 0 {
            println!();
            println!(
                "WARNING: {} file{} with overlapping changes will need manual resolution.",
                overlapping_count,
                if overlapping_count == 1 { "" } else { "s" }
            );
        }
    }
    println!();

    // Merge order
    println!("Merge order:");
    for (i, slug) in merge_order.iter().enumerate() {
        println!("  {}. {}", i + 1, slug);
    }
    println!();

    // Persist the plan to hub branch
    let sync = SyncManager::new(crosslink_dir)?;
    if sync.is_initialized() {
        sync.fetch()?;
        write_hub_json(&sync, "swarm/merge-plan.json", &plan)?;
        commit_hub_files(
            &sync,
            &["swarm/merge-plan.json"],
            &format!(
                "swarm: merge plan for {} agents → {}",
                sources.len(),
                branch
            ),
        )?;
        println!("Plan saved to hub branch (swarm/merge-plan.json).");
    }

    if dry_run {
        println!("Dry run — no changes applied.");
        return Ok(());
    }

    // Create the target branch from the resolved base
    let create_branch = std::process::Command::new("git")
        .current_dir(repo_root)
        .args(["checkout", "-b", branch, &resolved_base])
        .output()
        .context("Failed to create target branch")?;

    if create_branch.status.success() {
        println!("Created branch '{branch}' from {resolved_base}.");
    } else {
        let stderr = String::from_utf8_lossy(&create_branch.stderr);
        // If branch already exists, try to check it out
        if stderr.contains("already exists") {
            let checkout = std::process::Command::new("git")
                .current_dir(repo_root)
                .args(["checkout", branch])
                .output()
                .context("Failed to checkout existing target branch")?;
            if !checkout.status.success() {
                bail!(
                    "Failed to checkout branch '{}': {}",
                    branch,
                    String::from_utf8_lossy(&checkout.stderr)
                );
            }
            println!("Checked out existing branch '{branch}'.");
        } else {
            bail!("Failed to create branch '{branch}': {stderr}");
        }
    }

    // Apply each agent's diff in merge order
    let slug_to_source: std::collections::HashMap<&str, &MergeSource> =
        sources.iter().map(|s| (s.agent_slug.as_str(), s)).collect();

    let mut applied = 0usize;
    let mut failed = Vec::new();

    for slug in &merge_order {
        let Some(source) = slug_to_source.get(slug.as_str()) else {
            continue;
        };

        println!("Applying changes from '{slug}'...");

        // Generate the diff from the agent's worktree
        let diff_output = std::process::Command::new("git")
            .current_dir(&source.worktree_path)
            .args(["diff", &format!("{resolved_base}...HEAD")])
            .output()
            .context("Failed to generate diff")?;

        if !diff_output.status.success() {
            tracing::error!(
                "Failed to generate diff for '{}': {}",
                slug,
                String::from_utf8_lossy(&diff_output.stderr)
            );
            failed.push(slug.clone());
            continue;
        }

        let diff_content = diff_output.stdout;
        if diff_content.is_empty() {
            println!("  No diff to apply for '{slug}'.");
            continue;
        }

        // Apply the diff using git apply
        let mut apply_cmd = std::process::Command::new("git")
            .current_dir(repo_root)
            .args(["apply", "--3way", "--stat", "-"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .context("Failed to start git apply")?;

        if let Some(mut stdin) = apply_cmd.stdin.take() {
            use std::io::Write;
            stdin.write_all(&diff_content)?;
        }

        let apply_result = apply_cmd.wait_with_output()?;

        if !apply_result.status.success() {
            let stderr = String::from_utf8_lossy(&apply_result.stderr);
            tracing::error!(
                "Failed to apply diff for '{}': {} — manual resolution required.",
                slug,
                stderr
            );
            failed.push(slug.clone());

            // INTENTIONAL: checkout to abort partial apply is best-effort — next agent's diff will be applied fresh
            let _ = std::process::Command::new("git")
                .current_dir(repo_root)
                .args(["checkout", "."])
                .output();
            continue;
        }

        // INTENTIONAL: staging is best-effort — commit below will capture whatever was staged
        let _ = std::process::Command::new("git")
            .current_dir(repo_root)
            .args(["add", "-A"])
            .output()?;

        let commit_msg = format!("merge: apply changes from agent '{slug}'");
        let commit_output = std::process::Command::new("git")
            .current_dir(repo_root)
            .args([
                "commit",
                "-m",
                &commit_msg,
                "--no-gpg-sign",
                "--allow-empty",
            ])
            .output()?;

        if commit_output.status.success() {
            println!("  Applied and committed changes from '{slug}'.");
            applied += 1;
        } else {
            let stderr = String::from_utf8_lossy(&commit_output.stderr);
            if stderr.contains("nothing to commit") {
                println!("  No new changes from '{slug}' (already applied).");
            } else {
                tracing::error!("Commit failed for '{}': {}", slug, stderr);
                failed.push(slug.clone());
            }
        }
    }

    println!();
    println!(
        "Merge complete: {} applied, {} failed.",
        applied,
        failed.len()
    );
    if !failed.is_empty() {
        println!("Failed agents: {}", failed.join(", "));
        println!("These agents' changes need manual resolution.");
    }

    Ok(())
}