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
mod common;
use common::*;

#[tokio::test]
async fn test_test_command_pass() -> 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 file with a test script.
    tokio::fs::write(repo_path.join("check.sh"), "#!/bin/bash\necho ok\n").await?;
    git_manager.add_all().await?;
    let commit_hash = git_manager.commit("add check script").await?;

    // Make the script executable.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(repo_path.join("check.sh"))?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(repo_path.join("check.sh"), perms)?;
    }

    // Run `true` at the commit — should pass.
    let result = commands::test_command(
        commit_hash.clone(),
        vec!["true".to_string()],
    ).await;
    assert!(result.is_ok(), "test command should pass with 'true'");

    Ok(())
}

#[tokio::test]
async fn test_test_command_fail() -> 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())?;

    git_manager.add_all().await?;
    let commit_hash = git_manager.commit("base").await?;

    // Run `false` at the commit — should fail.
    let result = commands::test_command(
        commit_hash.clone(),
        vec!["false".to_string()],
    ).await;
    assert!(result.is_err(), "test command should fail with 'false'");

    Ok(())
}

#[tokio::test]
async fn test_test_command_restores_working_tree() -> 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 1: file with content "v1"
    tokio::fs::write(repo_path.join("app.rs"), "fn main() { /* v1 */ }\n").await?;
    git_manager.add_all().await?;
    let commit1 = git_manager.commit("v1").await?;

    // Commit 2: file with content "v2"
    tokio::fs::write(repo_path.join("app.rs"), "fn main() { /* v2 */ }\n").await?;
    git_manager.add_all().await?;
    let _commit2 = git_manager.commit("v2").await?;

    // Run a test at commit1 (which has "v1").
    let result = commands::test_command(
        commit1.clone(),
        vec!["true".to_string()],
    ).await;
    assert!(result.is_ok());

    // After the test, the working tree should be restored to HEAD (commit2, "v2").
    let content = tokio::fs::read_to_string(repo_path.join("app.rs")).await?;
    assert_eq!(content, "fn main() { /* v2 */ }\n", "working tree should be restored after test");

    Ok(())
}

#[tokio::test]
async fn test_smartlog_command() -> 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 operation (off main)
    commands::start_command(
        "Fix login".to_string(),
        true, false, false,
        None, None, None, None,
        None, false).await?;

    // Start another parallel operation (off main)
    commands::start_command(
        "Fix logout".to_string(),
        true, false, false,
        None, None, None, None,
        None, false).await?;

    // Start a branchless bookmark
    commands::start_command(
        "Quick hotfix".to_string(),
        false, false, true,
        None, None, None, None,
        None, false).await?;

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

    // Verify the output contains the base branch and operations
    // (We can't capture stdout directly, but the command should not error)

    // Now finish one operation and verify smartlog still works
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branches = git_manager.list_branches()?;
    let first_op = branches.iter()
        .filter(|b| b.name.starts_with("codetree_"))
        .find(|b| b.name.contains("fix_login"))
        .map(|b| b.name.clone())
        .unwrap();

    // Add a commit so finish can merge
    git_manager.checkout_branch(&first_op).await?;
    tokio::fs::write(repo_path.join("login.rs"), "fn login() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("Login implementation").await?;

    commands::finish_command(Some(first_op.clone()), None, false).await?;

    // Smartlog should still work with a merged branch
    commands::smartlog_command(false, false, None, None, false, false).await?;

    Ok(())
}

