codetree 0.1.1

AI-native version control system for autonomous agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
use crate::error::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::fs;

/// Current Unix timestamp in seconds
pub(crate) fn now_ts() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

/// Simplified change information (no monitoring)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangeGroup {
    pub files: Vec<String>,
    pub description: String,
    pub created_at: u64,
}

/// Branch metadata for an AI-agent mini-operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BranchInfo {
    pub name: String,
    pub created_at: u64,
    pub updated_at: u64,
    pub change_group: ChangeGroup,
    pub status: BranchStatus,
    #[serde(default)]
    pub template: Option<String>,
    #[serde(default)]
    pub worktree: Option<std::path::PathBuf>,
    #[serde(default)]
    pub branchless: bool,
    #[serde(default)]
    pub depends_on: Vec<String>,
    #[serde(default)]
    pub last_commit: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub parent_branch: Option<String>,
    #[serde(default)]
    pub agent_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum BranchStatus {
    /// Branch created and active for mini-operation
    Active,
    /// Branch has been merged back to base
    Merged,
    /// Branch archived or deleted
    Archived,
}

impl BranchStatus {
    /// Get a text representation for this status (machine-friendly for AI agents)
    pub fn as_str(&self) -> &str {
        match self {
            BranchStatus::Active => "active",
            BranchStatus::Merged => "merged",
            BranchStatus::Archived => "archived",
        }
    }
}

/// Branch manager for tracking and managing branches
pub struct BranchManager {
    pub branches: HashMap<String, BranchInfo>,
    data_file: std::path::PathBuf,
}

impl BranchManager {
    /// Create a new branch manager
    pub async fn new(data_file: std::path::PathBuf) -> Result<Self> {
        let mut manager = Self {
            branches: HashMap::new(),
            data_file,
        };
        
        // Load existing branch data
        if let Err(e) = manager.load_branches().await {
            warn!("Failed to load existing branches: {}", e);
        }
        
        Ok(manager)
    }

    /// Save branches to file
    pub async fn save(&self) -> Result<()> {
        self.save_branches().await
    }

    /// Get all branches as (name, status) pairs
    pub async fn get_all_branches(&self) -> Result<Vec<(String, BranchStatus)>> {
        Ok(self.branches.values()
            .map(|branch| (branch.name.clone(), branch.status.clone()))
            .collect())
    }

