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
// E-ana tablet — prune command: squash hub/knowledge branch history for storage efficiency
use anyhow::{bail, Context, Result};
use serde::Serialize;
use std::path::Path;
use std::process::Command;

use crate::knowledge::KnowledgeManager;
use crate::sync::SyncManager;

/// Options for the prune command.
pub struct PruneOpts {
    pub dry_run: bool,
    pub force: bool,
    pub keep_commits: usize,
    pub hub_only: bool,
    pub knowledge_only: bool,
}

/// Size stats for a branch before/after pruning.
#[derive(Debug, Serialize)]
struct BranchStats {
    branch: String,
    commits_before: usize,
    commits_after: usize,
}

/// Run a git command in the given directory, returning its output.
fn git_in_dir(dir: &Path, args: &[&str]) -> Result<std::process::Output> {
    let output = Command::new("git")
        .current_dir(dir)
        .args(args)
        .output()
        .with_context(|| format!("Failed to run git {:?} in {}", args, dir.display()))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git {:?} in {} failed: {}",
            args,
            dir.display(),
            stderr.trim()
        );
    }
    Ok(output)
}

/// Count the number of commits on the current branch in a worktree.
fn count_commits(cache_dir: &Path) -> Result<usize> {
    let output = git_in_dir(cache_dir, &["rev-list", "--count", "HEAD"])?;
    let count_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    count_str
        .parse::<usize>()
        .with_context(|| format!("Failed to parse commit count: {count_str:?}"))
}

/// Remove stale data files from the hub branch cache.
///
/// Cleans up old heartbeat files (V1 layout) and agent directories
/// for decommissioned agents (those with no events).
fn remove_stale_hub_data(cache_dir: &Path) -> Result<Vec<String>> {
    let mut removed = Vec::new();

    // Clean up old V1 heartbeat files
    let heartbeats_dir = cache_dir.join("heartbeats");
    if heartbeats_dir.is_dir() {
        for entry in std::fs::read_dir(&heartbeats_dir)? {
            let entry = entry?;
            if entry.file_type()?.is_file() {
                let name = entry.file_name().to_string_lossy().to_string();
                removed.push(format!("heartbeats/{name}"));
                std::fs::remove_file(entry.path())?;
            }
        }
        // Remove the directory if now empty
        if std::fs::read_dir(&heartbeats_dir)?.next().is_none() {
            std::fs::remove_dir(&heartbeats_dir)?;
        }
    }

    // Clean up agent directories for decommissioned agents
    // (those whose events.log is empty or missing)
    let agents_dir = cache_dir.join("agents");
    if agents_dir.is_dir() {
        for entry in std::fs::read_dir(&agents_dir)? {
            let entry = entry?;
            if !entry.file_type()?.is_dir() {
                continue;
            }
            let agent_dir = entry.path();
            let events_log = agent_dir.join("events.log");
            let has_events =
                events_log.exists() && std::fs::metadata(&events_log).is_ok_and(|m| m.len() > 0);

            if !has_events {
                let agent_name = entry.file_name().to_string_lossy().to_string();
                removed.push(format!("agents/{agent_name}/"));
                std::fs::remove_dir_all(&agent_dir)?;
            }
        }
    }

    Ok(removed)
}

/// Count stale data files without removing them (for dry-run).
fn count_stale_hub_data(cache_dir: &Path) -> Vec<String> {
    let mut stale = Vec::new();

    let heartbeats_dir = cache_dir.join("heartbeats");
    if heartbeats_dir.is_dir() {
        if let Ok(entries) = std::fs::read_dir(&heartbeats_dir) {
            for entry in entries.flatten() {
                if entry.file_type().is_ok_and(|t| t.is_file()) {
                    stale.push(format!(
                        "heartbeats/{}",
                        entry.file_name().to_string_lossy()
                    ));
                }
            }
        }
    }

    let agents_dir = cache_dir.join("agents");
    if agents_dir.is_dir() {
        if let Ok(entries) = std::fs::read_dir(&agents_dir) {
            for entry in entries.flatten() {
                if !entry.file_type().is_ok_and(|t| t.is_dir()) {
                    continue;
                }
                let events_log = entry.path().join("events.log");
                let has_events = events_log.exists()
                    && std::fs::metadata(&events_log).is_ok_and(|m| m.len() > 0);
                if !has_events {
                    stale.push(format!("agents/{}/", entry.file_name().to_string_lossy()));
                }
            }
        }
    }

    stale
}