#[tokio::test]
async fn test_smartlog_verbose() -> 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())?;

    // Start an operation and add commits
    commands::start_command("Feature work".to_string(), true, false, false, None, None, None, None, None, false).await?;

    let branches = git_manager.list_branches()?;
    let op_name = branches.iter()
        .find(|b| b.name.starts_with("codetree_"))
        .map(|b| b.name.clone())
        .unwrap();

    // Add two commits
    git_manager.checkout_branch(&op_name).await?;
    tokio::fs::write(repo_path.join("file1.rs"), "// file1\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("First commit").await?;
    tokio::fs::write(repo_path.join("file2.rs"), "// file2\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("Second commit").await?;

    git_manager.checkout_branch("main").await?;

    // Verbose smartlog should run without error and show commits
    commands::smartlog_command(true, false, None, None, false, false).await?;

    // Non-verbose should also work
    commands::smartlog_command(false, false, None, None, false, false).await?;

    Ok(())
}

#[tokio::test]
async fn test_list_query_filter() -> 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 two active branches with tags
    let branch1 = "codetree_op_one";
    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![], "Op one".to_string()).await?;
    branch_manager.add_tag(branch1, "sprint-42").await?;

    let branch2 = "codetree_op_two";
    git_manager.create_branch(branch2, None).await?;
    branch_manager.register_branch(branch2, vec![], "Op two".to_string()).await?;
    branch_manager.add_tag(branch2, "sprint-99").await?;

    // Create a merged branch
    let branch3 = "codetree_op_three";
    git_manager.create_branch(branch3, None).await?;
    branch_manager.register_branch(branch3, vec![], "Op three".to_string()).await?;
    branch_manager.mark_branch_merged(branch3).await?;

    // Query: active && tag:sprint-42 — should only match branch1
    commands::list_command(None, Some("active && tag:sprint-42".to_string()), false, None).await?;

    // Query: active — should match branch1 and branch2
    commands::list_command(None, Some("active".to_string()), false, None).await?;

    // Query: merged — should match branch3
    commands::list_command(None, Some("merged".to_string()), false, None).await?;

    // Query: active && tag:sprint-42 || merged — should match branch1 and branch3
    commands::list_command(None, Some("active && tag:sprint-42 || merged".to_string()), false, None).await?;

    // Query: active && tag:sprint-99 — should only match branch2
    commands::list_command(None, Some("active && tag:sprint-99".to_string()), false, None).await?;

    Ok(())
}

#[tokio::test]
async fn test_list_query_negation_and_only_child() -> 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 branches with parent relationships.
    // main is the base. child_a and child_b both have parent "main" (siblings).
    // child_c has parent "child_a" (only child of child_a).
    let child_a = "codetree_op_child_a";
    git_manager.create_branch(child_a, None).await?;
    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    branch_manager.register_branch(child_a, vec![], "Child A".to_string()).await?;
    branch_manager.set_parent_branch(child_a, "main").await?;

    let child_b = "codetree_op_child_b";
    git_manager.create_branch(child_b, None).await?;
    branch_manager.register_branch(child_b, vec![], "Child B".to_string()).await?;
    branch_manager.set_parent_branch(child_b, "main").await?;

    let child_c = "codetree_op_child_c";
    git_manager.create_branch(child_c, None).await?;
    branch_manager.register_branch(child_c, vec![], "Child C".to_string()).await?;
    branch_manager.set_parent_branch(child_c, child_a).await?;

    // Mark one as merged for negation test.
    let merged = "codetree_op_merged";
    git_manager.create_branch(merged, None).await?;
    branch_manager.register_branch(merged, vec![], "Merged".to_string()).await?;
    branch_manager.mark_branch_merged(merged).await?;

    // `!active` should match merged branches (negation of active).
    commands::list_command(None, Some("!active".to_string()), false, None).await?;

    // `!` alone should match only-child branches (child_c is the only child of child_a).
    // child_a and child_b are siblings (both children of main), so they are NOT only children.
    commands::list_command(None, Some("!".to_string()), false, None).await?;

    // `active && !` should match only-child active branches.
    commands::list_command(None, Some("active && !".to_string()), false, None).await?;

    Ok(())
}

#[tokio::test]
async fn test_json_output_status() -> 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 file and save it.
    tokio::fs::write(repo_path.join("app.rs"), "fn main() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("add app").await?;

    // Create an untracked file.
    tokio::fs::write(repo_path.join("new.rs"), "fn new() {}\n").await?;

    // JSON status should not panic and should produce valid output.
    commands::status_command(true).await?;

    Ok(())
}

#[tokio::test]
async fn test_json_output_list() -> 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.
    let branch1 = "codetree_op_json";
    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![], "JSON test".to_string()).await?;

    // JSON list should not panic and should produce valid output.
    commands::list_command(None, None, true, None).await?;

    // JSON list with query should also work.
    commands::list_command(None, Some("active".to_string()), true, None).await?;

    Ok(())
}

#[tokio::test]
async fn test_list_format_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?;
    let git_manager = VcsManager::new(repo_path.clone())?;

    let branch1 = "codetree_op_format";
    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![], "Format test".to_string()).await?;

    // Template-based output should not panic.
    commands::list_command(
        None,
        None,
        false,
        Some("{name} | {status} | {description}".to_string()),
    ).await?;

    Ok(())
}

