codetree 0.1.2

AI-native version control system for autonomous 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
use crate::error::{Context, Result};

use crate::branch::{BranchManager, BranchStatus};
use crate::vcs::VcsManager;
use crate::lock::LockManager;
use crate::ops::{Operation, OperationLog};

use super::load_config;
use super::get_active_op_branches_sorted;
use super::auto_snapshot;
use super::save_command;

#[allow(clippy::too_many_arguments)]
pub async fn start_command(description: String, parallel: bool, worktree: bool, branchless: bool, files: Option<Vec<String>>, depends_on: Option<Vec<String>>, template: Option<String>, tags: Option<Vec<String>>, agent_id: Option<String>, wait: bool) -> Result<()> {
    // Auto-snapshot before checkout (non-parallel start switches the working tree).
    if !parallel && !worktree {
        auto_snapshot().await;
    }
    let config = load_config(None).await?;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let mut branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let slug = crate::utils::slugify(&description);

    let branch_prefix = if let Some(template_name) = &template {
        if let Some(tmpl) = config.get_template(template_name) {
            tmpl.branch_prefix.as_deref().unwrap_or(&config.git.branch_prefix)
        } else {
            return Err(format!("Unknown template: '{}'", template_name).into());
        }
    } else {
        &config.git.branch_prefix
    };

    let branch_name = format!("{}_{}_{}", branch_prefix, timestamp, slug);

    let current_branch = git_manager.get_current_branch().await?;
    let base_branch = if let Some(branch) = branch_manager.get_branch(&current_branch) {
        if matches!(branch.status, BranchStatus::Active) {
            if parallel || worktree {
                info!("Creating parallel operation '{}' on branch '{}'", description, branch_name);
            } else {
                info!("Stacking operation '{}' on branch '{}'", description, branch_name);
            }
            current_branch.clone()
        } else {
            config.git.base_branch.clone()
        }
    } else {
        config.git.base_branch.clone()
    };

    let file_list = files.unwrap_or_default();
    let deps = depends_on.unwrap_or_default();
    let tag_list = tags.unwrap_or_default();

    if branchless {
        branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
            .context("Failed to register branch")?;
        if let Some(branch) = branch_manager.branches.get_mut(&branch_name) {
            branch.branchless = true;
        }
        branch_manager.save().await?;
        println!("Created branchless bookmark: {} (on {})", branch_name, current_branch);
    } else if worktree {
        let worktree_path = current_dir.join(".codetree").join("worktrees").join(&branch_name);
        tokio::fs::create_dir_all(&worktree_path).await
            .context("Failed to create worktree directory")?;
        git_manager.add_worktree_new_branch(&branch_name, &worktree_path, &base_branch).await
            .context("Failed to add worktree")?;
        branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
            .context("Failed to register branch")?;
        branch_manager.set_branch_worktree_no_save(&branch_name, worktree_path.clone()).await?;
        branch_manager.save().await?;
        println!("Created operation in worktree: {} at {:?}", branch_name, worktree_path);
    } else {
        git_manager.create_branch(&branch_name, Some(&base_branch)).await
            .context("Failed to create branch")?;

        if parallel {
            branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
                .context("Failed to register branch")?;
            branch_manager.save().await?;
            println!("Created parallel operation on branch: {} (stay on {})", branch_name, current_branch);
        } else {
            git_manager.checkout_branch(&branch_name).await
                .context("Failed to checkout branch")?;
            branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
                .context("Failed to register branch")?;
            if base_branch != config.git.base_branch {
                branch_manager.set_parent_branch_no_save(&branch_name, &base_branch).await?;
            }
            branch_manager.save().await?;
        }
    }

    if !file_list.is_empty() {
        let locks_path = current_dir.join(".codetree").join("locks.json");

        if wait {
            let max_attempts = 150;
            for attempt in 0..max_attempts {
                let conflicts = LockManager::load(locks_path.clone())?
                    .conflicts(&file_list, &branch_name);
                if conflicts.is_empty() {
                    break;
                }
                if attempt == 0 {
                    info!("Waiting for file locks: {}", conflicts.iter()
                        .map(|(f, h)| format!("{} (held by {})", f, h))
                        .collect::<Vec<_>>().join(", "));
                }
                if attempt == max_attempts - 1 {
                    bail!("Timed out waiting for file locks after 5 minutes: {}",
                        conflicts.iter().map(|(f, h)| format!("{} (held by {})", f, h))
                            .collect::<Vec<_>>().join(", "));
                }
                tokio::time::sleep(std::time::Duration::from_secs(2)).await;
            }
        }

        // Acquire atomically: load + conflict-check + persist all run under
        // one exclusive lockfile, so a concurrent agent cannot slip a lock in
        // between our check and our write.
        LockManager::update_atomically(locks_path.clone(), |m| {
            m.acquire(&file_list, &branch_name)
        })?;
        info!("Acquired {} file lock(s) for operation '{}'", file_list.len(), branch_name);
    }

    let ops_path = current_dir.join(".codetree").join("ops.json");
    let mut op_log = OperationLog::new(&ops_path).await?;
    op_log.push(Operation::Start {
        branch: branch_name.clone(),
        timestamp: crate::branch::now_ts(),
        agent_id: agent_id.clone(),
    });
    op_log.save(&ops_path).await?;

    Ok(())
}

