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
//! Model Context Protocol (MCP) Server for CodeTree
//!
//! Lightweight MCP server exposing CodeTree's elementary commands
//! for AI-agent integration.

use rmcp::{
    ErrorData as McpError,
    RoleServer,
    ServerHandler,
    handler::server::{
        router::tool::ToolRouter,
        wrapper::Parameters,
    },
    model::*,
    service::RequestContext,
    tool,
    tool_handler,
    tool_router,
};
use serde_json::json;
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::{BranchManager, VcsManager, Config, BranchStatus};

/// MCP server handler for CodeTree
#[derive(Clone)]
pub struct CodetreeServer {
    branch_manager: Arc<RwLock<BranchManager>>,
    git_manager: Arc<VcsManager>,
    codetree_config: Config,
    #[allow(dead_code)]
    tool_router: ToolRouter<Self>,
}

impl CodetreeServer {
    pub fn new(
        branch_manager: Arc<RwLock<BranchManager>>,
        git_manager: Arc<VcsManager>,
        codetree_config: Config,
    ) -> Self {
        Self {
            branch_manager,
            git_manager,
            codetree_config,
            tool_router: Self::tool_router(),
        }
    }

    fn _create_resource_text(&self, uri: &str, name: &str) -> Resource {
        Resource::new(
            rmcp::model::RawResource {
                uri: uri.to_string(),
                name: name.to_string(),
                title: None,
                description: None,
                mime_type: Some("text/plain".to_string()),
                size: None,
                icons: None,
                meta: None,
            },
            None,
        )
    }
}

#[tool_router]
impl CodetreeServer {
    /// Initialize codetree in current directory
    #[tool(description = "Initialize codetree in current directory")]
    async fn init_repository(
        &self,
        Parameters(args): Parameters<InitRepositoryArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        match crate::commands::init_command(args.force).await {
            Ok(()) => {
                let result = json!({
                    "success": true,
                    "message": if args.force {
                        "Repository reinitialized with codetree"
                    } else {
                        "Repository initialized with codetree"
                    },
                    "config_file": ".codetree/config.toml"
                });
                Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
            }
            Err(e) => {
                let result = json!({"success": false, "error": e.to_string()});
                Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
            }
        }
    }