#[tokio::test]
async fn test_smartlog_pagination() -> 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())?;
    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;

    // Create multiple branches.
    for i in 0..5 {
        let name = format!("codetree_op_page_{}", i);
        git_manager.create_branch(&name, None).await?;
        branch_manager.register_branch(&name, vec![], format!("Page test {}", i)).await?;
    }

    // Full smartlog should show all.
    commands::smartlog_command(false, false, None, None, false, false).await?;

    // Paginated: limit to 2.
    commands::smartlog_command(false, false, Some(2), None, false, false).await?;

    // Paginated: offset 2, limit 2.
    commands::smartlog_command(false, false, Some(2), Some(2), false, false).await?;

    // Reverse order.
    commands::smartlog_command(false, false, None, None, true, false).await?;

    Ok(())
}

#[tokio::test]
async fn test_list_query_branches_pattern() -> 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())?;
    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;

    // Create branches with specific names.
    for name in &["codetree_op_feat_auth", "codetree_op_feat_login", "codetree_op_fix_bug"] {
        git_manager.create_branch(name, None).await?;
        branch_manager.register_branch(name, vec![], "test".to_string()).await?;
    }

    // Query: branches(codetree_op_feat_*) should match the two feat branches.
    commands::list_command(None, Some("branches(codetree_op_feat_*)".to_string()), false, None).await?;

    // Query: branches(*fix*) should match the fix branch.
    commands::list_command(None, Some("branches(*fix*)".to_string()), false, None).await?;

    // Query: merges() should match merged branches (none yet).
    commands::list_command(None, Some("merges()".to_string()), false, None).await?;

    Ok(())
}

#[tokio::test]
async fn test_smartlog_exact() -> 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())?;
    let mut branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;

    git_manager.create_branch("codetree_op_exact_test", None).await?;
    branch_manager.register_branch("codetree_op_exact_test", vec![], "test".to_string()).await?;

    // Normal smartlog shows base branch.
    commands::smartlog_command(false, false, None, None, false, false).await?;

    // Exact mode skips base branch rendering.
    commands::smartlog_command(false, false, None, None, false, true).await?;

    Ok(())
}

#[tokio::test]
async fn test_log_command() -> 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())?;

    for i in 0..3 {
        tokio::fs::write(repo_path.join(format!("file{}.rs", i)), format!("fn f{}() {{}}\n", i)).await?;
        git_manager.add_all().await?;
        git_manager.commit(&format!("commit {}", i)).await?;
    }

    // Full log.
    commands::log_command(None, None, false).await?;

    // Limited log.
    commands::log_command(None, Some(2), false).await?;

    Ok(())
}

#[tokio::test]
async fn test_whereami_on_base() -> 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?;

    // On base branch with no operations
    commands::whereami_command().await?;

    Ok(())
}

#[tokio::test]
async fn test_whereami_on_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 a parallel operation
    commands::start_command("Fix login".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();

    // Checkout the operation branch
    git_manager.checkout_branch(&op_branch).await?;

    // whereami should run without error on an operation branch
    commands::whereami_command().await?;

    Ok(())
}

#[tokio::test]
async fn test_smartlog_position_flag() -> 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("Position test".to_string(), true, false, false, None, None, None, None, None, false).await?;

    // smartlog --position should run without error
    commands::smartlog_command(false, true, None, None, false, false).await?;

    // smartlog with both verbose and position should also work
    commands::smartlog_command(true, true, None, None, false, false).await?;

    Ok(())
}

#[tokio::test]
async fn test_list_command_no_tag_filter() -> 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 few ops
    commands::start_command("List A".to_string(), true, false, false, None, None, None, None, None, false).await?;
    commands::start_command("List B".to_string(), true, false, false, None, None, None, None, None, false).await?;

    // list with no filters should show all
    commands::list_command(None, None, false, None).await?;

    // list with tag filter for a non-existent tag should return empty
    commands::list_command(Some("nonexistent".to_string()), None, false, None).await?;

    Ok(())
}

#[tokio::test]
async fn test_show_command() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "fn main() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("add file").await?;

    // Show HEAD — should display the commit message and diff.
    commands::show_command("HEAD".to_string(), false).await?;

    Ok(())
}

#[tokio::test]
async fn test_diff_command() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "fn main() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("initial").await?;

    // Modify the file without committing.
    tokio::fs::write(repo_path.join("file.rs"), "fn main() { println!(\"hi\"); }\n").await?;

    // Diff should show the change.
    commands::diff_command(None).await?;

    Ok(())
}

