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
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
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
mod common;
use common::*;

#[tokio::test]
async fn test_finish_command_workflow() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    // Initialize codetree
    commands::init_command(false).await?;

    // Create a branch
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_name = "codetree_test_finish_op";
    git_manager.create_branch(branch_name, None).await?;

    // Register branch in manager
    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    branch_manager.register_branch(
        branch_name,
        vec!["src/test.rs".to_string()],
        "Test finish workflow".to_string()
    ).await?;

    // Add a commit on the branch
    git_manager.checkout_branch(branch_name).await?;
    tokio::fs::create_dir_all(repo_path.join("src")).await?;
    tokio::fs::write(repo_path.join("src/test.rs"), "// test content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("Test commit for finish").await?;

    // Finish the operation
    commands::finish_command(Some(branch_name.to_string()), None, false).await?;

    // Verify branch is merged and deleted
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let info = branch_manager.get_branch(branch_name).unwrap();
    assert_eq!(info.status, BranchStatus::Merged);

    // Verify git branch no longer exists
    let branches = git_manager.list_branches()?;
    assert!(!branches.iter().any(|b| b.name == branch_name));

    Ok(())
}

#[tokio::test]
async fn test_withdraw_command_workflow() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    // Initialize
    commands::init_command(false).await?;

    // Create and register a branch
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_name = "codetree_test_withdraw_op";
    git_manager.create_branch(branch_name, None).await?;

    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    branch_manager.register_branch(
        branch_name,
        vec!["src/test.rs".to_string()],
        "Test withdraw workflow".to_string()
    ).await?;

    // Add a commit on the branch
    git_manager.checkout_branch(branch_name).await?;
    tokio::fs::create_dir_all(repo_path.join("src")).await?;
    tokio::fs::write(repo_path.join("src/test.rs"), "// test content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("Test commit for withdraw").await?;

    // Withdraw
    commands::withdraw_command(Some(branch_name.to_string()), None).await?;

    // Verify branch is archived
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let info = branch_manager.get_branch(branch_name).unwrap();
    assert_eq!(info.status, BranchStatus::Archived);

    // Verify git branch no longer exists
    let branches = git_manager.list_branches()?;
    assert!(!branches.iter().any(|b| b.name == branch_name));

    Ok(())
}