/// Squash the history of a branch in a cache worktree.
///
/// Creates a new orphan commit (or keeps the last N commits) with the current
/// tree state, then force-updates the branch ref and force-pushes.
fn squash_branch(
    cache_dir: &Path,
    branch: &str,
    remote: &str,
    keep_commits: usize,
    dry_run: bool,
) -> Result<BranchStats> {
    let commits_before = count_commits(cache_dir)?;

    if commits_before <= keep_commits.max(1) {
        return Ok(BranchStats {
            branch: branch.to_string(),
            commits_before,
            commits_after: commits_before,
        });
    }

    if dry_run {
        let commits_after = keep_commits.max(1);
        return Ok(BranchStats {
            branch: branch.to_string(),
            commits_before,
            commits_after,
        });
    }

    let commits_after = if keep_commits <= 1 {
        // Squash everything into a single commit with the current tree.
        // 1. Stage all current content (ensures index matches worktree)
        git_in_dir(cache_dir, &["add", "-A"])?;

        // 2. Write the current index as a tree object
        let tree_output = git_in_dir(cache_dir, &["write-tree"])?;
        let tree_hash = String::from_utf8_lossy(&tree_output.stdout)
            .trim()
            .to_string();

        // 3. Create a root commit (no parent) with this tree
        let commit_output = Command::new("git")
            .current_dir(cache_dir)
            .args([
                "commit-tree",
                &tree_hash,
                "-m",
                &format!(
                    "prune: squash {branch} history to current state\n\nSquashed {commits_before} commit(s)."
                ),
            ])
            .output()
            .context("Failed to create squash commit")?;

        if !commit_output.status.success() {
            let stderr = String::from_utf8_lossy(&commit_output.stderr);
            bail!("git commit-tree failed: {}", stderr.trim());
        }

        let new_head = String::from_utf8_lossy(&commit_output.stdout)
            .trim()
            .to_string();

        // 4. Update the branch ref to the new root commit
        git_in_dir(
            cache_dir,
            &["update-ref", &format!("refs/heads/{branch}"), &new_head],
        )?;

        // 5. Reset HEAD to the new commit
        git_in_dir(cache_dir, &["reset", "--hard", &new_head])?;

        1
    } else {
        // Keep last N commits: rewrite history preserving recent commits.
        // Find the base commit (Nth from HEAD)
        let base_ref = format!("HEAD~{keep_commits}");
        let base_hash_output = git_in_dir(cache_dir, &["rev-parse", &base_ref])?;
        let base_hash = String::from_utf8_lossy(&base_hash_output.stdout)
            .trim()
            .to_string();

        // Get the tree at the base commit
        let tree_output = git_in_dir(cache_dir, &["rev-parse", &format!("{base_hash}^{{tree}}")])?;
        let tree_hash = String::from_utf8_lossy(&tree_output.stdout)
            .trim()
            .to_string();

        // Create a new root commit with the base tree
        let commit_output = Command::new("git")
            .current_dir(cache_dir)
            .args([
                "commit-tree",
                &tree_hash,
                "-m",
                &format!(
                    "prune: squash {} history (kept last {} commits)\n\nSquashed {} commit(s).",
                    branch,
                    keep_commits,
                    commits_before - keep_commits
                ),
            ])
            .output()
            .context("Failed to create base squash commit")?;

        if !commit_output.status.success() {
            let stderr = String::from_utf8_lossy(&commit_output.stderr);
            bail!("git commit-tree failed: {}", stderr.trim());
        }

        let new_base = String::from_utf8_lossy(&commit_output.stdout)
            .trim()
            .to_string();

        // Save current tip
        let tip_output = git_in_dir(cache_dir, &["rev-parse", "HEAD"])?;
        let tip_hash = String::from_utf8_lossy(&tip_output.stdout)
            .trim()
            .to_string();

        // Detach, reset to new base, cherry-pick the kept commits
        git_in_dir(cache_dir, &["checkout", "--detach", "HEAD"])?;
        git_in_dir(cache_dir, &["reset", "--hard", &new_base])?;

        // Get list of commits to replay (oldest first)
        let range = format!("{base_hash}..{tip_hash}");
        let log_output = git_in_dir(cache_dir, &["rev-list", "--reverse", &range])?;
        let log_text = String::from_utf8_lossy(&log_output.stdout)
            .trim()
            .to_string();

        for commit_hash in log_text.lines() {
            if !commit_hash.is_empty() {
                git_in_dir(cache_dir, &["cherry-pick", commit_hash])?;
            }
        }

        // Update the branch ref to point to the new history
        let new_tip_output = git_in_dir(cache_dir, &["rev-parse", "HEAD"])?;
        let new_tip = String::from_utf8_lossy(&new_tip_output.stdout)
            .trim()
            .to_string();
        git_in_dir(
            cache_dir,
            &["update-ref", &format!("refs/heads/{branch}"), &new_tip],
        )?;
        git_in_dir(cache_dir, &["checkout", branch])?;

        keep_commits + 1 // base squash commit + kept commits
    };

    // Force-push the rewritten branch
    let refspec = format!("{branch}:{branch}");
    git_in_dir(cache_dir, &["push", "--force", remote, &refspec])?;

    Ok(BranchStats {
        branch: branch.to_string(),
        commits_before,
        commits_after,
    })
}