#[tokio::test]
async fn test_blame_command() -> 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 file with multiple lines.
    tokio::fs::write(repo_path.join("file.rs"), "line1\nline2\nline3\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("initial file").await?;

    // Modify line 2.
    tokio::fs::write(repo_path.join("file.rs"), "line1\nline2 modified\nline3\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("modify line 2").await?;

    // Blame should show different commits for line 2 vs lines 1 and 3.
    commands::blame_command("file.rs".to_string()).await?;

    Ok(())
}

#[tokio::test]
async fn test_filelog_command() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "v1\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("first version").await?;

    tokio::fs::write(repo_path.join("file.rs"), "v2\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("second version").await?;

    // Filelog should show both commits.
    commands::filelog_command("file.rs".to_string()).await?;

    Ok(())
}

#[tokio::test]
async fn test_clean_command() -> 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())?;

    tokio::fs::write(repo_path.join("tracked.rs"), "fn main() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("add tracked").await?;

    // Create an untracked file.
    tokio::fs::write(repo_path.join("untracked.rs"), "fn untracked() {}\n").await?;
    assert!(repo_path.join("untracked.rs").exists());

    // Clean should remove the untracked file.
    commands::clean_command().await?;

    assert!(!repo_path.join("untracked.rs").exists(), "untracked file should be removed");
    assert!(repo_path.join("tracked.rs").exists(), "tracked file should remain");

    Ok(())
}

#[tokio::test]
async fn test_gc_command() -> 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 some commits, then rewrite history (creating unreachable objects).
    tokio::fs::write(repo_path.join("file.rs"), "v1\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("first").await?;

    tokio::fs::write(repo_path.join("file.rs"), "v2\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("second").await?;

    // Reword HEAD to create an unreachable old commit.
    commands::reword_command("HEAD".to_string(), "reworded".to_string(), false).await?;

    // GC should remove unreachable objects.
    commands::gc_command().await?;

    Ok(())
}

#[tokio::test]
async fn test_op_log_command() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("test commit").await?;

    // Op log should show the save operation.
    commands::op_log_command().await?;

    Ok(())
}

#[tokio::test]
async fn test_bisect() -> 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 5 commits, where commit 3 introduces a "bug".
    for i in 0..5 {
        let content = if i >= 3 { "buggy\n" } else { "good\n" };
        tokio::fs::write(repo_path.join("file.rs"), content).await?;
        git_manager.add_all().await?;
        git_manager.commit(&format!("commit {}", i)).await?;
    }

    // Start bisect (HEAD = commit 4, marked bad).
    commands::bisect_command(BisectAction::Start).await?;

    // Mark the initial commit as good.
    let head_hash = git_manager.get_head_hash()?;
    // Navigate to the root commit first to mark it good.
    // We need to find the root commit. Walk back from HEAD.
    let repo = git_manager.repo();
    let mut root = head_hash.clone();
    loop {
        let commit = repo.read_commit(&root)?;
        if commit.parents.is_empty() {
            break;
        }
        root = commit.parents[0].clone();
    }

    commands::bisect_command(BisectAction::Good(Some(root))).await?;

    // The bisect should narrow down. Let's mark the current commit as bad
    // (it should be somewhere in the middle).
    // After marking good, bisect will checkout a intermediate commit.
    // Mark it bad to narrow further.
    commands::bisect_command(BisectAction::Bad(None)).await?;

    // Check the bisect log.
    commands::bisect_command(BisectAction::Log).await?;

    // Reset to end the bisect session.
    commands::bisect_command(BisectAction::Reset).await?;

    Ok(())
}

#[tokio::test]
async fn test_tag_create_list_delete() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("first").await?;

    let head = git_manager.get_head_hash()?;

    // Create a tag at HEAD.
    commands::tag_command(TagAction::Create {
        name: "v1.0".to_string(),
        commit: None,
        annotate: None,
    }).await?;

    // Verify the tag exists.
    let repo = git_manager.repo();
    let tag_commit = repo.refs().get_tag("v1.0")?;
    assert_eq!(tag_commit, Some(head.clone()));

    // List tags.
    commands::tag_command(TagAction::List).await?;

    // Create another tag at HEAD~1.
    commands::tag_command(TagAction::Create {
        name: "v0.9".to_string(),
        commit: Some("HEAD~1".to_string()),
        annotate: None,
    }).await?;

    // Delete the first tag.
    commands::tag_command(TagAction::Delete {
        name: "v1.0".to_string(),
    }).await?;

    assert_eq!(repo.refs().get_tag("v1.0")?, None);
    assert!(repo.refs().get_tag("v0.9")?.is_some());

    Ok(())
}