pub async fn goto_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    git_manager.goto_commit(&commit).await?;
    let short = &commit[..7.min(commit.len())];
    println!("Checked out commit {} (detached HEAD)", short);
    println!("Use 'codetree switch <branch>' to return to a branch");
    Ok(())
}

/// Navigate to the next commit (child of HEAD in the current branch).
pub async fn next_commit_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let repo = git_manager.repo();

    let head_id = repo.refs().resolve_head()?
        .context("HEAD does not point to a commit")?;

    // Find a commit whose parent is HEAD (the child of HEAD).
    let branches = repo.refs().list_branches()?;
    for branch in &branches {
        if let Some(branch_tip) = repo.refs().get_branch(branch)? {
            // Walk from branch tip to find a commit whose parent is HEAD.
            let mut current = branch_tip.clone();
            let mut found_child = None;
            loop {
                let commit = repo.read_commit(&current)?;
                if !commit.parents.is_empty() && commit.parents[0] == head_id {
                    found_child = Some(current.clone());
                    break;
                }
                if commit.parents.is_empty() {
                    break;
                }
                current = commit.parents[0].clone();
            }
            if let Some(child) = found_child {
                git_manager.goto_commit(&child).await?;
                let short = &child[..7.min(child.len())];
                println!("Moved to next commit: {}", short);
                return Ok(());
            }
        }
    }

    bail!("No next commit found (HEAD has no children on any branch)");
}

/// Navigate to the previous commit (parent of HEAD).
pub async fn prev_commit_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let repo = git_manager.repo();

    let head_id = repo.refs().resolve_head()?
        .context("HEAD does not point to a commit")?;
    let commit = repo.read_commit(&head_id)?;

    if commit.parents.is_empty() {
        bail!("No previous commit (HEAD is the root commit)");
    }

    let parent = &commit.parents[0];
    git_manager.goto_commit(parent).await?;
    let short = &parent[..7.min(parent.len())];
    println!("Moved to previous commit: {}", short);
    Ok(())
}

/// Restack: repair the commit graph by rebuilding any commits whose
/// parents were removed or rewritten. Currently a no-op if the graph
/// is already consistent.
pub async fn restack_graph_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let repo = git_manager.repo();

    let branches = repo.refs().list_branches()?;
    let mut repaired = 0;

    for branch in &branches {
        if let Some(tip) = repo.refs().get_branch(branch)? {
            // Walk the branch and check all parent commits exist.
            let mut current = tip.clone();
            loop {
                let commit = match repo.read_commit(&current) {
                    Ok(c) => c,
                    Err(_) => {
                        // Missing commit — needs restack.
                        repaired += 1;
                        break;
                    }
                };
                if commit.parents.is_empty() {
                    break;
                }
                current = commit.parents[0].clone();
            }
        }
    }

    if repaired == 0 {
        println!("No restack needed — commit graph is consistent.");
    } else {
        println!("Restacked {} broken commit(s).", repaired);
    }

    Ok(())
}

/// Rename a branch (jj bookmark rename).
pub async fn branch_rename_command(old_name: String, new_name: String) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    git_manager.repo().refs().rename_branch(&old_name, &new_name)?;
    println!("Renamed branch '{}' to '{}'", old_name, new_name);
    Ok(())
}