#[tokio::test]
async fn test_full_agent_workflow_parallel_start_save_finish() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    // Step 1: init
    commands::init_command(false).await?;

    // Step 2: start parallel operation (default, no --checkout)
    commands::start_command(
        "Fix login bug".to_string(),
        true,  // parallel (default)
        false, // not worktree
        false, // not branchless
        None,  // no files
        None,  // no depends_on
        None,  // no template
        None,  // no tags
        None, false).await?;  // no agent_id

    // Step 3: start second parallel operation
    commands::start_command(
        "Refactor auth".to_string(),
        true,  // parallel
        false,
        false,
        None,
        None,
        None,
        None,
        None, false).await?;  // no agent_id

    // Verify both branches exist but we stayed on main
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let current = git_manager.get_current_branch().await?;
    assert_eq!(current, "main");
    assert!(branches.iter().any(|b| b.name.starts_with("codetree_") && b.name.contains("fix_login_bug")));
    assert!(branches.iter().any(|b| b.name.starts_with("codetree_") && b.name.contains("refactor_auth")));

    // Step 4: switch to first op and save
    let op1_branch = branches.iter()
        .find(|b| b.name.contains("fix_login_bug"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&op1_branch).await?;
    tokio::fs::write(repo_path.join("login.rs"), "fn login() {}\n").await?;
    commands::save_command(vec![], false, false, None).await?;

    // Step 5: switch to second op and save
    let op2_branch = branches.iter()
        .find(|b| b.name.contains("refactor_auth"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&op2_branch).await?;
    tokio::fs::write(repo_path.join("auth.rs"), "fn auth() {}\n").await?;
    commands::save_command(vec![], false, false, None).await?;

    // Step 6: compare
    commands::compare_command().await?;

    // Step 7: finish first op
    commands::finish_command(Some(op1_branch.clone()), None, false).await?;

    // Step 8: withdraw second op
    commands::withdraw_command(Some(op2_branch.clone()), None).await?;

    // Verify states
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let info1 = branch_manager.get_branch(&op1_branch).unwrap();
    let info2 = branch_manager.get_branch(&op2_branch).unwrap();
    assert_eq!(info1.status, BranchStatus::Merged);
    assert_eq!(info2.status, BranchStatus::Archived);

    Ok(())
}

#[tokio::test]
async fn test_undo_list_and_selective() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    // Initialize
    commands::init_command(false).await?;

    // Create two operations via start_command (records in ops log)
    commands::start_command("First op".to_string(), false, false, false, None, None, None, None, None, false).await?;
    commands::start_command("Second op".to_string(), false, false, false, None, None, None, None, None, false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;

    // List operations — should show the two Start operations
    commands::undo_command(None, true).await?;

    // Verify both op branches exist
    let branches = git_manager.list_branches()?;
    let op_branches: Vec<_> = branches.iter().filter(|b| b.name.starts_with("codetree_")).collect();
    assert_eq!(op_branches.len(), 2);

    // Undo the first Start operation by index (index 0)
    commands::undo_command(Some(0), false).await?;

    // Verify the first branch is gone but second remains
    let branches = git_manager.list_branches()?;
    let op_branches: Vec<_> = branches.iter().filter(|b| b.name.starts_with("codetree_")).collect();
    assert_eq!(op_branches.len(), 1);

    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    assert_eq!(branch_manager.list_branches().len(), 1); // only the second op

    Ok(())
}

#[tokio::test]
async fn test_per_file_assignment_scoped_save() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    // Initialize
    commands::init_command(false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;

    // Create a parallel operation with assigned files
    commands::start_command(
        "Fix login".to_string(),
        true,  // parallel
        false,
        false,
        Some(vec!["src/auth.rs".to_string(), "src/login.html".to_string()]),
        None,  // no depends_on
        None,
        None,
        None,
        false,
    ).await?;

    // Switch to the operation branch
    let branches = git_manager.list_branches()?;
    let op_branch = branches.iter()
        .find(|b| b.name.starts_with("codetree_"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&op_branch).await?;

    // Create files: one assigned, one not
    tokio::fs::create_dir_all(repo_path.join("src")).await?;
    tokio::fs::write(repo_path.join("src/auth.rs"), "// auth fix\n").await?;
    tokio::fs::write(repo_path.join("src/other.rs"), "// unrelated\n").await?;

    // Save should only commit the assigned file
    commands::save_command(vec![], false, false, None).await?;

    // Verify only auth.rs was committed (other.rs should remain untracked/modified)
    let status = git_manager.get_status().await?;
    assert!(status.modified.iter().any(|f| f == "src/other.rs") || status.untracked.iter().any(|f| f == "src/other.rs"));

    Ok(())
}

#[tokio::test]
async fn test_branchless_auto_absorb() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    // Initialize
    commands::init_command(false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;

    // Create a branchless bookmark
    commands::start_command(
        "Fix login".to_string(),
        false, false, true,  // branchless
        None, None, None, None,
        None, false).await?;

    // Verify we stayed on main
    let current = git_manager.get_current_branch().await?;
    assert_eq!(current, "main");

    // Create a file and save (first save = new commit)
    tokio::fs::write(repo_path.join("auth.rs"), "// v1\n").await?;
    commands::save_command(vec![], false, false, None).await?;
    let history1 = git_manager.get_commit_history("main", 5)?;
    let first_commit_hash = history1[0].hash.clone();

    // Modify the same file and save again (second save = amend, not new commit)
    tokio::fs::write(repo_path.join("auth.rs"), "// v2\n").await?;
    commands::save_command(vec![], false, false, None).await?;
    let history2 = git_manager.get_commit_history("main", 5)?;
    let second_commit_hash = history2[0].hash.clone();

    // The second save should have amended the first commit, so HEAD should be different
    // But the parent commit should be the same (no extra commit inserted)
    assert_ne!(first_commit_hash, second_commit_hash, "Amended commit should have new hash");
    assert_eq!(history1[1].hash, history2[1].hash, "Parent commit should be unchanged");

    Ok(())
}

#[tokio::test]
async fn test_snapshot_clean_tree_no_snapshot() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    // Commit the .gitignore that init_command creates, so the tree is clean.
    git_manager.add_all().await?;
    git_manager.commit("Add .gitignore").await?;

    // Clean working tree — snapshot should return None.
    let result = git_manager.snapshot_working_tree().await?;
    assert!(result.is_none(), "clean tree should not produce a snapshot");

    Ok(())
}

#[tokio::test]
async fn test_snapshot_dirty_tree_and_restore() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    // Commit the .gitignore that init_command creates.
    git_manager.add_all().await?;
    git_manager.commit("Add .gitignore").await?;

    // Make a dirty change (uncommitted).
    tokio::fs::write(repo_path.join("work.rs"), "fn work() { 42 }\n").await?;

    // Snapshot should capture the dirty tree.
    let result = git_manager.snapshot_working_tree().await?;
    assert!(result.is_some(), "dirty tree should produce a snapshot");
    let snap = result.unwrap();
    assert_eq!(snap.file_count, 2); // .gitignore + work.rs
    assert_eq!(snap.branch, "main");
    assert!(!snap.commit_hash.is_empty());

    // Record it in the manager.
    let mut mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;
    let id = mgr.add(snap.commit_hash.clone(), snap.timestamp, snap.branch.clone(), snap.file_count);
    mgr.save(&git_manager.snapshots_path()).await?;

    // Overwrite the working tree (simulating a risky command destroying work).
    tokio::fs::write(repo_path.join("work.rs"), "fn lost() {}\n").await?;

    // Restore the snapshot — working tree should have the original content.
    commands::restore_snapshot_command(id, false).await?;

    let content = tokio::fs::read_to_string(repo_path.join("work.rs")).await?;
    assert_eq!(content, "fn work() { 42 }\n");

    Ok(())
}