    /// Update branch status
    pub async fn update_branch_status(&mut self, branch_name: &str, status: BranchStatus) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.status = status;
            branch.updated_at = now_ts();
            self.save_branches().await?;
        }
        Ok(())
    }

    /// Update files tracked in a branch
    pub async fn update_branch_files(&mut self, branch_name: &str, files: &[String]) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            for f in files {
                if !branch.change_group.files.contains(f) {
                    branch.change_group.files.push(f.clone());
                }
            }
            branch.updated_at = now_ts();
            self.save_branches().await?;
        }
        Ok(())
    }

    /// Set the last commit hash for a branch (used for branchless auto-absorb)
    pub async fn set_branch_last_commit(&mut self, branch_name: &str, commit_hash: &str) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.last_commit = Some(commit_hash.to_string());
            branch.updated_at = now_ts();
            self.save_branches().await?;
        }
        Ok(())
    }

    /// Remove a branch from tracking
    pub async fn remove_branch(&mut self, branch_name: &str) -> Result<()> {
        self.branches.remove(branch_name);
        self.save_branches().await
    }

    /// Register a new branch
    pub async fn register_branch(&mut self, branch_name: &str, files: Vec<String>, description: String) -> Result<()> {
        self.register_branch_with_template(branch_name, files, description, Vec::new(), None).await
    }

    /// Register a new branch with an operation template
    pub async fn register_branch_with_template(&mut self, branch_name: &str, files: Vec<String>, description: String, depends_on: Vec<String>, template: Option<String>) -> Result<()> {
        self.register_branch_full(branch_name, files, description, depends_on, template, Vec::new(), None).await
    }

    /// Register a new branch with full options including tags
    #[allow(clippy::too_many_arguments)]
    pub async fn register_branch_full(&mut self, branch_name: &str, files: Vec<String>, description: String, depends_on: Vec<String>, template: Option<String>, tags: Vec<String>, agent_id: Option<String>) -> Result<()> {
        self.register_branch_full_no_save(branch_name, files, description, depends_on, template, tags, agent_id).await?;
        self.save_branches().await
    }

    /// Register a new branch without saving to disk (caller must call save() afterwards)
    #[allow(clippy::too_many_arguments)]
    pub async fn register_branch_full_no_save(&mut self, branch_name: &str, files: Vec<String>, description: String, depends_on: Vec<String>, template: Option<String>, tags: Vec<String>, agent_id: Option<String>) -> Result<()> {
        info!("Registering branch: {}", branch_name);

        let change_group = ChangeGroup {
            files,
            description,
            created_at: now_ts(),
        };

        let branch_info = BranchInfo {
            name: branch_name.to_string(),
            created_at: now_ts(),
            updated_at: now_ts(),
            change_group,
            status: BranchStatus::Active,
            template,
            worktree: None,
            branchless: false,
            depends_on,
            last_commit: None,
            tags,
            parent_branch: None,
            agent_id,
        };

        self.branches.insert(branch_name.to_string(), branch_info);
        Ok(())
    }

    /// Set worktree path for a branch
    pub async fn set_branch_worktree(&mut self, branch_name: &str, path: std::path::PathBuf) -> Result<()> {
        self.set_branch_worktree_no_save(branch_name, path).await?;
        self.save_branches().await
    }

    /// Set worktree path without saving to disk
    pub async fn set_branch_worktree_no_save(&mut self, branch_name: &str, path: std::path::PathBuf) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.worktree = Some(path);
            branch.updated_at = now_ts();
        }
        Ok(())
    }

    /// Set parent branch for a stacked operation
    pub async fn set_parent_branch(&mut self, branch_name: &str, parent: &str) -> Result<()> {
        self.set_parent_branch_no_save(branch_name, parent).await?;
        self.save_branches().await
    }

    /// Set parent branch without saving to disk
    pub async fn set_parent_branch_no_save(&mut self, branch_name: &str, parent: &str) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.parent_branch = Some(parent.to_string());
            branch.updated_at = now_ts();
        }
        Ok(())
    }

    /// Get parent branch for a stacked operation
    pub fn get_parent_branch(&self, branch_name: &str) -> Option<&str> {
        self.branches.get(branch_name)
            .and_then(|b| b.parent_branch.as_deref())
    }

    /// Clear worktree path for a branch
    pub async fn clear_branch_worktree(&mut self, branch_name: &str) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.worktree = None;
            branch.updated_at = now_ts();
            self.save_branches().await?;
        }
        Ok(())
    }

    /// Get branch information
    pub fn get_branch(&self, branch_name: &str) -> Option<&BranchInfo> {
        self.branches.get(branch_name)
    }

    /// List all branches
    pub fn list_branches(&self) -> Vec<&BranchInfo> {
        self.branches.values().collect()
    }

    /// List branches by status
    pub fn list_branches_by_status(&self, status: BranchStatus) -> Vec<&BranchInfo> {
        self.branches.values()
            .filter(|branch| branch.status == status)
            .collect()
    }

    /// List branches by agent ID
    pub fn list_branches_by_agent(&self, agent_id: &str) -> Vec<&BranchInfo> {
        self.branches.values()
            .filter(|b| b.agent_id.as_deref() == Some(agent_id))
            .collect()
    }

    /// List branches by tag
    pub fn list_branches_by_tag(&self, tag: &str) -> Vec<&BranchInfo> {
        self.branches.values()
            .filter(|branch| branch.tags.iter().any(|t| t == tag))
            .collect()
    }

    /// Add a tag to a branch
    pub async fn add_tag(&mut self, branch_name: &str, tag: &str) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name)
            && !branch.tags.iter().any(|t| t == tag)
        {
            branch.tags.push(tag.to_string());
            branch.updated_at = now_ts();
            self.save_branches().await?;
        }
        Ok(())
    }

    /// Remove a tag from a branch
    pub async fn remove_tag(&mut self, branch_name: &str, tag: &str) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.tags.retain(|t| t != tag);
            branch.updated_at = now_ts();
            self.save_branches().await?;
        }
        Ok(())
    }

    /// Mark branch as merged
    pub async fn mark_branch_merged(&mut self, branch_name: &str) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.status = BranchStatus::Merged;
            branch.updated_at = now_ts();
            
            self.save_branches().await?;
            info!("Branch '{}' marked as merged", branch_name);
        } else {
            bail!("Branch '{}' not found", branch_name);
        }
        
        Ok(())
    }

    /// Archive a branch (withdrawn or manually archived)
    pub async fn archive_branch(&mut self, branch_name: &str) -> Result<()> {
        if let Some(branch) = self.branches.get_mut(branch_name) {
            branch.status = BranchStatus::Archived;
            branch.updated_at = now_ts();
            self.save_branches().await?;
            info!("Branch '{}' archived", branch_name);
        } else {
            bail!("Branch '{}' not found", branch_name);
        }
        Ok(())
    }

    /// Archive old branches
    pub async fn archive_old_branches(&mut self, days_old: u32) -> Result<Vec<String>> {
        let cutoff = now_ts().saturating_sub(days_old as u64 * 86400);
        let mut archived = Vec::new();
        
        for (name, branch) in self.branches.iter_mut() {
            if branch.updated_at < cutoff &&
               matches!(branch.status, BranchStatus::Active | BranchStatus::Merged) {
                branch.status = BranchStatus::Archived;
                archived.push(name.clone());
            }
        }
        
        if !archived.is_empty() {
            self.save_branches().await?;
            info!("Archived {} old branches", archived.len());
        }
        
        Ok(archived)
    }

    /// Load branches from disk
    async fn load_branches(&mut self) -> Result<()> {
        if !self.data_file.exists() {
            return Ok(());
        }
        
        let content = fs::read_to_string(&self.data_file).await
            .context("Failed to read branches file")?;
        
        self.branches = serde_json::from_str(&content)
            .context("Failed to parse branches file")?;
        
        debug!("Loaded {} branches from disk", self.branches.len());
        Ok(())
    }

    /// Save branches to disk
    async fn save_branches(&self) -> Result<()> {
        // Ensure data directory exists
        if let Some(parent) = self.data_file.parent() {
            fs::create_dir_all(parent).await
                .context("Failed to create data directory")?;
        }
        
        let content = serde_json::to_string_pretty(&self.branches)
            .context("Failed to serialize branches")?;

        crate::atomic::write_atomic(&self.data_file, content.as_bytes())
            .context("Failed to write branches file")?;
        
        debug!("Saved {} branches to disk", self.branches.len());
        Ok(())
    }

    /// Clean up branches data file
    pub async fn cleanup(&self) -> Result<()> {
        if self.data_file.exists() {
            fs::remove_file(&self.data_file).await
                .context("Failed to remove branches file")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    async fn create_test_branch_manager() -> (BranchManager, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test_branches.json");
        let manager = BranchManager::new(db_path).await.unwrap();
        (manager, temp_dir)
    }

    #[tokio::test]
    async fn test_branch_manager_creation() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("branches.json");
        
        let branch_manager = BranchManager::new(db_path.clone()).await;
        assert!(branch_manager.is_ok());
        
        // Save to create the database file
        let branch_manager = branch_manager.unwrap();
        branch_manager.save().await.unwrap();
        
        // Check that the database file is created
        assert!(db_path.exists());
    }

    #[tokio::test]
    async fn test_branch_registration() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        let result = branch_manager.register_branch(
            "feature-test",
            vec!["src/main.rs".to_string()],
            "Test feature".to_string()
        ).await;
        assert!(result.is_ok());

        let branch_info = branch_manager.get_branch("feature-test").unwrap();
        assert_eq!(branch_info.name, "feature-test");
        assert_eq!(branch_info.status, BranchStatus::Active);
    }

    #[tokio::test]
    async fn test_branch_status_transitions() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        // Register branch
        branch_manager.register_branch(
            "feature-status",
            vec!["src/test.rs".to_string()],
            "Status test".to_string()
        ).await.unwrap();

        // Check initial status
        let info = branch_manager.get_branch("feature-status").unwrap();
        assert_eq!(info.status, BranchStatus::Active);

        // Mark as merged
        let result = branch_manager.mark_branch_merged("feature-status").await;
        assert!(result.is_ok());

        // Check updated status
        let info = branch_manager.get_branch("feature-status").unwrap();
        assert_eq!(info.status, BranchStatus::Merged);
    }

    #[tokio::test]
    async fn test_branch_listing() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        // Register multiple branches
        let branches = vec!["feature-1", "feature-2", "bugfix-1"];
        for branch_name in &branches {
            branch_manager.register_branch(
                branch_name,
                vec![format!("src/{}.rs", branch_name)],
                format!("{} branch", branch_name)
            ).await.unwrap();
        }
        
        // Test get_all_branches
        let all_branches = branch_manager.get_all_branches().await.unwrap();
        assert_eq!(all_branches.len(), 3);
        
        // Test list_branches_by_status
        let active_branches = branch_manager.list_branches_by_status(BranchStatus::Active);
        assert_eq!(active_branches.len(), 3);
        
        let merged_branches = branch_manager.list_branches_by_status(BranchStatus::Merged);
        assert_eq!(merged_branches.len(), 0);
    }

    #[tokio::test]
    async fn test_branch_cleanup() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        // Create old branch
        branch_manager.register_branch(
            "old-feature",
            vec!["src/old.rs".to_string()],
            "Old feature".to_string()
        ).await.unwrap();

        // Update the branch's updated_at to be old
        if let Some(branch) = branch_manager.branches.get_mut("old-feature") {
            branch.updated_at = now_ts() - 40 * 86400;
        }

        // Create recent branch
        branch_manager.register_branch(
            "recent-feature",
            vec!["src/recent.rs".to_string()],
            "Recent feature".to_string()
        ).await.unwrap();

        // Test cleanup
        let cleaned = branch_manager.archive_old_branches(30).await.unwrap();
        assert_eq!(cleaned.len(), 1);
        assert!(cleaned.contains(&"old-feature".to_string()));

        // Verify old branch is archived
        let old_info = branch_manager.get_branch("old-feature").unwrap();
        assert_eq!(old_info.status, BranchStatus::Archived);

        // Verify recent branch is still active
        let recent_info = branch_manager.get_branch("recent-feature").unwrap();
        assert_eq!(recent_info.status, BranchStatus::Active);
    }

    #[test]
    fn test_branch_status_enum() {
        let active_status = BranchStatus::Active;
        let merged_status = BranchStatus::Merged;

        assert_ne!(active_status, merged_status);
        assert_eq!(active_status, BranchStatus::Active);
    }

    #[tokio::test]
    async fn test_update_branch_status() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        branch_manager.register_branch(
            "feature-update",
            vec!["src/test.rs".to_string()],
            "Update test".to_string()
        ).await.unwrap();

        let result = branch_manager.update_branch_status("feature-update", BranchStatus::Merged).await;
        assert!(result.is_ok());

        let info = branch_manager.get_branch("feature-update").unwrap();
        assert_eq!(info.status, BranchStatus::Merged);
    }

    #[tokio::test]
    async fn test_update_branch_files() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        branch_manager.register_branch(
            "feature-files",
            vec!["src/a.rs".to_string()],
            "Files test".to_string()
        ).await.unwrap();

        let new_files = vec!["src/a.rs".to_string(), "src/b.rs".to_string()];
        let result = branch_manager.update_branch_files("feature-files", &new_files).await;
        assert!(result.is_ok());

        let info = branch_manager.get_branch("feature-files").unwrap();
        assert_eq!(info.change_group.files, new_files);
    }

    #[tokio::test]
    async fn test_remove_branch() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        branch_manager.register_branch(
            "feature-remove",
            vec!["src/test.rs".to_string()],
            "Remove test".to_string()
        ).await.unwrap();

        assert!(branch_manager.get_branch("feature-remove").is_some());

        let result = branch_manager.remove_branch("feature-remove").await;
        assert!(result.is_ok());

        assert!(branch_manager.get_branch("feature-remove").is_none());
    }

    #[tokio::test]
    async fn test_remove_nonexistent_branch() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        let result = branch_manager.remove_branch("nonexistent").await;
        assert!(result.is_ok()); // Removing non-existent branch succeeds silently
    }

    #[tokio::test]
    async fn test_get_all_branches_empty() {
        let (branch_manager, _temp_dir) = create_test_branch_manager().await;

        let branches = branch_manager.get_all_branches().await.unwrap();
        assert!(branches.is_empty());
    }

    #[tokio::test]
    async fn test_branchless_bookmark() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        branch_manager.register_branch(
            "bookmark-1",
            vec!["src/main.rs".to_string()],
            "Branchless test".to_string()
        ).await.unwrap();

        // Initially not branchless
        let info = branch_manager.get_branch("bookmark-1").unwrap();
        assert!(!info.branchless);

        // Set branchless
        if let Some(branch) = branch_manager.branches.get_mut("bookmark-1") {
            branch.branchless = true;
            branch_manager.save().await.unwrap();
        }

        let info = branch_manager.get_branch("bookmark-1").unwrap();
        assert!(info.branchless);
    }

    #[tokio::test]
    async fn test_cleanup_no_old_branches() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        branch_manager.register_branch(
            "recent",
            vec!["src/test.rs".to_string()],
            "Recent branch".to_string()
        ).await.unwrap();

        let cleaned = branch_manager.archive_old_branches(30).await.unwrap();
        assert!(cleaned.is_empty());

        let info = branch_manager.get_branch("recent").unwrap();
        assert_eq!(info.status, BranchStatus::Active);
    }

    #[tokio::test]
    async fn test_load_and_save_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("branches.json");

        // Create and populate manager
        let mut manager = BranchManager::new(db_path.clone()).await.unwrap();
        manager.register_branch("persist-test", vec!["src/main.rs".to_string()], "Test".to_string()).await.unwrap();
        manager.save().await.unwrap();

        // Load from same path by creating a new manager
        let loaded_manager = BranchManager::new(db_path).await.unwrap();
        let branch = loaded_manager.get_branch("persist-test").unwrap();
        assert_eq!(branch.name, "persist-test");
        assert_eq!(branch.status, BranchStatus::Active);
    }

    #[tokio::test]
    async fn test_load_nonexistent_file_creates_empty() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("nonexistent.json");

        let manager = BranchManager::new(db_path).await.unwrap();
        let branches = manager.get_all_branches().await.unwrap();
        assert!(branches.is_empty());
    }

    #[tokio::test]
    async fn test_tags_add_remove_list() {
        let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;

        branch_manager.register_branch_full(
            "tagged-op",
            vec!["src/main.rs".to_string()],
            "Tagged operation".to_string(),
            Vec::new(),
            None,
            vec!["sprint-42".to_string(), "bugfix-week".to_string()],
            None,
        ).await.unwrap();

        let info = branch_manager.get_branch("tagged-op").unwrap();
        assert_eq!(info.tags.len(), 2);
        assert!(info.tags.contains(&"sprint-42".to_string()));

        // List by tag
        let sprint_branches = branch_manager.list_branches_by_tag("sprint-42");
        assert_eq!(sprint_branches.len(), 1);

        let bugfix_branches = branch_manager.list_branches_by_tag("bugfix-week");
        assert_eq!(bugfix_branches.len(), 1);

        let none_branches = branch_manager.list_branches_by_tag("nonexistent");
        assert_eq!(none_branches.len(), 0);

        // Remove a tag
        branch_manager.remove_tag("tagged-op", "bugfix-week").await.unwrap();
        let info = branch_manager.get_branch("tagged-op").unwrap();
        assert_eq!(info.tags.len(), 1);
        assert!(!info.tags.contains(&"bugfix-week".to_string()));

        // Add a tag
        branch_manager.add_tag("tagged-op", "hotfix").await.unwrap();
        let info = branch_manager.get_branch("tagged-op").unwrap();
        assert!(info.tags.contains(&"hotfix".to_string()));

        // Adding duplicate tag should not duplicate
        branch_manager.add_tag("tagged-op", "hotfix").await.unwrap();
        let info = branch_manager.get_branch("tagged-op").unwrap();
        assert_eq!(info.tags.iter().filter(|t| *t == "hotfix").count(), 1);
    }
}