#[tokio::test]
async fn test_tag_annotated() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("release 1").await?;

    // Create an annotated tag.
    commands::tag_command(TagAction::Create {
        name: "v1.0".to_string(),
        commit: None,
        annotate: Some("Release 1.0 — first stable release".to_string()),
    }).await?;

    // Verify the tag ref exists.
    let repo = git_manager.repo();
    assert!(repo.refs().get_tag("v1.0")?.is_some());

    // Verify the annotation file exists.
    let annot_path = repo.refs().tag_path("v1.0").with_extension("annot");
    assert!(annot_path.exists(), "Annotation file should exist");

    // Verify annotation content.
    let content = std::fs::read_to_string(&annot_path)?;
    let ann: codetree::commands::tag::TagAnnotation = serde_json::from_str(&content)?;
    assert_eq!(ann.message, "Release 1.0 — first stable release");

    // List should show the message.
    commands::tag_command(TagAction::List).await?;

    // Delete should remove both the ref and the annotation.
    commands::tag_command(TagAction::Delete {
        name: "v1.0".to_string(),
    }).await?;

    assert!(!annot_path.exists(), "Annotation file should be deleted");

    Ok(())
}

#[tokio::test]
async fn test_file_search() -> 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())?;

    tokio::fs::write(repo_path.join("main.rs"), "fn main() {\n    println!(\"hello\");\n}\n").await?;
    tokio::fs::write(repo_path.join("lib.rs"), "pub fn greet() {\n    println!(\"hello\");\n}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("add files").await?;

    // Search for "hello" — should find 2 matches.
    commands::file_search_command("hello".to_string(), false).await?;

    // Verify programmatically.
    let results = git_manager.file_search("hello")?;
    assert_eq!(results.len(), 2, "Should find 2 matches for 'hello'");

    Ok(())
}

#[tokio::test]
async fn test_file_list() -> 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())?;

    tokio::fs::write(repo_path.join("file1.rs"), "content\n").await?;
    tokio::fs::write(repo_path.join("file2.rs"), "content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("add files").await?;

    let files = git_manager.file_list(None)?;
    assert!(files.contains(&"file1.rs".to_string()), "Should list file1.rs");
    assert!(files.contains(&"file2.rs".to_string()), "Should list file2.rs");

    // Also test the command.
    commands::file_list_command(None).await?;

    Ok(())
}

#[tokio::test]
async fn test_heads() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("first").await?;

    let heads = git_manager.heads()?;
    assert!(!heads.is_empty(), "Should have at least one branch head");

    // Also test the command.
    commands::heads_command().await?;

    Ok(())
}

#[tokio::test]
async fn test_log_count() -> 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())?;

    for i in 0..3 {
        tokio::fs::write(repo_path.join(format!("file{}.rs", i)), format!("content {}\n", i)).await?;
        git_manager.add_all().await?;
        git_manager.commit(&format!("commit {}", i)).await?;
    }

    // Log --count should print the commit count.
    commands::log_command(None, None, true).await?;

    Ok(())
}

#[tokio::test]
async fn test_file_search_name_only() -> 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())?;

    tokio::fs::write(repo_path.join("main.rs"), "fn main() {}\n").await?;
    tokio::fs::write(repo_path.join("lib.rs"), "pub fn lib() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("add files").await?;

    // Search for file names containing "main".
    let names = git_manager.file_search_names("main")?;
    assert!(names.contains(&"main.rs".to_string()), "Should find main.rs by name");

    // Also test the command.
    commands::file_search_command("main".to_string(), true).await?;

    Ok(())
}

#[tokio::test]
async fn test_forks() -> 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())?;

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

    // Create a branch to create a fork point.
    git_manager.create_branch("feature", None).await?;

    // Forks should find the base commit (it has 2 children: main and feature).
    let _forks = git_manager.forks()?;
    // Note: forks only shows commits with multiple children across branches
    // that have tips. The base commit won't have children until both branches
    // have commits on top of it. For now, just verify the command runs.
    commands::forks_command().await?;

    Ok(())
}