#[tokio::test]
async fn test_auto_snapshot_before_switch() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start a parallel op (stays on main).
    commands::start_command("test op".to_string(), true, false, false, None, None, None, None, None, false).await?;

    // Make uncommitted changes on main (the .gitignore from init is already committed
    // by create_test_repo's initial commit + init_command's .gitignore — but init adds
    // .gitignore as a new file, so we need to account for it).
    tokio::fs::write(repo_path.join("uncommitted.rs"), "fn temp() {}\n").await?;

    // Switch to the op branch — auto_snapshot should fire before the switch.
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let op_branch = branches.iter()
        .find(|b| b.name.starts_with("codetree_") && b.name != "main")
        .map(|b| b.name.clone())
        .unwrap();

    commands::switch_command(op_branch).await?;

    // A snapshot should have been recorded.
    let mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;
    assert!(!mgr.is_empty(), "auto-snapshot should have been created before switch");
    let snap = mgr.list().last().unwrap();
    assert_eq!(snap.branch, "main");
    assert!(snap.file_count > 0);

    // The snapshot commit should be readable.
    let commit = git_manager.repo().read_commit(&snap.commit_hash)?;
    assert_eq!(commit.message, "Working copy snapshot");

    Ok(())
}

#[tokio::test]
async fn test_save_clears_snapshots() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    // Create uncommitted changes and manually snapshot.
    tokio::fs::write(repo_path.join("file.rs"), "fn main() {}\n").await?;
    commands::snapshot_command(false).await?;

    let mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;
    assert!(!mgr.is_empty(), "snapshot should exist");

    // Save — should clear snapshots.
    commands::save_command(vec!["save work".to_string()], false, false, None).await?;

    let mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;
    assert!(mgr.is_empty(), "save should clear snapshots");

    Ok(())
}

#[tokio::test]
async fn test_checkpoint_rewind_workflow() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    // Dirty tree → checkpoint captures it with a label.
    tokio::fs::write(repo_path.join("a.txt"), "v1\n").await?;
    commands::checkpoint_command(Some("before risky refactor".to_string())).await?;

    let snapshots_path = repo_path.join(".codetree").join("snapshots.json");
    let mgr = SnapshotManager::load(&snapshots_path).await?;
    assert_eq!(mgr.len(), 1);
    assert_eq!(mgr.get(0).unwrap().label.as_deref(), Some("before risky refactor"));

    // "Risky" changes: modify + create a stray file.
    tokio::fs::write(repo_path.join("a.txt"), "v2 broken\n").await?;
    tokio::fs::write(repo_path.join("stray.txt"), "stray\n").await?;

    // Dry-run rewinds nothing.
    commands::rewind_command(0, true).await?;
    assert_eq!(tokio::fs::read_to_string(repo_path.join("a.txt")).await?, "v2 broken\n");
    assert!(repo_path.join("stray.txt").exists());

    // Real rewind restores the checkpoint's tree; HEAD and history untouched.
    let head_before = git_manager.get_head_hash()?;
    commands::rewind_command(0, false).await?;
    assert_eq!(tokio::fs::read_to_string(repo_path.join("a.txt")).await?, "v1\n");
    assert!(!repo_path.join("stray.txt").exists(), "rewind removes files created after the checkpoint");
    assert_eq!(git_manager.get_head_hash()?, head_before, "rewind must not move HEAD");

    Ok(())
}

