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
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
//! History surgery (jj-style): amend, reword, squash, move, abandon, fold,
//! revert, absorb, and other commit-rewriting operations on VcsManager.

use crate::error::{Context, Result};
use super::objects::{Tree, TreeEntry, Commit};
use super::manager::VcsManager;

impl VcsManager {
    /// Amend the HEAD commit with current staged changes.
    pub async fn amend_commit(&self) -> Result<String> {
        let index = self.repo.load_index()?;

        // Build tree from index
        let entries: Vec<TreeEntry> = index.entries_sorted().into_iter().map(|(path, blob_id)| {
            TreeEntry { mode: 0o100644, name: path, id: blob_id }
        }).collect();
        let tree = Tree::new(entries);
        let tree_id = self.repo.write_tree(&tree)?;

        // Get current HEAD commit for message and parents
        let head_id = self
            .repo
            .refs()
            .resolve_head()?
            .context("HEAD does not point to a commit")?;
        let head_commit = self.repo.read_commit(&head_id)?;

        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        let new_commit = Commit::new(
            tree_id,
            head_commit.parents.clone(),
            head_commit.author.clone(),
            head_commit.message.clone(),
            timestamp,
        );
        let new_id = self.repo.write_commit(&new_commit)?;

        // Update branch ref
        if let Some(branch) = self.repo.refs().current_branch()? {
            self.repo.refs().set_branch(&branch, &new_id)?;
        }

        Ok(new_id)
    }