/// Advance a branch to a target commit (jj bookmark advance).
pub async fn branch_advance_command(name: String, commit: Option<String>) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let repo = git_manager.repo();

    let head_id = repo.refs().resolve_head()?
        .context("HEAD does not point to a commit")?;
    let target_id = if let Some(spec) = commit {
        git_manager.resolve_commit_pub(&spec, &head_id)?
    } else {
        head_id
    };

    // Verify the branch exists.
    if repo.refs().get_branch(&name)?.is_none() {
        bail!("Branch '{}' not found", name);
    }

    repo.refs().set_branch(&name, &target_id)?;
    let short = &target_id[..7.min(target_id.len())];
    println!("Advanced branch '{}' to {}", name, short);
    Ok(())
}

pub async fn switch_command(branch_name: String) -> Result<()> {
    let config = load_config(None).await?;
    // Auto-commit policy: if save_on_switch is enabled, save before switching.
    // Otherwise, snapshot the working tree as a safety net.
    if config.auto.save_on_switch {
        let git_manager = VcsManager::new(std::env::current_dir()
            .context("Failed to get current directory")?)?;
        let status = git_manager.get_status().await?;
        if !status.modified.is_empty() || !status.untracked.is_empty() {
            save_command(vec![], false, false, None).await?;
        }
    } else {
        auto_snapshot().await;
    }
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    if branch_name == "-" {
        let last_path = current_dir.join(".codetree").join("last_branch");
        let last_branch = std::fs::read_to_string(&last_path)
            .context("No previous branch to switch to. Use 'codetree switch <branch>' first.")?;
        let last_branch = last_branch.trim().to_string();
        if last_branch.is_empty() {
            bail!("No previous branch recorded");
        }
        let current = git_manager.get_current_branch().await?;
        if current == last_branch {
            println!("Already on branch: {}", last_branch);
            return Ok(());
        }
        crate::atomic::write_atomic(&last_path, current.as_bytes())?;
        git_manager.checkout_branch(&last_branch).await
            .context("Failed to checkout branch")?;
        println!("Switched to branch: {}", last_branch);
        return Ok(());
    }

    if let Some(branch) = branch_manager.get_branch(&branch_name) {
        if !matches!(branch.status, BranchStatus::Active) {
            return Err(format!("Branch '{}' is not active (status: {})", branch_name, branch.status.as_str()).into());
        }
    } else {
        return Err(format!("Branch '{}' is not tracked by codetree", branch_name).into());
    }

    let current = git_manager.get_current_branch().await?;
    if current == branch_name {
        println!("Already on branch: {}", branch_name);
        return Ok(());
    }

    let status = git_manager.get_status().await?;
    let dirty = !status.modified.is_empty() || !status.untracked.is_empty() || !status.staged.is_empty();
    if dirty {
        warn!("Switching from '{}' with uncommitted changes; they will be left in working tree", current);
    }

    let last_path = current_dir.join(".codetree").join("last_branch");
    crate::atomic::write_atomic(&last_path, current.as_bytes())?;

    git_manager.checkout_branch(&branch_name).await
        .context("Failed to checkout branch")?;

    println!("Switched to branch: {}", branch_name);
    Ok(())
}

pub async fn next_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let current = git_manager.get_current_branch().await?;
    let branches = get_active_op_branches_sorted(&current_dir).await?;

    if branches.is_empty() {
        return Err("No active operations to switch to".into());
    }

    let target = if let Some(pos) = branches.iter().position(|b| b == &current) {
        branches[(pos + 1) % branches.len()].clone()
    } else {
        branches[0].clone()
    };

    if target == current {
        println!("Already on the last operation; wrapping to first: {}", target);
    }

    switch_command(target.clone()).await?;
    println!("Next operation: {}", target);
    Ok(())
}

pub async fn prev_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let current = git_manager.get_current_branch().await?;
    let branches = get_active_op_branches_sorted(&current_dir).await?;

    if branches.is_empty() {
        return Err("No active operations to switch to".into());
    }

    let target = if let Some(pos) = branches.iter().position(|b| b == &current) {
        if pos == 0 {
            branches[branches.len() - 1].clone()
        } else {
            branches[pos - 1].clone()
        }
    } else {
        branches[branches.len() - 1].clone()
    };

    if target == current {
        println!("Already on the first operation; wrapping to last: {}", target);
    }

    switch_command(target.clone()).await?;
    println!("Previous operation: {}", target);
    Ok(())
}