#[tokio::test]
async fn test_checkpoint_survives_save_and_clean_checkpoint_targets_head() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    // Labeled checkpoint, then save: the checkpoint survives (auto-snapshots don't).
    tokio::fs::write(repo_path.join("a.txt"), "v1\n").await?;
    commands::checkpoint_command(Some("turn 1".to_string())).await?;
    commands::save_command(vec!["save a".to_string()], false, false, None).await?;

    let snapshots_path = repo_path.join(".codetree").join("snapshots.json");
    let mgr = SnapshotManager::load(&snapshots_path).await?;
    assert_eq!(mgr.len(), 1, "labeled checkpoint survives save");
    assert_eq!(mgr.get(0).unwrap().label.as_deref(), Some("turn 1"));

    // Clean-tree checkpoint targets HEAD directly (no new commit needed).
    commands::checkpoint_command(Some("turn 2".to_string())).await?;
    let mgr = SnapshotManager::load(&snapshots_path).await?;
    assert_eq!(mgr.len(), 2);
    let head = git_manager.get_head_hash()?;
    assert_eq!(mgr.get(1).unwrap().commit_hash, head, "clean checkpoint targets HEAD's tree");
    assert_eq!(mgr.get(1).unwrap().label.as_deref(), Some("turn 2"));

    // Break things, rewind to the clean checkpoint → HEAD's tree restored.
    tokio::fs::write(repo_path.join("a.txt"), "broken\n").await?;
    tokio::fs::write(repo_path.join("stray.txt"), "x\n").await?;
    commands::rewind_command(1, false).await?;
    assert_eq!(tokio::fs::read_to_string(repo_path.join("a.txt")).await?, "v1\n");
    assert!(!repo_path.join("stray.txt").exists());

    Ok(())
}

#[tokio::test]
async fn test_operation_tags_grouping() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start two operations with the same tag
    commands::start_command(
        "Fix login".to_string(),
        true, false, false,
        None, None, None,
        Some(vec!["sprint-42".to_string()]),
        None,
        false,
    ).await?;

    commands::start_command(
        "Fix logout".to_string(),
        true, false, false,
        None, None, None,
        Some(vec!["sprint-42".to_string()]),
        None,
        false,
    ).await?;

    // Start one operation with a different tag
    commands::start_command(
        "Refactor parser".to_string(),
        true, false, false,
        None, None, None,
        Some(vec!["tech-debt".to_string()]),
        None,
        false,
    ).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let codetree_branches: Vec<_> = branches.iter().filter(|b| b.name.starts_with("codetree_")).collect();
    assert_eq!(codetree_branches.len(), 3);

    // List by tag via branch manager
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;

    let sprint_branches = branch_manager.list_branches_by_tag("sprint-42");
    assert_eq!(sprint_branches.len(), 2);

    let tech_debt_branches = branch_manager.list_branches_by_tag("tech-debt");
    assert_eq!(tech_debt_branches.len(), 1);

    // Batch withdraw by tag
    let sprint_names: Vec<_> = sprint_branches.iter().map(|b| b.name.clone()).collect();
    for name in &sprint_names {
        commands::withdraw_command(Some(name.clone()), None).await?;
    }

    // Verify both sprint-42 ops are archived
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    for name in &sprint_names {
        let info = branch_manager.get_branch(name).unwrap();
        assert_eq!(info.status, BranchStatus::Archived);
    }

    // Tech-debt op should still be active
    let tech_debt_name = tech_debt_branches[0].name.clone();
    let info = branch_manager.get_branch(&tech_debt_name).unwrap();
    assert_eq!(info.status, BranchStatus::Active);

    Ok(())
}

#[tokio::test]
async fn test_next_prev_navigation() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start three parallel operations (stays on main)
    commands::start_command("Alpha fix".to_string(), true, false, false, None, None, None, None, None, false).await?;
    commands::start_command("Beta fix".to_string(), true, false, false, None, None, None, None, None, false).await?;
    commands::start_command("Gamma fix".to_string(), true, false, false, None, None, None, None, None, false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;

    // Currently on main — next should go to first active op (alphabetically)
    commands::next_command().await?;
    let current = git_manager.get_current_branch().await?;
    let branches = git_manager.list_branches()?;
    let mut active: Vec<_> = branches.iter().filter(|b| b.name.starts_with("codetree_")).map(|b| b.name.clone()).collect();
    active.sort();
    assert_eq!(current, active[0], "next from main should go to first active op");

    // next again should go to second
    commands::next_command().await?;
    let current = git_manager.get_current_branch().await?;
    assert_eq!(current, active[1], "next should advance to second op");

    // prev should go back to first
    commands::prev_command().await?;
    let current = git_manager.get_current_branch().await?;
    assert_eq!(current, active[0], "prev should go back to first op");

    // prev at first should wrap to last
    commands::prev_command().await?;
    let current = git_manager.get_current_branch().await?;
    assert_eq!(current, active[2], "prev at first should wrap to last op");

    // next at last should wrap to first
    commands::next_command().await?;
    let current = git_manager.get_current_branch().await?;
    assert_eq!(current, active[0], "next at last should wrap to first op");

    Ok(())
}