    /// Rewrite a commit's message. Rebuilds all descendants on the current
    /// branch. Returns the new HEAD commit hash.
    pub async fn reword(&self, commit_spec: &str, new_message: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let commit_spec = commit_spec.to_string();
        let new_message = new_message.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            // Resolve the target commit.
            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;

            // Walk from HEAD to the target, collecting descendants (newest first).
            let mut descendants: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                if current == target_id {
                    break;
                }
                descendants.push(current.clone());
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &commit_spec);
                }
                current = commit.parents[0].clone();
            }

            // Rewrite the target commit's message.
            let target_commit = repo.read_commit(&target_id)?;
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let new_target = Commit::new(
                target_commit.tree,
                target_commit.parents.clone(),
                target_commit.author.clone(),
                new_message,
                timestamp,
            );
            let new_target_id = repo.write_commit(&new_target)?;

            // Rebuild descendants in reverse order (oldest first).
            let mut new_parent = new_target_id.clone();
            for old_hash in descendants.iter().rev() {
                let old_commit = repo.read_commit(old_hash)?;
                let new_commit = Commit::new(
                    old_commit.tree,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    old_commit.timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            // Update branch ref to the new HEAD.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_parent)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&new_parent)?;
            mgr.restore_working_tree_pub(&new_parent)?;

            Ok(new_parent)
        })
        .await?
    }

    /// Resolve a commit spec (hash prefix, "HEAD", "HEAD~N") to a full hash.
    /// Amend working-tree changes into a specific commit (not just HEAD).
    /// The target commit's tree is updated with working-tree changes for
    /// files that exist in the target. New files are only added if the
    /// target is HEAD. Descendants are rebuilt. Returns the new HEAD hash.
    pub async fn amend_to(&self, commit_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let commit_spec = commit_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;

            // Compute working-tree modified files.
            let head_tree = mgr.head_tree()?;
            let head_map: std::collections::HashMap<String, String> = head_tree
                .entries.iter().map(|e| (e.name.clone(), e.id.clone())).collect();

            let wt_files = mgr.walk_working_tree(&repo_path)?;
            let mut wt_changes: Vec<(String, String)> = Vec::new();
            for file in &wt_files {
                let relative = file.strip_prefix(&repo_path).unwrap_or(file);
                let relative_str = relative.to_string_lossy().to_string();
                let content = std::fs::read(file)
                    .with_context(|| format!("amend --to: read file {:?}", file))?;
                let blob_id = repo.write_blob(&content)?;
                match head_map.get(&relative_str) {
                    Some(h) if *h == blob_id => {} // unchanged
                    _ => wt_changes.push((relative_str, blob_id)),
                }
            }

            if wt_changes.is_empty() {
                bail!("No uncommitted changes to amend");
            }

            // Collect descendants (commits from HEAD to target, excluding target).
            let mut descendants: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            let is_head = current == target_id;
            loop {
                if current == target_id {
                    break;
                }
                descendants.push(current.clone());
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &commit_spec);
                }
                current = commit.parents[0].clone();
            }

            // Build the new target tree.
            let target_commit = repo.read_commit(&target_id)?;
            let target_tree = repo.read_tree(&target_commit.tree)?;
            let mut target_entries = target_tree.entries.clone();
            let target_map: std::collections::HashMap<String, usize> = target_tree
                .entries.iter().enumerate().map(|(i, e)| (e.name.clone(), i)).collect();

            let mut amended_files = Vec::new();
            for (path, new_blob) in &wt_changes {
                if let Some(&idx) = target_map.get(path) {
                    if new_blob.is_empty() {
                        target_entries[idx] = TreeEntry { mode: 0, name: String::new(), id: String::new() };
                    } else {
                        target_entries[idx].id = new_blob.clone();
                    }
                    amended_files.push(path.clone());
                } else if !new_blob.is_empty() && is_head {
                    target_entries.push(TreeEntry { mode: 0o100644, name: path.clone(), id: new_blob.clone() });
                    amended_files.push(path.clone());
                }
            }
            target_entries.retain(|e| e.mode != 0);

            let new_tree = Tree::new(target_entries);
            let new_tree_id = repo.write_tree(&new_tree)?;

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let new_target = Commit::new(
                new_tree_id,
                target_commit.parents.clone(),
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let new_target_id = repo.write_commit(&new_target)?;

            // Rebuild descendants.
            let amended_set: std::collections::HashSet<&str> =
                amended_files.iter().map(|s| s.as_str()).collect();

            let mut new_parent = new_target_id.clone();
            for old_hash in descendants.iter().rev() {
                let old_commit = repo.read_commit(old_hash)?;
                let old_tree = repo.read_tree(&old_commit.tree)?;

                let mut new_entries = old_tree.entries.clone();
                for entry in &mut new_entries {
                    if amended_set.contains(entry.name.as_str())
                        && let Some(blob) = wt_changes.iter().find(|(p, _)| p == &entry.name).map(|(_, b)| b)
                        && !blob.is_empty()
                    {
                        entry.id = blob.clone();
                    }
                }

                let new_tree = Tree::new(new_entries);
                let new_tree_id = repo.write_tree(&new_tree)?;
                let new_commit = Commit::new(
                    new_tree_id,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    old_commit.timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            // Update branch ref.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_parent)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&new_parent)?;
            mgr.restore_working_tree_pub(&new_parent)?;

            Ok(new_parent)
        })
        .await?
    }

    /// Restore a commit's tree contents from another commit (jj restore).
    /// Replaces the target commit's tree with the source commit's tree,
    /// rebuilding descendants. Returns the new HEAD hash.
    pub async fn restore(&self, from_spec: &str, to_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let from_spec = from_spec.to_string();
        let to_spec = to_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let from_id = mgr.resolve_commit(&from_spec, &head_id)?;
            let to_id = mgr.resolve_commit(&to_spec, &head_id)?;

            let from_commit = repo.read_commit(&from_id)?;
            let to_commit = repo.read_commit(&to_id)?;

            // Create a new commit with to's metadata but from's tree.
            let restored = Commit::new(
                from_commit.tree,
                to_commit.parents.clone(),
                to_commit.author.clone(),
                to_commit.message.clone(),
                to_commit.timestamp,
            );
            let new_to_id = repo.write_commit(&restored)?;

            // Rebuild descendants of `to` onto the restored commit.
            let mut descendants: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                if current == to_id {
                    break;
                }
                descendants.push(current.clone());
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", to_spec);
                }
                current = commit.parents[0].clone();
            }

            let mut new_parent = new_to_id;
            for old_hash in descendants.iter().rev() {
                let old_commit = repo.read_commit(old_hash)?;
                let new_commit = Commit::new(
                    old_commit.tree,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    old_commit.timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_parent)?;
            }

            mgr.sync_index_to_commit(&new_parent)?;
            mgr.restore_working_tree_pub(&new_parent)?;

            Ok(new_parent)
        })
        .await?
    }

    /// Move (reparent) a commit onto a new parent. The commit's tree is
    /// preserved — only the parent pointer changes. All descendants are
    /// rebuilt. Returns the new HEAD hash.
    pub async fn move_commit(&self, commit_spec: &str, onto_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let commit_spec = commit_spec.to_string();
        let onto_spec = onto_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;
            let new_parent_id = mgr.resolve_commit(&onto_spec, &head_id)?;

            // Prevent moving a commit onto itself or one of its descendants.
            if target_id == new_parent_id {
                bail!("Cannot move a commit onto itself");
            }

            // Collect descendants of the target (commits from HEAD to target,
            // excluding the target itself).
            let mut descendants: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                if current == target_id {
                    break;
                }
                descendants.push(current.clone());
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &commit_spec);
                }
                current = commit.parents[0].clone();
            }

            // Check that the new parent is not a descendant of the target.
            if descendants.contains(&new_parent_id) {
                bail!("Cannot move a commit onto one of its own descendants");
            }

            // Create the moved commit: same tree and message, new parent.
            let target_commit = repo.read_commit(&target_id)?;
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let moved = Commit::new(
                target_commit.tree,
                vec![new_parent_id.clone()],
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let moved_id = repo.write_commit(&moved)?;

            // Rebuild descendants in reverse order (oldest first).
            let mut new_parent = moved_id.clone();
            for old_hash in descendants.iter().rev() {
                let old_commit = repo.read_commit(old_hash)?;
                let new_commit = Commit::new(
                    old_commit.tree,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    old_commit.timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            // Update branch ref.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_parent)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&new_parent)?;
            mgr.restore_working_tree_pub(&new_parent)?;

            Ok(new_parent)
        })
        .await?
    }

    /// Revert a commit: create a new commit on top of HEAD that undoes the
    /// changes introduced by the target commit. Uses a 3-way merge with
    /// base=target_tree, ours=head_tree, theirs=target_parent_tree.
    /// Returns the new HEAD hash.
    pub async fn revert(&self, commit_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let commit_spec = commit_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;
            let target_commit = repo.read_commit(&target_id)?;

            if target_commit.parents.is_empty() {
                bail!("Cannot revert the root commit");
            }

            let parent_id = &target_commit.parents[0];
            let parent_commit = repo.read_commit(parent_id)?;

            // 3-way merge: base = target's tree, ours = HEAD's tree, theirs = parent's tree.
            // This reverses the target's changes.
            let base_tree = repo.read_tree(&target_commit.tree)?;
            let our_tree = mgr.head_tree()?;
            let their_tree = repo.read_tree(&parent_commit.tree)?;

            let (merged_entries, conflicts) = mgr.merge_trees(&base_tree, &our_tree, &their_tree)?;

            if !conflicts.is_empty() {
                let conflict_files: Vec<_> = conflicts.iter().map(|c| c.path.clone()).collect();
                bail!("Revert conflicts in: {}. Resolve manually.", conflict_files.join(", "));
            }

            let new_tree = Tree::new(merged_entries);
            let new_tree_id = repo.write_tree(&new_tree)?;

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let message = format!("Revert \"{}\"", target_commit.message.lines().next().unwrap_or(""));
            let new_commit = Commit::new(
                new_tree_id,
                vec![head_id.clone()],
                target_commit.author.clone(),
                message,
                timestamp,
            );
            let new_id = repo.write_commit(&new_commit)?;

            // Update branch ref.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_id)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&new_id)?;
            mgr.restore_working_tree_pub(&new_id)?;

            Ok(new_id)
        })
        .await?
    }

}