#[tokio::test]
async fn test_merge_point() -> 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())?;

    tokio::fs::write(repo_path.join("base.rs"), "content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("base").await?;
    let base_hash = git_manager.get_head_hash()?;

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

    // Merge point of HEAD with itself should be HEAD.
    let mp = git_manager.merge_point("HEAD", "HEAD")?;
    assert!(mp.is_some(), "Merge point of HEAD with itself should exist");

    // Merge point of HEAD with HEAD~1 should be HEAD~1.
    let mp = git_manager.merge_point("HEAD", "HEAD~1")?;
    assert_eq!(mp, Some(base_hash), "Merge point should be the base commit");

    // Also test the command.
    commands::merge_point_command("HEAD".to_string(), "HEAD~1".to_string()).await?;

    Ok(())
}

#[tokio::test]
async fn test_verify() -> 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())?;

    tokio::fs::write(repo_path.join("file.rs"), "content\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("first").await?;

    // Verify HEAD — should have no issues.
    let issues = git_manager.verify_commit("HEAD")?;
    assert!(issues.is_empty(), "HEAD should verify cleanly: {:?}", issues);

    // Also test the command.
    commands::verify_command("HEAD".to_string()).await?;

    Ok(())
}

#[tokio::test]
async fn test_run_command() -> 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())?;

    tokio::fs::write(repo_path.join("file1.rs"), "fn f1() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("first").await?;

    tokio::fs::write(repo_path.join("file2.rs"), "fn f2() {}\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("second").await?;

    // Run a simple command (echo) across both commits.
    commands::run_command("HEAD~1".to_string(), vec![
        "sh".to_string(),
        "-c".to_string(),
        "echo running".to_string(),
    ]).await?;

    // Verify the working tree was restored to HEAD after the run.
    let head_content = tokio::fs::read_to_string(repo_path.join("file2.rs")).await?;
    assert_eq!(head_content, "fn f2() {}\n", "Working tree should be restored to HEAD after run");

    Ok(())
}

#[tokio::test]
async fn test_config_get_set_list() -> 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?;

    // List config (should show default values).
    commands::config_command(ConfigAction::List).await?;

    // Get a known config value.
    commands::config_command(ConfigAction::Get("git.base_branch".to_string())).await?;

    // Set a config value.
    commands::config_command(ConfigAction::Set(
        "git.base_branch".to_string(),
        "develop".to_string(),
    )).await?;

    // Verify it was set.
    commands::config_command(ConfigAction::Get("git.base_branch".to_string())).await?;

    Ok(())
}


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

    // Start an operation with checkout so saves land on the op branch.
    commands::start_command(
        "Fix login validation".to_string(),
        false, // checkout (not parallel)
        false,
        false,
        None,
        None,
        None,
        None,
        Some("agent-7".to_string()),
        false,
    ).await?;

    tokio::fs::write(repo_path.join("login.rs"), "fn check() -> bool {\n    true\n}\n").await?;
    commands::save_command(
        vec!["save work".to_string()],
        false,
        false,
        Some("user asked to fix login validation".to_string()),
    ).await?;

    // The provenance sidecar records commit → operation/agent/prompt.
    let prov = codetree::provenance::ProvenanceLog::load(&repo_path)?;
    assert_eq!(prov.entries.len(), 1);
    let entry = &prov.entries[0];
    assert_eq!(entry.agent_id.as_deref(), Some("agent-7"));
    assert_eq!(entry.prompt.as_deref(), Some("user asked to fix login validation"));
    assert!(entry.operation.contains("fix_login_validation"));

    // `why file` resolves the newest commit for the file.
    let mgr = VcsManager::new(repo_path.clone())?;
    let info = commands::lookup_why(&mgr, &prov, "login.rs").await?;
    assert_eq!(info.agent_id.as_deref(), Some("agent-7"));
    assert_eq!(info.prompt.as_deref(), Some("user asked to fix login validation"));
    assert!(info.operation.as_deref().unwrap().contains("fix_login_validation"));

    // `why file:line` resolves the same commit via blame (7-char hash prefix).
    let line_info = commands::lookup_why(&mgr, &prov, "login.rs:1").await?;
    assert_eq!(line_info.commit, info.commit);
    assert!(prov.get(&info.commit[..7]).is_some());

    // CLI command path works end-to-end.
    commands::why_command("login.rs".to_string()).await?;
    commands::why_command("login.rs:1".to_string()).await?;

    Ok(())
}