#[tokio::test]
async fn test_staleness_warning() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    // Create an operation
    let branch_name = "codetree_stale_op";
    git_manager.create_branch(branch_name, None).await?;
    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    branch_manager.register_branch(
        branch_name,
        vec!["src/main.rs".to_string()],
        "Stale op".to_string()
    ).await?;

    // Make the branch's updated_at 10 days old
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let ten_days_ago = now - 10 * 86400;
    if let Some(branch) = branch_manager.branches.get_mut(branch_name) {
        branch.updated_at = ten_days_ago;
    }
    branch_manager.save().await?;

    // status_command should run without error (staleness label is printed)
    commands::status_command(false).await?;

    // smartlog_command should also run without error
    commands::smartlog_command(false, false, None, None, false, false).await?;

    Ok(())
}

#[tokio::test]
async fn test_snapshot_with_ops_backup() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    // Create a branch with metadata.
    let branch1 = "codetree_op_snapshot_ops";
    git_manager.create_branch(branch1, None).await?;
    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    branch_manager.register_branch(branch1, vec![], "Ops snapshot test".to_string()).await?;

    // Make the working tree dirty.
    tokio::fs::write(repo_path.join("file.rs"), "fn main() {}\n").await?;

    // Create a snapshot with --ops.
    commands::snapshot_command(true).await?;

    // Verify the ops backup directory exists.
    let backup_dir = repo_path.join(".codetree").join("ops_backups");
    assert!(backup_dir.exists(), "ops_backups directory should exist");

    // Verify branches.json was backed up.
    let mut found_backup = false;
    for entry in std::fs::read_dir(&backup_dir)? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            let backup_file = entry.path().join("branches.json");
            if backup_file.exists() {
                found_backup = true;
                break;
            }
        }
    }
    assert!(found_backup, "branches.json should be backed up");

    Ok(())
}

#[tokio::test]
async fn test_redo_start_operation() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start an operation
    commands::start_command("Redo test op".to_string(), true, false, false, None, None, None, None, None, false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches_before = git_manager.list_branches()?;
    let op_branch = branches_before.iter()
        .find(|b| b.name.starts_with("codetree_"))
        .map(|b| b.name.clone())
        .unwrap();
    assert!(git_manager.branch_exists(&op_branch), "Branch should exist before undo");

    // Undo the start
    commands::undo_command(None, false).await?;

    // Verify branch is gone
    let branches_after_undo = git_manager.list_branches()?;
    assert!(!branches_after_undo.iter().any(|b| b.name == op_branch), "Branch should be gone after undo");

    // Redo the start
    commands::redo_command(None, false).await?;

    // Verify branch is back
    let branches_after_redo = git_manager.list_branches()?;
    assert!(branches_after_redo.iter().any(|b| b.name == op_branch), "Branch should exist again after redo");

    Ok(())
}

#[tokio::test]
async fn test_redo_list_empty() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Redo list on empty redo stack should not error
    commands::redo_command(None, true).await?;

    Ok(())
}

#[tokio::test]
async fn test_undo_then_redo_then_undo_again() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start an operation
    commands::start_command("Cycle test".to_string(), true, false, false, None, None, None, None, None, false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let op_branch = branches.iter()
        .find(|b| b.name.starts_with("codetree_"))
        .map(|b| b.name.clone())
        .unwrap();

    // Undo
    commands::undo_command(None, false).await?;
    assert!(!git_manager.branch_exists(&op_branch), "Branch gone after undo");

    // Redo
    commands::redo_command(None, false).await?;
    assert!(git_manager.branch_exists(&op_branch), "Branch back after redo");

    // Undo again
    commands::undo_command(None, false).await?;
    assert!(!git_manager.branch_exists(&op_branch), "Branch gone after second undo");

    Ok(())
}

#[tokio::test]
async fn test_switch_toggle() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start two operations
    commands::start_command("Op A".to_string(), true, false, false, None, None, None, None, None, false).await?;
    commands::start_command("Op B".to_string(), true, false, false, None, None, None, None, None, false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let op_a = branches.iter().find(|b| b.name.contains("op_a")).map(|b| b.name.clone()).unwrap();
    let op_b = branches.iter().find(|b| b.name.contains("op_b")).map(|b| b.name.clone()).unwrap();

    // Switch to op_a
    commands::switch_command(op_a.clone()).await?;
    assert_eq!(git_manager.get_current_branch().await?, op_a);

    // Switch to op_b
    commands::switch_command(op_b.clone()).await?;
    assert_eq!(git_manager.get_current_branch().await?, op_b);

    // Switch back with "-"
    commands::switch_command("-".to_string()).await?;
    assert_eq!(git_manager.get_current_branch().await?, op_a, "switch - should toggle back to op_a");

    // Switch back again with "-"
    commands::switch_command("-".to_string()).await?;
    assert_eq!(git_manager.get_current_branch().await?, op_b, "switch - should toggle back to op_b");

    Ok(())
}