    /// Start a new mini-operation branch
    #[tool(description = "Start a new mini-operation branch")]
    async fn start_op(
        &self,
        Parameters(args): Parameters<StartOpArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let slug = crate::utils::slugify(&args.description);
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let branch_prefix: String = if let Some(template_name) = &args.template {
            if let Some(tmpl) = self.codetree_config.get_template(template_name) {
                tmpl.branch_prefix.clone().unwrap_or_else(|| self.codetree_config.git.branch_prefix.clone())
            } else {
                let err = json!({"success": false, "error": format!("Unknown template: '{}'", template_name)});
                return Ok(CallToolResult::success(vec![Content::text(err.to_string())]));
            }
        } else {
            self.codetree_config.git.branch_prefix.clone()
        };
        let branch_name = format!("{}_{}_{}", branch_prefix, timestamp, slug);

        let current = match self.git_manager.get_current_branch().await {
            Ok(b) => b,
            Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
        };

        let base_branch = {
            let bm = self.branch_manager.read().await;
            if let Some(branch) = bm.get_branch(&current) {
                if matches!(branch.status, crate::BranchStatus::Active) {
                    current.clone()
                } else {
                    self.codetree_config.git.base_branch.clone()
                }
            } else {
                self.codetree_config.git.base_branch.clone()
            }
        };

        let res = if args.branchless {
            let mut bm = self.branch_manager.write().await;
            match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
                Ok(_) => {
                    if let Some(branch) = bm.branches.get_mut(&branch_name) {
                        branch.branchless = true;
                        let _ = bm.save().await;
                    }
                    json!({"success": true, "branch": branch_name, "status": "created_branchless", "base": current})
                }
                Err(e) => json!({"success": false, "error": e.to_string()}),
            }
        } else if args.worktree {
            let worktree_path = self.git_manager.repo_path().join(".codetree").join("worktrees").join(&branch_name);
            match tokio::fs::create_dir_all(&worktree_path).await {
                Ok(_) => match self.git_manager.add_worktree_new_branch(&branch_name, &worktree_path, &base_branch).await {
                    Ok(_) => {
                        let mut bm = self.branch_manager.write().await;
                        match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
                            Ok(_) => {
                                let _ = bm.set_branch_worktree(&branch_name, worktree_path.clone()).await;
                                json!({"success": true, "branch": branch_name, "status": "created_worktree", "base": base_branch, "worktree": worktree_path.to_string_lossy()})
                            }
                            Err(e) => json!({"success": false, "error": e.to_string()}),
                        }
                    }
                    Err(e) => json!({"success": false, "error": e.to_string()}),
                }
                Err(e) => json!({"success": false, "error": e.to_string()}),
            }
        } else {
            match self.git_manager.create_branch(&branch_name, Some(&base_branch)).await {
                Ok(_) => {
                    if args.parallel {
                        let mut bm = self.branch_manager.write().await;
                        match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
                            Ok(_) => json!({"success": true, "branch": branch_name, "status": "created_parallel", "base": base_branch, "current": current}),
                            Err(e) => json!({"success": false, "error": e.to_string()}),
                        }
                    } else {
                        match self.git_manager.checkout_branch(&branch_name).await {
                            Ok(_) => {
                                let mut bm = self.branch_manager.write().await;
                                match bm.register_branch_full(&branch_name, args.files.clone().unwrap_or_default(), args.description, args.depends_on.clone().unwrap_or_default(), args.template.clone(), args.tags.clone().unwrap_or_default(), args.agent_id.clone()).await {
                                    Ok(_) => json!({"success": true, "branch": branch_name, "status": "started", "base": base_branch}),
                                    Err(e) => json!({"success": false, "error": e.to_string()}),
                                }
                            }
                            Err(e) => json!({"success": false, "error": e.to_string()}),
                        }
                    }
                }
                Err(e) => json!({"success": false, "error": e.to_string()}),
            }
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Save all current changes to the active branch
    #[tool(description = "Save all current changes to the active operation branch")]
    async fn save_changes(
        &self,
        Parameters(args): Parameters<SaveChangesArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let current = match self.git_manager.get_current_branch().await {
            Ok(b) => b,
            Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
        };
        let status = match self.git_manager.get_status().await {
            Ok(s) => s,
            Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
        };
        let files: Vec<String> = [status.untracked, status.modified, status.staged].concat();
        if files.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(json!({"success": true, "message": "No changes to save", "branch": current}).to_string())]));
        }
        let msg = if let Some(msg) = args.message {
            msg
        } else {
            let summary = if files.len() == 1 {
                files[0].clone()
            } else if files.len() <= 4 {
                files.join(", ")
            } else {
                format!("{} files", files.len())
            };

            let bm = self.branch_manager.read().await;
            if let Some(branch) = bm.get_branch(&current) {
                if let Some(template_name) = &branch.template {
                    if let Some(tmpl) = self.codetree_config.get_template(template_name) {
                        tmpl.commit_message_format.replace("{description}", &summary)
                    } else {
                        format!("Save changes to {}", summary)
                    }
                } else {
                    format!("Save changes to {}", summary)
                }
            } else {
                format!("Save changes to {}", summary)
            }
        };
        // Validation gate
        let should_validate = !args.no_validate.unwrap_or(false) && (args.validate.unwrap_or(false) || self.codetree_config.validation.is_required());

        if should_validate {
            if let Some(cmd) = &self.codetree_config.validation.command {
                let output = match tokio::process::Command::new("sh")
                    .arg("-c")
                    .arg(cmd)
                    .output()
                    .await
                {
                    Ok(o) => o,
                    Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": format!("Failed to run validation: {}", e)}).to_string())])),
                };
                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": format!("Validation failed: {}", stderr.trim())}).to_string())]));
                }
            } else if self.codetree_config.validation.is_required() || args.validate.unwrap_or(false) {
                return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": "Validation requested but no command configured. Set [validation] command in config.toml."}).to_string())]));
            }
        }

        let res = match self.git_manager.add_all().await {
            Ok(_) => match self.git_manager.commit(&msg).await {
                Ok(commit_hash) => {
                    let agent_id = {
                        let mut bm = self.branch_manager.write().await;
                        let _ = bm.update_branch_files(&current, &files).await;
                        bm.get_branch(&current).and_then(|b| b.agent_id.clone())
                    };
                    // Provenance sidecar: commit → operation/agent/prompt (TODO Round 13)
                    if let Ok(mut prov) = crate::provenance::ProvenanceLog::load(self.git_manager.repo_path()) {
                        prov.record(&commit_hash, &current, agent_id, args.prompt.clone());
                        let _ = prov.save(self.git_manager.repo_path());
                    }
                    json!({"success": true, "branch": current, "files": files.len(), "message": msg, "commit": commit_hash})
                }
                Err(e) => json!({"success": false, "error": e.to_string()}),
            },
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Show provenance for a file or line
    #[tool(description = "Show provenance for a file or line: the commit, operation, agent, and prompt that produced it")]
    async fn why(
        &self,
        Parameters(args): Parameters<WhyArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let prov = match crate::provenance::ProvenanceLog::load(self.git_manager.repo_path()) {
            Ok(p) => p,
            Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
        };
        let res = match crate::commands::why::lookup_why(&self.git_manager, &prov, &args.file).await {
            Ok(info) => json!({
                "success": true,
                "file": info.file,
                "line": info.line,
                "commit": info.commit,
                "timestamp": info.timestamp,
                "message": info.message,
                "operation": info.operation,
                "agent_id": info.agent_id,
                "prompt": info.prompt,
            }),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Create a labeled turn-level checkpoint
    #[tool(description = "Create a labeled turn-level checkpoint as a rewind target. Recorded even on a clean tree; survives save")]
    async fn checkpoint(
        &self,
        Parameters(args): Parameters<CheckpointArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::snapshot::create_checkpoint(&self.git_manager, args.label).await {
            Ok((id, commit, branch, files)) => json!({
                "success": true, "checkpoint_id": id, "commit": commit, "branch": branch, "files": files
            }),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Rewind the working tree to a checkpoint
    #[tool(description = "Rewind the working tree to a checkpoint (HEAD/history untouched). dry_run previews changed files")]
    async fn rewind(
        &self,
        Parameters(args): Parameters<RewindArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let dry_run = args.dry_run.unwrap_or(false);
        let res = match crate::commands::snapshot::rewind_working_tree(&self.git_manager, args.id, dry_run).await {
            Ok((commit, label, changed)) => json!({
                "success": true, "checkpoint_id": args.id, "commit": commit, "label": label,
                "dry_run": dry_run, "changed_files": changed
            }),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Converge divergent commits of an operation
    #[tool(description = "Combine divergent commits of an operation (e.g. two agents on one operation) into a single merge commit")]
    async fn converge_op(
        &self,
        Parameters(args): Parameters<ConvergeOpArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let mut bm = self.branch_manager.write().await;
        let res = match crate::commands::converge::converge_operations(
            &self.git_manager,
            &mut bm,
            args.operation,
            args.dry_run.unwrap_or(false),
        ).await {
            Ok(report) => json!({
                "success": true,
                "dry_run": report.dry_run,
                "operations": report.operations,
            }),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Merge all active operations into one working state
    #[tool(description = "Merge all active operations into one working state (megamerge) so cross-operation conflicts surface before finish")]
    async fn megamerge_op(
        &self,
        Parameters(args): Parameters<MegamergeOpArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let mut bm = self.branch_manager.write().await;
        let res = match crate::commands::megamerge::megamerge_state(
            &self.git_manager,
            &mut bm,
            args.abort.unwrap_or(false),
        ).await {
            Ok(outcome) => json!({
                "success": true,
                "aborted": outcome.aborted,
                "commit": outcome.commit,
                "operations": outcome.operations,
                "conflicts": outcome.conflicts,
            }),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Route working-tree changes back to their owning operations
    #[tool(description = "Route working-tree changes back to the operations that own them (megamerge mode)")]
    async fn route_op(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let mut bm = self.branch_manager.write().await;
        let res = match crate::commands::megamerge::route_changes(&self.git_manager, &mut bm).await {
            Ok(report) => json!({
                "success": true,
                "routed": report.routed,
                "unrouted": report.unrouted,
                "operations": report.operations,
            }),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Merge an operation branch back into the base branch
    #[tool(description = "Merge an operation branch back into the base branch")]
    async fn merge_branch(
        &self,
        Parameters(args): Parameters<MergeBranchArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let target = match args.branch {
            Some(b) => b,
            None => match self.git_manager.get_current_branch().await {
                Ok(b) => b,
                Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
            }
        };
        let base = &self.codetree_config.git.base_branch;
        let res = match self.git_manager.checkout_branch(base).await {
            Ok(_) => {
                let cache_path = self.git_manager.repo_path()
                    .join(".codetree").join("resolutions.json");
                let mut cache = match crate::resolution::ResolutionCache::load(&cache_path).await {
                    Ok(c) => c,
                    Err(e) => return Ok(CallToolResult::success(vec![Content::text(
                        json!({"success": false, "error": e.to_string()}).to_string())])),
                };
                // Merge drivers come from config; the manager is behind an Arc,
                // so clone it (cheap: Arc<Repository> + PathBuf) when drivers
                // are configured.
                let merge_result = if self.codetree_config.merge.drivers.is_empty() {
                    if args.squash {
                        self.git_manager.squash_merge_branch_with_cache(&target, &mut cache).await
                    } else {
                        self.git_manager.merge_branch_with_cache(&target, &mut cache).await
                    }
                } else {
                    let mut mgr = (*self.git_manager).clone();
                    mgr.set_merge_drivers(self.codetree_config.merge.drivers.clone());
                    if args.squash {
                        mgr.squash_merge_branch_with_cache(&target, &mut cache).await
                    } else {
                        mgr.merge_branch_with_cache(&target, &mut cache).await
                    }
                };
                match merge_result {
                    Ok(result) => {
                        if !result.driver_resolved.is_empty() {
                            // Persist driver resolutions for future merges.
                            let _ = cache.save(&cache_path).await;
                        }
                        if !result.resolved_from_cache && !result.conflicts.is_empty() {
                            // First-class conflicts: merge committed, awaiting resolution.
                            let files: Vec<_> = result.conflicts.iter()
                                .map(|c| c.path.as_str()).collect();
                            json!({
                                "success": true,
                                "merged_branch": target,
                                "base_branch": base,
                                "squashed": args.squash,
                                "conflicts_pending": true,
                                "conflict_files": files,
                                "next_step": "resolve_op"
                            })
                        } else {
                            let resolved_from_cache = result.resolved_from_cache;
                            match self.git_manager.delete_branch(&target, false).await {
                                Ok(_) => {
                                    let mut bm = self.branch_manager.write().await;
                                    let _ = bm.mark_branch_merged(&target).await;
                                    json!({"success": true, "merged_branch": target, "base_branch": base, "squashed": args.squash, "auto_resolved": resolved_from_cache})
                                }
                                Err(e) => json!({"success": false, "error": e.to_string()}),
                            }
                        }
                    }
                    Err(e) => json!({"success": false, "error": e.to_string()}),
                }
            }
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Resolve pending merge conflicts (first-class conflicts) and finalize the merge
    #[tool(description = "Resolve pending merge conflicts and finalize the merge. After merge_branch returns conflicts_pending, edit the files and call this to finish.")]
    async fn resolve_op(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::merge::resolve_command().await {
            Ok(()) => json!({"success": true, "message": "Conflicts resolved and merge finalized"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Finish an operation: merge back to base and clean up
    #[tool(description = "Finish an operation by merging it back to base and cleaning up")]
    async fn finish_op(
        &self,
        Parameters(args): Parameters<FinishOpArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::finish_command(args.branch, None, false).await {
            Ok(()) => json!({"success": true, "message": "Operation finished"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Withdraw an operation: fully revert and remove it
    #[tool(description = "Withdraw an operation by fully reverting and removing it")]
    async fn withdraw_op(
        &self,
        Parameters(args): Parameters<WithdrawOpArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::withdraw_command(Some(args.branch), None).await {
            Ok(()) => json!({"success": true, "message": "Operation withdrawn"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Compare diffs across all active operations
    #[tool(description = "Compare diffs across all active operations")]
    async fn compare_ops(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::compare_command().await {
            Ok(()) => json!({"success": true, "message": "Comparison displayed"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Rebase all active operation branches onto the base branch
    #[tool(description = "Rebase all active operation branches onto the base branch")]
    async fn rebase_ops(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::rebase_command(false).await {
            Ok(()) => json!({"success": true, "message": "All active branches rebased"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Get current status of all managed branches
    #[tool(description = "Get current status of all managed branches")]
    async fn get_status(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let current = match self.git_manager.get_current_branch().await {
            Ok(b) => b,
            Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
        };
        let status = match self.git_manager.get_status().await {
            Ok(s) => s,
            Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
        };
        let branch_manager = self.branch_manager.read().await;
        let branches = branch_manager.list_branches();
        let active: Vec<serde_json::Value> = branches
            .iter()
            .filter(|b| matches!(b.status, BranchStatus::Active))
            .map(|b| json!({"name": b.name, "description": b.change_group.description, "created_at": b.created_at, "files": b.change_group.files.len()}))
            .collect();

        // Detect file conflicts between active operations
        let active_refs: Vec<_> = branches.iter()
            .filter(|b| matches!(b.status, BranchStatus::Active))
            .collect();
        let mut conflicts = Vec::new();
        if active_refs.len() >= 2 {
            for i in 0..active_refs.len() {
                for j in (i + 1)..active_refs.len() {
                    let files_i: std::collections::HashSet<&String> = active_refs[i].change_group.files.iter().collect();
                    let shared: Vec<&String> = active_refs[j].change_group.files.iter()
                        .filter(|f| files_i.contains(f))
                        .collect();
                    if !shared.is_empty() {
                        conflicts.push(json!({
                            "between": [active_refs[i].name, active_refs[j].name],
                            "files": shared
                        }));
                    }
                }
            }
        }

        let result = json!({
            "success": true,
            "current_branch": current,
            "modified": status.modified.len(),
            "untracked": status.untracked.len(),
            "staged": status.staged.len(),
            "active_operations": active.len(),
            "operations": active,
            "conflicts": conflicts
        });
        Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
    }

    /// List all managed branches
    #[tool(description = "List all managed branches")]
    async fn list_branches(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let branch_manager = self.branch_manager.read().await;
        let branches = branch_manager.list_branches();
        let branch_data: Vec<serde_json::Value> = branches
            .iter()
            .map(|b| json!({
                "name": b.name,
                "status": b.status.as_str(),
                "created_at": b.created_at,
                "description": b.change_group.description,
                "files": b.change_group.files.len()
            }))
            .collect();
        let result = json!({
            "success": true,
            "branches": branch_data,
            "total": branch_data.len()
        });
        Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
    }

    /// Undo an operation (last by default, or specify by index)
    #[tool(description = "Undo an operation (last by default, or specify by index). Use index=null for last operation.")]
    async fn undo_op(
        &self,
        Parameters(args): Parameters<UndoOpArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let is_list = args.list.unwrap_or(false);
        let res = match crate::commands::undo_command(args.index, is_list).await {
            Ok(()) if is_list => json!({"success": true, "message": "Operations listed"}),
            Ok(()) => json!({"success": true, "message": "Operation undone"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Publish an operation as a GitHub PR
    #[tool(description = "Publish an operation branch as a GitHub PR. Pushes to remote and auto-creates PR if gh CLI is installed.")]
    async fn publish_op(
        &self,
        Parameters(args): Parameters<PublishOpArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::publish_command(args.branch).await {
            Ok(()) => json!({"success": true, "message": "PR published"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Freeze a file or directory — prevents any modification by operations
    #[tool(description = "Freeze a file or directory so no operation can modify it")]
    async fn freeze_path(
        &self,
        Parameters(args): Parameters<FreezePathArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::freeze_command(args.path).await {
            Ok(()) => json!({"success": true, "message": "Path frozen"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Unfreeze a file or directory — allows modifications again
    #[tool(description = "Unfreeze a file or directory, allowing modifications again")]
    async fn unfreeze_path(
        &self,
        Parameters(args): Parameters<UnfreezePathArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::unfreeze_command(args.path, args.force.unwrap_or(false)).await {
            Ok(()) => json!({"success": true, "message": "Path unfrozen"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// List all frozen paths
    #[tool(description = "List all frozen paths in the repository")]
    async fn list_frozen(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::frozen_command().await {
            Ok(()) => json!({"success": true, "message": "Frozen paths listed"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Release a file lock manually
    #[tool(description = "Manually release a file lock (e.g. if an agent crashed)")]
    async fn unlock_file(
        &self,
        Parameters(args): Parameters<UnlockFileArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::unlock_command(args.path).await {
            Ok(()) => json!({"success": true, "message": "File unlocked"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// List all active file locks
    #[tool(description = "List all active file locks and which operation holds them")]
    async fn list_locks(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::locks_command().await {
            Ok(()) => json!({"success": true, "message": "Locks listed"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Evaluate candidates in a candidate group
    #[tool(description = "Evaluate and compare candidate operations in a group")]
    async fn evaluate_candidates(
        &self,
        Parameters(args): Parameters<EvaluateCandidatesArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::evaluate_command(args.group).await {
            Ok(()) => json!({"success": true, "message": "Candidates evaluated"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Promote a candidate operation — merge it and withdraw all others in the group
    #[tool(description = "Promote a candidate operation: merge the winner and withdraw all others in the group")]
    async fn promote_candidate(
        &self,
        Parameters(args): Parameters<PromoteCandidateArgs>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let res = match crate::commands::promote_command(args.group, args.operation).await {
            Ok(()) => json!({"success": true, "message": "Candidate promoted"}),
            Err(e) => json!({"success": false, "error": e.to_string()}),
        };
        Ok(CallToolResult::success(vec![Content::text(res.to_string())]))
    }

    /// Show current position in the version tree
    #[tool(description = "Show current position in the version tree: current branch, parent, base, divergence, siblings, children")]
    async fn whereami(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let current = match self.git_manager.get_current_branch().await {
            Ok(b) => b,
            Err(e) => return Ok(CallToolResult::success(vec![Content::text(json!({"success": false, "error": e.to_string()}).to_string())])),
        };

        let base_branch = self.codetree_config.git.base_branch.clone();

        let (ahead, behind) = self.git_manager.get_branch_divergence(&current, &base_branch)
            .unwrap_or((0, 0));

        let bm = self.branch_manager.read().await;
        let branch_info = bm.get_branch(&current);

        let parent = branch_info
            .and_then(|b| b.parent_branch.clone())
            .unwrap_or_else(|| {
                let git_branch_names: Vec<String> = bm.list_branches()
                    .into_iter()
                    .filter(|b| matches!(b.status, crate::BranchStatus::Active) && !b.branchless)
                    .map(|b| b.name.clone())
                    .collect();
                self.git_manager.get_branch_parent(&current, &base_branch, &git_branch_names)
                    .unwrap_or_else(|_| base_branch.clone())
            });

        let siblings: Vec<String> = bm.list_branches()
            .into_iter()
            .filter(|b| {
                matches!(b.status, crate::BranchStatus::Active)
                    && !b.branchless
                    && b.name != current
                    && b.parent_branch.as_deref() == Some(&parent)
            })
            .map(|b| b.name.clone())
            .collect();

        let children: Vec<String> = bm.list_branches()
            .into_iter()
            .filter(|b| {
                matches!(b.status, crate::BranchStatus::Active)
                    && !b.branchless
                    && b.parent_branch.as_deref() == Some(&current)
            })
            .map(|b| b.name.clone())
            .collect();

        let result = json!({
            "success": true,
            "current_branch": current,
            "base_branch": base_branch,
            "parent_branch": parent,
            "ahead": ahead,
            "behind": behind,
            "siblings": siblings,
            "children": children,
            "description": branch_info.map(|b| b.change_group.description.clone()),
            "tags": branch_info.map(|b| b.tags.clone()).unwrap_or_default(),
            "agent_id": branch_info.and_then(|b| b.agent_id.clone()),
        });
        Ok(CallToolResult::success(vec![Content::text(result.to_string())]))
    }
}

#[tool_handler]
impl ServerHandler for CodetreeServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .build(),
        )
        .with_server_info(Implementation::from_build_env())
        .with_protocol_version(ProtocolVersion::V_2024_11_05)
        .with_instructions(
            "CodeTree is an AI-native VCS for autonomous coding agents. Tools: init_repository, start_op, save_changes, finish_op, withdraw_op, compare_ops, rebase_ops, merge_branch, resolve_op, undo_op, publish_op, get_status, list_branches, freeze_path, unfreeze_path, list_frozen, unlock_file, list_locks, evaluate_candidates, promote_candidate, whereami, why, checkpoint, rewind, converge_op, megamerge_op, route_op".to_string(),
        )
    }

    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, McpError> {
        Ok(ListResourcesResult {
            resources: vec![
                self._create_resource_text("config://codetree", "Configuration"),
                self._create_resource_text("status://branches", "Branch Status"),
                self._create_resource_text("diff://current", "Current Diff"),
            ],
            next_cursor: None,
            meta: None,
        })
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResult, McpError> {
        match request.uri.as_str() {
            "config://codetree" => {
                let config = json!({
                    "git": {
                        "branch_prefix": self.codetree_config.git.branch_prefix,
                        "base_branch": self.codetree_config.git.base_branch,
                        "auto_push": self.codetree_config.git.auto_push,
                        "remote_name": self.codetree_config.git.remote_name
                    }
                });
                Ok(ReadResourceResult::new(vec![ResourceContents::text(config.to_string(), request.uri.clone())]))
            }
            "status://branches" => {
                let branch_manager = self.branch_manager.read().await;
                let branches = branch_manager.list_branches();
                let (total, active, merged, archived) = branches.iter().fold(
                    (0, 0, 0, 0),
                    |(total, active, merged, archived), b| {
                        (
                            total + 1,
                            active + if matches!(b.status, BranchStatus::Active) { 1 } else { 0 },
                            merged + if matches!(b.status, BranchStatus::Merged) { 1 } else { 0 },
                            archived + if matches!(b.status, BranchStatus::Archived) { 1 } else { 0 },
                        )
                    },
                );
                let status = json!({"total": total, "active": active, "merged": merged, "archived": archived});
                Ok(ReadResourceResult::new(vec![ResourceContents::text(status.to_string(), request.uri.clone())]))
            }
            "diff://current" => {
                match self.git_manager.get_diff() {
                    Ok(diff) => {
                        let content = if diff.is_empty() {
                            "No changes in working tree.".to_string()
                        } else {
                            diff
                        };
                        Ok(ReadResourceResult::new(vec![ResourceContents::text(content, request.uri.clone())]))
                    }
                    Err(e) => Ok(ReadResourceResult::new(vec![ResourceContents::text(format!("Error reading diff: {}", e), request.uri.clone())])),
                }
            }
            _ => Err(McpError::resource_not_found(
                "resource_not_found",
                Some(json!({"uri": request.uri})),
            )),
        }
    }
}

// Tool argument types
#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct InitRepositoryArgs {
    #[schemars(description = "Force reinitialization if already initialized")]
    #[serde(default = "default_force")]
    pub force: bool,
}

fn default_force() -> bool {
    false
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct StartOpArgs {
    #[schemars(description = "Description for the mini-operation (used in branch name)")]
    pub description: String,
    #[schemars(description = "Create branch without checking out (parallel operation)")]
    #[serde(default = "default_parallel")]
    pub parallel: bool,
    #[schemars(description = "Create a git worktree for the operation (implies parallel)")]
    #[serde(default = "default_worktree")]
    pub worktree: bool,
    #[schemars(description = "Branchless mode: track as bookmark without creating a git branch")]
    #[serde(default = "default_branchless")]
    pub branchless: bool,
    #[schemars(description = "Files assigned to this operation (pre-declares scope)")]
    #[serde(default)]
    pub files: Option<Vec<String>>,
    #[schemars(description = "Operations this one depends on (must finish first)")]
    #[serde(default)]
    pub depends_on: Option<Vec<String>>,
    #[schemars(description = "Operation template (refactor, bugfix, feature)")]
    pub template: Option<String>,
    #[schemars(description = "Tags for grouping operations (e.g., sprint-42, bugfix-week)")]
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    #[schemars(description = "Agent identifier for multi-agent tracking")]
    #[serde(default)]
    pub agent_id: Option<String>,
}

fn default_branchless() -> bool {
    false
}

fn default_worktree() -> bool {
    false
}

fn default_parallel() -> bool {
    false
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct SaveChangesArgs {
    #[schemars(description = "Optional commit message")]
    pub message: Option<String>,
    #[schemars(description = "Run validation command before committing")]
    pub validate: Option<bool>,
    #[schemars(description = "Skip validation even if config requires it")]
    pub no_validate: Option<bool>,
    #[schemars(description = "Prompt/intent that produced this change (recorded as provenance, queried via the why tool)")]
    pub prompt: Option<String>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct WhyArgs {
    #[schemars(description = "File to explain (`path` or `path:line`, 1-based line)")]
    pub file: String,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct CheckpointArgs {
    #[schemars(description = "Label for the checkpoint (e.g. the prompt or intent of this turn)")]
    pub label: Option<String>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct RewindArgs {
    #[schemars(description = "Checkpoint id to rewind to (from the checkpoint tool or `snapshots`)")]
    pub id: usize,
    #[schemars(description = "Preview changed files without touching the working tree")]
    pub dry_run: Option<bool>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct ConvergeOpArgs {
    #[schemars(description = "Operation to converge (default: every operation with divergence)")]
    pub operation: Option<String>,
    #[schemars(description = "Preview divergent heads without converging")]
    pub dry_run: Option<bool>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct MegamergeOpArgs {
    #[schemars(description = "Discard the megamerge and restore the base branch")]
    pub abort: Option<bool>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct MergeBranchArgs {
    #[schemars(description = "Branch to merge (defaults to current)")]
    pub branch: Option<String>,
    #[schemars(description = "Combine all feature-branch commits into a single commit")]
    #[serde(default = "default_squash")]
    pub squash: bool,
}

fn default_squash() -> bool {
    false
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct FinishOpArgs {
    #[schemars(description = "Branch to finish (defaults to current)")]
    pub branch: Option<String>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct WithdrawOpArgs {
    #[schemars(description = "Branch or bookmark to fully revert")]
    pub branch: String,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct UndoOpArgs {
    #[schemars(description = "Operation index to undo (omit for most recent)")]
    #[serde(default)]
    pub index: Option<usize>,
    #[schemars(description = "List all undoable operations with indices")]
    #[serde(default)]
    pub list: Option<bool>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct PublishOpArgs {
    #[schemars(description = "Branch to publish (defaults to current)")]
    pub branch: Option<String>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct FreezePathArgs {
    #[schemars(description = "Path to freeze (file or directory)")]
    pub path: String,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct UnfreezePathArgs {
    #[schemars(description = "Path to unfreeze")]
    pub path: String,
    #[schemars(description = "Skip confirmation prompt")]
    #[serde(default)]
    pub force: Option<bool>,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct UnlockFileArgs {
    #[schemars(description = "Path to unlock")]
    pub path: String,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct EvaluateCandidatesArgs {
    #[schemars(description = "Candidate group name to evaluate")]
    pub group: String,
}

#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
pub struct PromoteCandidateArgs {
    #[schemars(description = "Candidate group name")]
    pub group: String,
    #[schemars(description = "Operation name to promote as the winner")]
    pub operation: String,
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_codetree_server_creation() {
        // Test that server can be created (will need managers in integration tests)
    }
}