/// Entry point for `crosslink prune`.
pub fn run(crosslink_dir: &Path, opts: &PruneOpts, json: bool) -> Result<()> {
    if !opts.force && !opts.dry_run {
        tracing::warn!("This will rewrite branch history and force-push.");
        println!("Use --force to confirm, or --dry-run to preview.");
        return Ok(());
    }

    let mut results: Vec<BranchStats> = Vec::new();
    let mut stale_removed: Vec<String> = Vec::new();

    // --- Hub branch ---
    if !opts.knowledge_only {
        let sync = SyncManager::new(crosslink_dir)?;
        sync.init_cache()?;
        sync.fetch()?;

        let cache_dir = sync.cache_path();

        if opts.dry_run {
            stale_removed = count_stale_hub_data(cache_dir);
        } else {
            let removed = remove_stale_hub_data(cache_dir)?;
            if !removed.is_empty() {
                // INTENTIONAL: staging is best-effort — we check for actual changes before committing
                let _ = git_in_dir(cache_dir, &["add", "-A"]);
                let has_changes = git_in_dir(cache_dir, &["diff", "--cached", "--quiet"]).is_err();
                if has_changes {
                    git_in_dir(cache_dir, &["commit", "-m", "prune: remove stale hub data"])?;
                }
                stale_removed = removed;
            }
        }

        let stats = squash_branch(
            cache_dir,
            "crosslink/hub",
            sync.remote(),
            opts.keep_commits,
            opts.dry_run,
        )?;
        results.push(stats);
    }

    // --- Knowledge branch ---
    if !opts.hub_only {
        let km = KnowledgeManager::new(crosslink_dir)?;
        if km.is_initialized() {
            km.init_cache()?;
            km.sync()?;

            let cache_dir = km.cache_path();
            let remote = crate::sync::read_tracker_remote(km.crosslink_dir());

            let stats = squash_branch(
                cache_dir,
                "crosslink/knowledge",
                &remote,
                opts.keep_commits,
                opts.dry_run,
            )?;
            results.push(stats);
        } else {
            tracing::info!("Knowledge branch not initialized, skipping.");
        }
    }

    // --- Output ---
    if json {
        #[derive(Serialize)]
        struct PruneReport {
            branches: Vec<BranchStats>,
            stale_data_removed: Vec<String>,
            dry_run: bool,
        }
        let report = PruneReport {
            branches: results,
            stale_data_removed: stale_removed,
            dry_run: opts.dry_run,
        };
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(());
    }

    // Human-readable output
    if opts.dry_run {
        println!("Prune plan (dry run):\n");
    }

    for stats in &results {
        if stats.commits_before == stats.commits_after {
            println!(
                "  {}{} commit(s), nothing to prune",
                stats.branch, stats.commits_before
            );
        } else {
            let verb = if opts.dry_run {
                "would remove"
            } else {
                "removed"
            };
            println!(
                "  {}{}{} commit(s) ({} {})",
                stats.branch,
                stats.commits_before,
                stats.commits_after,
                stats.commits_before - stats.commits_after,
                verb,
            );
        }
    }

    if !stale_removed.is_empty() {
        println!(
            "\n  Stale data {}: {} file(s)/dir(s)",
            if opts.dry_run { "to remove" } else { "removed" },
            stale_removed.len()
        );
        for item in &stale_removed {
            println!("    {item}");
        }
    }

    if opts.dry_run {
        println!("\nRun with --force (without --dry-run) to proceed.");
    } else {
        println!("\nDone.");
    }

    Ok(())
}