#[tokio::test]
async fn test_finish_dry_run() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start an operation
    commands::start_command("Dry run finish test".to_string(), true, false, false, None, None, None, None, None, false).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let op_branch = branches.iter()
        .find(|b| b.name.starts_with("codetree_"))
        .map(|b| b.name.clone())
        .unwrap();

    // Run finish --dry-run
    commands::finish_command(Some(op_branch.clone()), None, true).await?;

    // Branch should still exist (dry-run doesn't actually merge)
    assert!(git_manager.branch_exists(&op_branch), "Branch should still exist after dry-run finish");

    Ok(())
}

#[tokio::test]
async fn test_start_checkout_switches_to_branch() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // start with parallel=false should checkout the new branch
    commands::start_command(
        "Checkout test".to_string(),
        false, false, false,
        None, None, None, None,
        None, false,
    ).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let current = git_manager.get_current_branch().await?;
    assert!(current.contains("checkout_test"), "Non-parallel start should checkout the new branch");

    Ok(())
}

#[tokio::test]
async fn test_save_with_explicit_message() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start and checkout
    commands::start_command(
        "Explicit msg test".to_string(),
        false, false, false,
        None, None, None, None,
        None, false,
    ).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let current = git_manager.get_current_branch().await?;

    // Create a file and save with explicit message
    tokio::fs::write(repo_path.join("msg_test.rs"), "// test\n").await?;
    commands::save_command(vec!["My explicit save message".to_string()], false, false, None).await?;

    // Verify the commit message
    let history = git_manager.get_commit_history(&current, 5)?;
    assert!(history.iter().any(|c| c.message == "My explicit save message"),
        "Commit with explicit message should exist");

    Ok(())
}

#[tokio::test]
async fn test_withdraw_nonexistent_branch_errors() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    let result = commands::withdraw_command(Some("nonexistent_branch".to_string()), None).await;
    assert!(result.is_err(), "Withdrawing a non-existent branch should error");

    Ok(())
}

#[tokio::test]
async fn test_finish_nonexistent_branch_errors() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    let result = commands::finish_command(Some("nonexistent_branch".to_string()), None, false).await;
    assert!(result.is_err(), "Finishing a non-existent branch should error");

    Ok(())
}

#[tokio::test]
async fn test_batch_withdraw_by_tag() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start two ops with the same tag
    commands::start_command(
        "Batch A".to_string(),
        true, false, false,
        None, None, None,
        Some(vec!["batch-test".to_string()]),
        None, false,
    ).await?;
    commands::start_command(
        "Batch B".to_string(),
        true, false, false,
        None, None, None,
        Some(vec!["batch-test".to_string()]),
        None, false,
    ).await?;

    // Start an unrelated op
    commands::start_command(
        "Unrelated".to_string(),
        true, false, false,
        None, None, None, None,
        None, false,
    ).await?;

    // Batch withdraw by tag
    commands::withdraw_command(None, Some("batch-test".to_string())).await?;

    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;

    // Both batch-test ops should be archived
    let batch_branches: Vec<_> = branch_manager.list_branches()
        .into_iter()
        .filter(|b| b.tags.iter().any(|t| t == "batch-test"))
        .collect();
    assert_eq!(batch_branches.len(), 2);
    for b in &batch_branches {
        assert_eq!(b.status, BranchStatus::Archived, "Batch-tagged op should be archived");
    }

    // Unrelated op should still be active
    let active: Vec<_> = branch_manager.list_branches()
        .into_iter()
        .filter(|b| matches!(b.status, BranchStatus::Active))
        .collect();
    assert_eq!(active.len(), 1, "Unrelated op should still be active");

    Ok(())
}

