codetree 0.1.1

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
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
//! 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::{object_path, Tree, TreeEntry, Commit};
use super::manager::{commit_tree_entries, AbsorbResult, 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 };

            // 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?
    }

    /// Squash a commit into its parent. The commit's tree is merged into
    /// the parent's tree (3-way merge with the commit as "theirs" and parent
    /// as "ours"), and the resulting commit replaces the parent. All
    /// descendants are rebuilt. Returns the new HEAD hash.
    pub async fn squash(&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 };

            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 squash the root commit");
            }
            let parent_id = &target_commit.parents[0];
            let parent_commit = repo.read_commit(parent_id)?;

            // The squashed commit uses the target's tree (which includes
            // all changes from both the parent and the target).
            // The message combines both messages.
            let combined_message = if parent_commit.message == target_commit.message {
                target_commit.message.clone()
            } else {
                format!("{}\n\n{}", parent_commit.message, target_commit.message)
            };

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

            let squashed = Commit::new(
                target_commit.tree,
                parent_commit.parents.clone(),
                parent_commit.author.clone(),
                combined_message,
                timestamp,
            );
            let squashed_id = repo.write_commit(&squashed)?;

            // 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();
            }

            // Rebuild descendants in reverse order (oldest first).
            let mut new_parent = squashed_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?
    }

    /// 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 };

            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?
    }

    /// Unsquash a commit: split it back into two commits (the original parent
    /// tree + a new commit with the diff). This is the reverse of `squash`.
    /// Requires that the squashed commit has a grandparent (i.e., the original
    /// parent had parents). Returns the new HEAD hash.
    pub async fn unsquash(&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 };

            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 unsquash the root commit (no parent to split from)");
            }

            let parent_id = &target_commit.parents[0];
            let parent_commit = repo.read_commit(parent_id)?;
            if parent_commit.parents.is_empty() {
                bail!("Cannot unsquash: parent commit is the root (no grandparent to restore)");
            }

            // The unsquash creates two commits:
            // 1. A restored parent commit with the grandparent's tree and the
            //    parent's original message (we don't have the original parent
            //    message, so we use a default).
            // 2. A new commit with the target's tree, parented to the restored
            //    parent, with the target's message.
            //
            // Since we can't recover the original parent's tree (it was
            // destroyed during squash), we use the grandparent's tree as the
            // restored parent's tree. This effectively splits the squashed
            // commit into: "empty parent" + "all changes".
            let grandparent_id = &parent_commit.parents[0];
            let grandparent_commit = repo.read_commit(grandparent_id)?;

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

            // Restored parent: grandparent's tree, grandparent as parent.
            let restored_parent = Commit::new(
                grandparent_commit.tree,
                vec![grandparent_id.clone()],
                parent_commit.author.clone(),
                format!("{} (restored)", parent_commit.message),
                timestamp,
            );
            let restored_id = repo.write_commit(&restored_parent)?;

            // New commit: target's tree, restored parent as parent.
            let new_commit = Commit::new(
                target_commit.tree,
                vec![restored_id.clone()],
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let new_commit_id = repo.write_commit(&new_commit)?;

            // Collect descendants of the target.
            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();
            }

            // Rebuild descendants.
            let mut new_parent = new_commit_id.clone();
            for old_hash in descendants.iter().rev() {
                let old_commit = repo.read_commit(old_hash)?;
                let rebuilt = 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(&rebuilt)?;
            }

            // 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?
    }

    /// 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 };

            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?
    }

    /// Squash the current HEAD commit into a specific ancestor commit
    /// (not just the parent). The HEAD's tree replaces the ancestor's tree,
    /// messages are combined, and descendants between them are rebuilt.
    /// Returns the new HEAD hash.
    pub async fn squash_into(&self, into_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let into_spec = into_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 };

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

            if target_id == head_id {
                bail!("Cannot squash HEAD into itself");
            }

            let head_commit = repo.read_commit(&head_id)?;
            let target_commit = repo.read_commit(&target_id)?;

            // The squashed commit uses HEAD's tree (which includes all changes
            // from the target through HEAD).
            let combined_message = if target_commit.message == head_commit.message {
                head_commit.message.clone()
            } else {
                format!("{}\n\n{}", target_commit.message, head_commit.message)
            };

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

            let squashed = Commit::new(
                head_commit.tree,
                target_commit.parents.clone(),
                target_commit.author.clone(),
                combined_message,
                timestamp,
            );
            let squashed_id = repo.write_commit(&squashed)?;

            // Collect descendants of the target (commits from HEAD to target,
            // excluding both).
            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", &into_spec);
                }
                current = commit.parents[0].clone();
            }

            // Rebuild descendants (excluding HEAD, which was squashed into target).
            // The last descendant (HEAD) is skipped — its changes are now in the
            // squashed commit. Other descendants keep their trees.
            let mut new_parent = squashed_id.clone();
            for old_hash in descendants.iter().rev().skip(1) {
                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?
    }

    /// Revive an abandoned commit: restore it onto HEAD as a new commit.
    /// The revived commit gets HEAD as its parent and the abandoned commit's tree.
    /// Returns the new HEAD hash.
    pub async fn revive(&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 };

            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)?;

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

            let revived = Commit::new(
                target_commit.tree,
                vec![head_id.clone()],
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let new_id = repo.write_commit(&revived)?;

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

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

            Ok(new_id)
        })
        .await?
    }

    /// Duplicate a commit: create a copy on top of HEAD with the same tree
    /// and metadata. Useful for experimenting with variations.
    /// Returns the new HEAD hash.
    pub async fn duplicate(&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 };

            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)?;

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

            let duplicated = Commit::new(
                target_commit.tree,
                vec![head_id.clone()],
                target_commit.author.clone(),
                format!("{} (duplicated)", target_commit.message),
                timestamp,
            );
            let new_id = repo.write_commit(&duplicated)?;

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

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

            Ok(new_id)
        })
        .await?
    }

    /// Abandon a commit: remove it from the branch and rebuild descendants
    /// onto its parent. Unlike `withdraw` (which removes an entire operation),
    /// `abandon` works on individual commits. Returns the new HEAD hash.
    pub async fn abandon(&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 };

            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 abandon the root commit");
            }
            let new_parent_id = target_commit.parents[0].clone();

            // Collect descendants (commits from HEAD to target, excluding target).
            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();
            }

            // If no descendants, just move branch to target's parent.
            if descendants.is_empty() {
                if let Some(branch) = repo.refs().current_branch()? {
                    repo.refs().set_branch(&branch, &new_parent_id)?;
                }
                mgr.sync_index_to_commit(&new_parent_id)?;
                mgr.restore_working_tree_pub(&new_parent_id)?;
                return Ok(new_parent_id);
            }

            // Rebuild descendants onto target's parent, skipping the target.
            let mut new_parent = new_parent_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)?;
            }

            // 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?
    }

    /// Forget a commit: abandon it AND remove it from the object store.
    /// Unlike abandon, the commit cannot be revived afterward.
    pub async fn forget(&self, commit_spec: &str) -> Result<String> {
        let new_head = self.abandon(commit_spec).await?;

        // Remove the forgotten commit's objects from the store.
        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let target_id = self.resolve_commit_pub(commit_spec, &head_id)?;

        // Best-effort deletion of the commit object.
        // The gc command will clean up any orphaned trees/blobs.
        let commit_path = object_path(self.repo.root(), &target_id);
        if commit_path.exists() {
            let _ = std::fs::remove_file(&commit_path);
        }

        Ok(new_head)
    }

    /// Fold a range of commits (from the specified commit to HEAD) into a
    /// single commit. The folded commit uses HEAD's tree and combines all
    /// messages in the range. Returns the new HEAD hash.
    pub async fn fold(&self, from_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let from_spec = from_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 };

            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)?;

            if from_id == head_id {
                bail!("Cannot fold a single commit (from == HEAD)");
            }

            // Collect all commits in the range [from, HEAD].
            let mut commits_in_range: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                commits_in_range.push(current.clone());
                if current == from_id {
                    break;
                }
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &from_spec);
                }
                current = commit.parents[0].clone();
            }

            // The from commit's parent is the new folded commit's parent.
            let from_commit = repo.read_commit(&from_id)?;
            if from_commit.parents.is_empty() {
                bail!("Cannot fold from the root commit");
            }
            let new_parent_id = &from_commit.parents[0];

            // Collect all messages (oldest first).
            let mut messages: Vec<String> = Vec::new();
            for hash in commits_in_range.iter().rev() {
                let commit = repo.read_commit(hash)?;
                messages.push(commit.message.clone());
            }
            let combined_message = messages.join("\n\n");

            // The folded commit uses HEAD's tree.
            let head_commit = 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 folded = Commit::new(
                head_commit.tree,
                vec![new_parent_id.clone()],
                head_commit.author.clone(),
                combined_message,
                timestamp,
            );
            let folded_id = repo.write_commit(&folded)?;

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

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

            Ok(folded_id)
        })
        .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 };

            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?
    }

    /// Absorb uncommitted working-tree changes into the best-matching commit
    /// in the current branch's history (Sapling-style). Returns the new HEAD
    /// commit hash and a description of what was absorbed.
    ///
    /// Algorithm:
    /// 1. Walk the working tree and compute modified files (vs HEAD tree).
    /// 2. Walk back through commits on the current branch (HEAD, HEAD~1, …).
    /// 3. For each commit, compute its changed files (diff vs its parent).
    /// 4. Pick the commit with the most file overlap with the working tree.
    /// 5. Amend that commit's tree with the new content for overlapping files.
    /// 6. Rebuild descendants: for each file in the absorbed set, if the
    ///    descendant didn't change it, take the new version; otherwise keep
    ///    the descendant's version.
    /// 7. Update the branch ref, sync index + working tree to new HEAD.
    pub async fn absorb(&self) -> Result<AbsorbResult> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        tokio::task::spawn_blocking(move || -> Result<AbsorbResult> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0 };

            // 1. Compute working-tree modified files (path -> new blob id).
            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(); // (path, new_blob_id)
            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!("absorb: read wt 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)),
                }
            }
            // Deleted files (in HEAD but not in working tree)
            let wt_set: std::collections::HashSet<&str> =
                wt_files.iter().map(|f| f.strip_prefix(&repo_path).unwrap_or(f).to_str().unwrap()).collect();
            for name in head_map.keys() {
                if !wt_set.contains(name.as_str()) {
                    wt_changes.push((name.clone(), String::new())); // empty = deleted
                }
            }

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

            let wt_files_set: std::collections::HashSet<&str> =
                wt_changes.iter().map(|(p, _)| p.as_str()).collect();

            // 2. Walk back through commits, collecting (commit_hash, changed_files).
            let head_id = repo.refs().resolve_head()?.context("HEAD does not point to a commit")?;
            let mut commits: Vec<(String, Vec<String>)> = Vec::new();
            let mut current = head_id.clone();
            for _ in 0..50 {
                let commit = repo.read_commit(&current)?;
                let parent_tree = if !commit.parents.is_empty() {
                    let parent = repo.read_commit(&commit.parents[0])?;
                    repo.read_tree(&parent.tree)?
                } else {
                    Tree::new(vec![])
                };
                let changed: Vec<String> = {
                    let parent_set: std::collections::HashMap<&String, &String> = parent_tree
                        .entries.iter().map(|e| (&e.name, &e.id)).collect();
                    let mut files = Vec::new();
                    for entry in &commit_tree_entries(&repo, &current)? {
                        match parent_set.get(&entry.name) {
                            Some(h) if **h != entry.id => files.push(entry.name.clone()),
                            None => files.push(entry.name.clone()),
                            _ => {}
                        }
                    }
                    for name in parent_tree.entries.iter().map(|e| &e.name) {
                        if !commit_tree_entries(&repo, &current)?.iter().any(|e| &e.name == name) {
                            files.push(name.clone());
                        }
                    }
                    files
                };
                commits.push((current.clone(), changed));
                if commit.parents.is_empty() {
                    break;
                }
                current = commit.parents[0].clone();
            }

            // 3. Find the commit with the most overlap.
            let mut best_idx = 0usize;
            let mut best_overlap = 0usize;
            for (i, (_, changed)) in commits.iter().enumerate() {
                let overlap = changed.iter().filter(|f| wt_files_set.contains(f.as_str())).count();
                if overlap > best_overlap {
                    best_overlap = overlap;
                    best_idx = i;
                }
            }

            if best_overlap == 0 {
                // No commit has overlap — amend HEAD as fallback.
                best_idx = 0;
            }

            let (target_hash, _) = &commits[best_idx];
            let target_hash = target_hash.clone();

            // 4. Build the new target tree: start from target's tree, apply
            //    working-tree changes for overlapping files.
            let target_commit = repo.read_commit(&target_hash)?;
            let target_tree = repo.read_tree(&target_commit.tree)?;
            let mut target_entries: Vec<TreeEntry> = 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 absorbed_files = Vec::new();
            for (path, new_blob) in &wt_changes {
                if let Some(&idx) = target_map.get(path) {
                    if new_blob.is_empty() {
                        // File was deleted in working tree — remove from target tree
                        target_entries[idx] = TreeEntry { mode: 0, name: String::new(), id: String::new() };
                    } else {
                        target_entries[idx].id = new_blob.clone();
                    }
                    absorbed_files.push(path.clone());
                } else if !new_blob.is_empty() {
                    // File is new (not in target tree) — add it only if the target
                    // is HEAD (otherwise it belongs to a later commit).
                    if best_idx == 0 {
                        target_entries.push(TreeEntry { mode: 0o100644, name: path.clone(), id: new_blob.clone() });
                        absorbed_files.push(path.clone());
                    }
                }
            }
            // Remove deleted entries (mode 0 = marker for deletion)
            target_entries.retain(|e| e.mode != 0);

            let new_target_tree = Tree::new(target_entries);
            let new_target_tree_id = repo.write_tree(&new_target_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 = Commit::new(
                new_target_tree_id,
                target_commit.parents.clone(),
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let new_target_id = repo.write_commit(&new_target_commit)?;

            // 5. Rebuild descendants (commits newer than the target).
            // `commits` is ordered newest-to-oldest, so descendants are
            // `commits[0..best_idx]` — iterate in reverse (oldest descendant first).
            let mut new_parent = new_target_id.clone();
            let absorbed_set: std::collections::HashSet<&str> =
                absorbed_files.iter().map(|s| s.as_str()).collect();

            for i in (0..best_idx).rev() {
                let (old_hash, _) = &commits[i];
                let old_commit = repo.read_commit(old_hash)?;
                let old_tree = repo.read_tree(&old_commit.tree)?;

                // For each absorbed file: if the descendant didn't change it
                // (same blob as the original target), update it to the new
                // version from the amended target tree.
                let mut new_entries = old_tree.entries.clone();
                let old_tree_map: std::collections::HashMap<String, usize> = old_tree
                    .entries.iter().enumerate().map(|(i, e)| (e.name.clone(), i)).collect();

                for (path, new_blob) in &wt_changes {
                    if !absorbed_set.contains(path.as_str()) {
                        continue;
                    }
                    if let Some(&idx) = old_tree_map.get(path) {
                        // Check if the descendant changed this file vs the target
                        let target_blob = target_tree.entries.iter()
                            .find(|e| e.name == *path)
                            .map(|e| e.id.clone());
                        if old_tree.entries[idx].id == target_blob.unwrap_or_default() {
                            // Descendant didn't change it — update to new version
                            if new_blob.is_empty() {
                                new_entries[idx] = TreeEntry { mode: 0, name: String::new(), id: String::new() };
                            } else {
                                new_entries[idx].id = new_blob.clone();
                            }
                        }
                    }
                }
                new_entries.retain(|e| e.mode != 0);

                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(),
                    timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            // 6. Update branch ref to the new HEAD.
            let branch = repo.refs().current_branch()?.context("No current branch")?;
            repo.refs().set_branch(&branch, &new_parent)?;

            // 7. Sync index + working tree to new HEAD.
            let mgr2 = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0 };
            mgr2.sync_index_to_commit(&new_parent)
                .context("absorb: sync index")?;
            mgr2.restore_working_tree_pub(&new_parent)
                .context("absorb: restore working tree")?;

            Ok(AbsorbResult {
                new_head: new_parent,
                target_commit: target_hash,
                absorbed_files,
                was_head: best_idx == 0,
            })
        })
        .await?
    }

    /// Soft reset to parent of HEAD (undo last commit, keep changes staged).
    pub async fn reset_soft_parent(&self) -> Result<()> {
        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)?;

        if head_commit.parents.is_empty() {
            bail!("No parent commit to reset to");
        }

        let parent_id = &head_commit.parents[0];

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

        // Restore index to match parent commit's tree
        let parent_commit = self.repo.read_commit(parent_id)?;
        let tree = self.repo.read_tree(&parent_commit.tree)?;
        let mut index = self.repo.load_index()?;
        index.clear();
        for entry in &tree.entries {
            index.add(&entry.name, &entry.id);
        }
        index.save()?;

        Ok(())
    }

    // ── Status ─────────────────────────────────────────────────────

    /// 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 };

            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?
    }

}