#[tokio::test]
async fn test_batch_finish_by_tag() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start two ops with the same tag, each with a commit
    commands::start_command(
        "Finish A".to_string(),
        false, false, false,
        None, None, None,
        Some(vec!["fin-tag".to_string()]),
        None, false,
    ).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let op_a = branch_manager.list_branches()
        .into_iter()
        .filter(|b| b.tags.iter().any(|t| t == "fin-tag"))
        .find(|b| b.name.contains("finish_a"))
        .map(|b| b.name.clone())
        .unwrap();

    tokio::fs::write(repo_path.join("a.rs"), "// a\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("A commit").await?;

    // Switch back to main, start second op
    git_manager.checkout_branch("main").await?;
    commands::start_command(
        "Finish B".to_string(),
        false, false, false,
        None, None, None,
        Some(vec!["fin-tag".to_string()]),
        None, false,
    ).await?;

    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let op_b = branch_manager.list_branches()
        .into_iter()
        .filter(|b| b.tags.iter().any(|t| t == "fin-tag"))
        .find(|b| b.name.contains("finish_b"))
        .map(|b| b.name.clone())
        .unwrap();

    tokio::fs::write(repo_path.join("b.rs"), "// b\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("B commit").await?;

    // Switch to main before batch finish
    git_manager.checkout_branch("main").await?;

    // Batch finish by tag
    commands::finish_command(None, Some("fin-tag".to_string()), false).await?;

    // Verify both are merged
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    for name in &[&op_a, &op_b] {
        let info = branch_manager.get_branch(name).unwrap();
        assert_eq!(info.status, BranchStatus::Merged, "Batch-finished op should be merged");
    }

    Ok(())
}

#[tokio::test]
async fn test_status_command_runs() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start an operation
    commands::start_command("Status test".to_string(), true, false, false, None, None, None, None, None, false).await?;

    // Create some changes
    tokio::fs::write(repo_path.join("new_file.rs"), "// new\n").await?;
    tokio::fs::write(repo_path.join("README.md"), "# updated\n").await?;

    // status should run without error
    commands::status_command(false).await?;

    Ok(())
}

#[tokio::test]
async fn test_worktree_add_and_remove() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start an operation with --worktree
    commands::start_command(
        "Worktree test".to_string(),
        false, true, false,
        None, None, None, None,
        None, false,
    ).await?;

    // Verify worktree directory exists
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let op = branch_manager.list_branches()
        .into_iter()
        .find(|b| matches!(b.status, BranchStatus::Active))
        .unwrap();
    assert!(op.worktree.is_some(), "Worktree path should be set");

    let worktree_path = op.worktree.clone().unwrap();
    assert!(worktree_path.exists(), "Worktree directory should exist on disk");

    // List worktrees should not error
    commands::worktree_list_command().await?;

    // Remove worktree
    commands::worktree_remove_command(op.name.clone()).await?;

    // Verify worktree path is cleared
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let op_after = branch_manager.get_branch(&op.name).unwrap();
    assert!(op_after.worktree.is_none(), "Worktree should be cleared after remove");

    Ok(())
}

#[tokio::test]
async fn test_undo_save_reverts_last_commit() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start and checkout
    commands::start_command(
        "Undo save test".to_string(),
        false, false, false,
        None, None, None, None,
        None, false,
    ).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let current = git_manager.get_current_branch().await?;

    // Save a commit
    tokio::fs::write(repo_path.join("undo_save.rs"), "// v1\n").await?;
    commands::save_command(vec!["First save".to_string()], false, false, None).await?;

    let history_before = git_manager.get_commit_history(&current, 10)?;
    let save_commits_before: Vec<_> = history_before.iter()
        .filter(|c| c.message == "First save")
        .collect();
    assert_eq!(save_commits_before.len(), 1);

    // Undo the save
    commands::undo_command(None, false).await?;

    // Verify the save commit is gone
    let history_after = git_manager.get_commit_history(&current, 10)?;
    let save_commits_after: Vec<_> = history_after.iter()
        .filter(|c| c.message == "First save")
        .collect();
    assert_eq!(save_commits_after.len(), 0, "Save commit should be reverted by undo");

    Ok(())
}

#[tokio::test]
async fn test_init_force_reinitializes() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    // First init
    commands::init_command(false).await?;
    assert!(repo_path.join(".codetree").exists());

    // Modify config
    let config_path = repo_path.join(".codetree").join("config.toml");
    let mut config = Config::load(&config_path).await?;
    config.git.branch_prefix = "custom_prefix".to_string();
    config.save(&config_path).await?;

    // Force re-init should not error
    commands::init_command(true).await?;
    assert!(repo_path.join(".codetree").exists());

    Ok(())
}

#[tokio::test]
async fn test_start_with_template() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start with the "bugfix" template (built-in default)
    commands::start_command(
        "Fix null pointer".to_string(),
        true, false, false,
        None, None,
        Some("bugfix".to_string()),
        None, None, false,
    ).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let op_branch = branches.iter()
        .find(|b| b.name.starts_with("codetree_") || b.name.starts_with("fix_"))
        .map(|b| b.name.clone())
        .unwrap();

    // The "bugfix" template has branch_prefix = "fix", so the branch should start with "fix_"
    assert!(op_branch.starts_with("fix_"), "Branch with bugfix template should start with 'fix_': {}", op_branch);

    Ok(())
}

#[tokio::test]
async fn test_start_unknown_template_errors() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    let result = commands::start_command(
        "Bad template".to_string(),
        true, false, false,
        None, None,
        Some("nonexistent_template".to_string()),
        None, None, false,
    ).await;

    assert!(result.is_err(), "Start with unknown template should error");

    Ok(())
}

#[tokio::test]
async fn test_stacked_operation_creation() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Start first op (non-parallel = checkout)
    commands::start_command(
        "Base op".to_string(),
        false, false, false,
        None, None, None, None,
        None, false,
    ).await?;

    let git_manager = VcsManager::new(repo_path.clone())?;
    let first_branch = git_manager.get_current_branch().await?;

    // Add a commit on first op
    tokio::fs::write(repo_path.join("base.rs"), "// base\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("Base op commit").await?;

    // Start second op (non-parallel = stacks on current active branch)
    commands::start_command(
        "Stacked op".to_string(),
        false, false, false,
        None, None, None, None,
        None, false,
    ).await?;

    let second_branch = git_manager.get_current_branch().await?;
    assert_ne!(first_branch, second_branch, "Should be on a new branch");

    // Verify parent relationship
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let parent = branch_manager.get_parent_branch(&second_branch);
    assert_eq!(parent, Some(first_branch.as_str()), "Second op should be stacked on first op");

    Ok(())
}

#[tokio::test]
async fn test_merge_base_into_itself_errors() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let _guard = DirGuard::new(&repo_path);

    commands::init_command(false).await?;

    // Trying to merge main into itself should error
    let result = commands::merge_command(Some("main".to_string()), false).await;
    assert!(result.is_err(), "Merging base branch into itself should error");

    Ok(())
}

// ============================================================
// Use-case coverage tests — from USECASES.md
// ============================================================

#[tokio::test]
async fn test_stat_cache_re_stages_modified_file() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (temp_dir, repo_path) = create_test_repo().await?;
    let _ = &temp_dir;
    let _guard = DirGuard::new(&repo_path);

    let mgr = VcsManager::new(repo_path.clone())?;

    // Stage and commit a file
    tokio::fs::write(repo_path.join("cached.rs"), "fn v1() {}\n").await?;
    mgr.add_all().await?;
    mgr.commit("v1").await?;

    // Re-stage with no changes: status must report a clean tree
    mgr.add_all().await?;
    let status = mgr.get_status().await?;
    assert!(status.modified.is_empty(), "clean tree after re-add, got {:?}", status.modified);

    // Modify the file (content + size change) and re-stage: new content must win
    tokio::fs::write(repo_path.join("cached.rs"), "fn v2_much_longer_name() {}\n").await?;
    mgr.add_all().await?;
    mgr.commit("v2").await?;
    let status = mgr.get_status().await?;
    assert!(status.modified.is_empty(), "tree clean after commit of new content, got {:?}", status.modified);

    // The committed content must be the new version
    let head = mgr.get_current_branch().await?;
    let history = mgr.get_commit_history(&head, 2)?;
    assert_eq!(history.len(), 2);

    Ok(())
}

#[tokio::test]
async fn test_checkout_skips_matching_files() -> Result<()> {
    let _serial = WORKDIR_LOCK.lock().await;
    let (temp_dir, repo_path) = create_test_repo().await?;
    let _ = &temp_dir;
    let _guard = DirGuard::new(&repo_path);

    let mgr = VcsManager::new(repo_path.clone())?;

    tokio::fs::write(repo_path.join("a.txt"), "alpha\n").await?;
    tokio::fs::write(repo_path.join("b.txt"), "beta\n").await?;
    mgr.add_all().await?;
    mgr.commit("base files").await?;

    // Branch from base, edit a file on main, then check the branch out again.
    mgr.create_branch("feature", None).await?;
    tokio::fs::write(repo_path.join("a.txt"), "alpha-main\n").await?;
    mgr.add_all().await?;
    mgr.commit("main change").await?;

    mgr.checkout_branch("feature").await?;
    let a = tokio::fs::read_to_string(repo_path.join("a.txt")).await?;
    let b = tokio::fs::read_to_string(repo_path.join("b.txt")).await?;
    assert_eq!(a, "alpha\n", "checkout must restore a.txt to branch content");
    assert_eq!(b, "beta\n", "untouched file must survive checkout (skip-if-match)");

    // Switching back must restore main's content
    mgr.checkout_branch("main").await?;
    let a = tokio::fs::read_to_string(repo_path.join("a.txt")).await?;
    assert_eq!(a, "alpha-main\n");

    Ok(())
}