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

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

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

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

    // Create first operation (foundation)
    commands::start_command(
        "Refactor auth".to_string(),
        true, false, false,
        None, None, None, None,
        None, false).await?;
    let branches = git_manager.list_branches()?;
    let auth_branch = branches.iter()
        .find(|b| b.name.starts_with("codetree_"))
        .map(|b| b.name.clone())
        .unwrap();

    // Create second operation that depends on the first
    commands::start_command(
        "Add OAuth".to_string(),
        true, false, false,
        None,
        Some(vec![auth_branch.clone()]),
        None,
        None,
        None,
        false,
    ).await?;
    let branches = git_manager.list_branches()?;
    let oauth_branch = branches.iter()
        .filter(|b| b.name.starts_with("codetree_"))
        .find(|b| b.name != auth_branch)
        .map(|b| b.name.clone())
        .unwrap();

    // Try to finish the OAuth branch before auth branch is finished — should fail
    let result = commands::finish_command(Some(oauth_branch.clone()), None, false).await;
    assert!(result.is_err(), "Should not be able to finish OAuth before auth is finished");

    // Finish the auth branch first
    commands::finish_command(Some(auth_branch.clone()), None, false).await?;

    // Now OAuth can be finished
    commands::finish_command(Some(oauth_branch.clone()), None, false).await?;

    Ok(())
}

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

    commands::init_command(false).await?;

    // Start an operation with --files — should acquire locks
    commands::start_command(
        "lock test".to_string(),
        true, true, false,
        Some(vec!["src/a.rs".to_string(), "src/b.rs".to_string()]),
        None, None, None,
        None,
        false,
    ).await?;

    // Verify locks file exists and contains the expected entries
    let locks_path = repo_path.join(".codetree").join("locks.json");
    assert!(locks_path.exists(), "locks.json should exist after start --files");

    let lock_manager = codetree::lock::LockManager::load(locks_path)?;
    assert!(lock_manager.is_locked("src/a.rs"));
    assert!(lock_manager.is_locked("src/b.rs"));

    // Start a second operation trying to lock the same file — should fail
    let result = commands::start_command(
        "conflict test".to_string(),
        true, true, false,
        Some(vec!["src/a.rs".to_string()]),
        None, None, None,
        None,
        false,
    ).await;

    assert!(result.is_err(), "Should not be able to lock an already-locked file");

    Ok(())
}

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

    commands::init_command(false).await?;

    // Start with files
    commands::start_command(
        "lock release test".to_string(),
        true, true, false,
        Some(vec!["src/c.rs".to_string()]),
        None, None, None,
        None,
        false,
    ).await?;

    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let branch_name = branch_manager.list_branches()
        .into_iter()
        .find(|b| matches!(b.status, BranchStatus::Active))
        .map(|b| b.name.clone())
        .unwrap();

    // Withdraw the operation
    commands::withdraw_command(Some(branch_name.clone()), None).await?;

    // Verify lock is released
    let locks_path = repo_path.join(".codetree").join("locks.json");
    let lock_manager = codetree::lock::LockManager::load(locks_path)?;
    assert!(!lock_manager.is_locked("src/c.rs"), "Lock should be released after withdraw");

    Ok(())
}

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

    // Freeze a file
    let frozen_path = repo_path.join(".codetree").join("frozen.json");
    let mut frozen = codetree::freeze::FrozenPaths::new(frozen_path.clone());
    frozen.freeze("src/protected.rs");
    frozen.save()?;

    // Start an operation and try to save the frozen file
    commands::start_command(
        "freeze test".to_string(),
        false, false, false,
        Some(vec!["src/protected.rs".to_string()]),
        None, None, None,
        None,
        false,
    ).await?;

    // Create the file on disk
    std::fs::create_dir_all(repo_path.join("src"))?;
    std::fs::write(repo_path.join("src/protected.rs"), "content")?;

    // Attempt to save — should be rejected because the file is frozen
    let result = commands::save_command(vec!["modify protected".to_string()], false, false, None).await;
    assert!(result.is_err(), "Save should be rejected for frozen files");
    let err_msg = result.unwrap_err().to_string();
    assert!(err_msg.contains("frozen"), "Error should mention frozen: {}", err_msg);

    Ok(())
}

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

    // Freeze then unfreeze
    let frozen_path = repo_path.join(".codetree").join("frozen.json");
    let mut frozen = codetree::freeze::FrozenPaths::new(frozen_path);
    frozen.freeze("src/unfrozen.rs");
    frozen.save()?;
    frozen.unfreeze("src/unfrozen.rs");
    frozen.save()?;

    // Verify unfrozen
    let loaded = codetree::freeze::FrozenPaths::load(repo_path.join(".codetree").join("frozen.json"))?;
    assert!(!loaded.is_frozen("src/unfrozen.rs"));

    Ok(())
}

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

    // Create a candidate group with two operations
    let candidates_path = repo_path.join(".codetree").join("candidates.json");
    let mut cand_mgr = codetree::candidates::CandidateManager::new(candidates_path.clone());

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

    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let active_ops: Vec<_> = branch_manager.list_branches()
        .into_iter()
        .filter(|b| matches!(b.status, BranchStatus::Active))
        .collect();
    assert_eq!(active_ops.len(), 2);

    // Add both to a candidate group
    cand_mgr.add_candidate("auth-fix", &active_ops[0].name)?;
    cand_mgr.add_candidate("auth-fix", &active_ops[1].name)?;
    cand_mgr.save()?;

    // Verify group
    let loaded = codetree::candidates::CandidateManager::load(candidates_path)?;
    assert_eq!(loaded.get_group("auth-fix").unwrap().len(), 2);
    assert!(loaded.is_candidate("auth-fix", &active_ops[0].name));
    assert!(loaded.is_candidate("auth-fix", &active_ops[1].name));

    // Evaluate the group (should not error)
    commands::evaluate_command("auth-fix".to_string()).await?;

    Ok(())
}

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

    // Freeze a file
    commands::freeze_command("src/important.rs".to_string()).await?;

    // Verify it's frozen
    let frozen = codetree::freeze::FrozenPaths::load(
        repo_path.join(".codetree").join("frozen.json")
    )?;
    assert!(frozen.is_frozen("src/important.rs"));

    // List frozen
    commands::frozen_command().await?;

    // Unfreeze
    commands::unfreeze_command("src/important.rs".to_string(), true).await?;

    let frozen = codetree::freeze::FrozenPaths::load(
        repo_path.join(".codetree").join("frozen.json")
    )?;
    assert!(!frozen.is_frozen("src/important.rs"));

    Ok(())
}

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

    commands::init_command(false).await?;

    // Start with files
    commands::start_command(
        "locks list test".to_string(),
        true, true, false,
        Some(vec!["src/x.rs".to_string(), "src/y.rs".to_string()]),
        None, None, None,
        None,
        false,
    ).await?;

    // List locks — should not error
    commands::locks_command().await?;

    // Verify locks exist
    let lock_manager = codetree::lock::LockManager::load(
        repo_path.join(".codetree").join("locks.json")
    )?;
    let locks = lock_manager.list_locks();
    assert!(locks.iter().any(|(p, _)| p == "src/x.rs"));
    assert!(locks.iter().any(|(p, _)| p == "src/y.rs"));

    Ok(())
}

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

    // Configure validation with a command that always succeeds
    let config_path = repo_path.join(".codetree").join("config.toml");
    let mut config = Config::load(&config_path).await?;
    config.validation.mode = "required".to_string();
    config.validation.command = Some("true".to_string());
    config.save(&config_path).await?;

    // Start an operation and make a change
    commands::start_command("validation test".to_string(), true, true, false, None, None, None, None, None, false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_manager = BranchManager::new(repo_path.join(".codetree").join("branches.json")).await?;
    let op_branch = branch_manager.list_branches()
        .into_iter()
        .find(|b| b.name.contains("validation_test"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&op_branch).await?;
    tokio::fs::write(repo_path.join("test.rs"), "fn test() {}\n").await?;

    // Save with validation — should succeed since command is "true"
    let result = commands::save_command(vec![], false, false, None).await;
    assert!(result.is_ok(), "Save with passing validation should succeed: {:?}", result.err());

    Ok(())
}

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

    // Configure validation with a command that always fails
    let config_path = repo_path.join(".codetree").join("config.toml");
    let mut config = Config::load(&config_path).await?;
    config.validation.mode = "required".to_string();
    config.validation.command = Some("false".to_string());
    config.save(&config_path).await?;

    // Start an operation and make a change
    commands::start_command("validation fail test".to_string(), true, true, false, None, None, None, None, None, false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_manager = BranchManager::new(repo_path.join(".codetree").join("branches.json")).await?;
    let op_branch = branch_manager.list_branches()
        .into_iter()
        .find(|b| b.name.contains("validation_fail_test"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&op_branch).await?;
    tokio::fs::write(repo_path.join("test.rs"), "fn test() {}\n").await?;

    // Save with validation — should fail since command is "false"
    let result = commands::save_command(vec![], false, false, None).await;
    assert!(result.is_err(), "Save with failing validation should be blocked");
    let err_msg = result.unwrap_err().to_string();
    assert!(err_msg.contains("Validation failed"), "Error should mention validation failure: {}", err_msg);

    Ok(())
}

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

    // Configure validation with a command that always fails
    let config_path = repo_path.join(".codetree").join("config.toml");
    let mut config = Config::load(&config_path).await?;
    config.validation.mode = "required".to_string();
    config.validation.command = Some("false".to_string());
    config.save(&config_path).await?;

    // Start an operation and make a change
    commands::start_command("validation skip test".to_string(), true, true, false, None, None, None, None, None, false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_manager = BranchManager::new(repo_path.join(".codetree").join("branches.json")).await?;
    let op_branch = branch_manager.list_branches()
        .into_iter()
        .find(|b| b.name.contains("validation_skip_test"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&op_branch).await?;
    tokio::fs::write(repo_path.join("test.rs"), "fn test() {}\n").await?;

    // Save with --no-validate — should succeed even though validation would fail
    let result = commands::save_command(vec![], false, true, None).await;
    assert!(result.is_ok(), "Save with --no-validate should skip validation: {:?}", result.err());

    Ok(())
}

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

    // Default config should have validation off
    let config_path = repo_path.join(".codetree").join("config.toml");
    let config = Config::load(&config_path).await?;
    assert!(config.validation.is_off(), "Validation should be off by default");

    // Start an operation and make a change
    commands::start_command("no validation test".to_string(), true, true, false, None, None, None, None, None, false).await?;
    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_manager = BranchManager::new(repo_path.join(".codetree").join("branches.json")).await?;
    let op_branch = branch_manager.list_branches()
        .into_iter()
        .find(|b| b.name.contains("no_validation_test"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&op_branch).await?;
    tokio::fs::write(repo_path.join("test.rs"), "fn test() {}\n").await?;

    // Save without validation flags — should succeed (no validation configured)
    let result = commands::save_command(vec![], false, false, None).await;
    assert!(result.is_ok(), "Save with no validation should succeed: {:?}", result.err());

    Ok(())
}

#[tokio::test]
async fn test_agent_id_tracking() -> 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 operations with different agent IDs
    commands::start_command("agent A task".to_string(), true, false, false, None, None, None, None, Some("agent-A".to_string()), false).await?;
    commands::start_command("agent B task".to_string(), true, false, false, None, None, None, None, Some("agent-B".to_string()), false).await?;
    commands::start_command("agent A task 2".to_string(), true, false, false, None, None, None, None, Some("agent-A".to_string()), false).await?;

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

    // Verify agent_id is stored
    let agent_a_ops = branch_manager.list_branches_by_agent("agent-A");
    assert_eq!(agent_a_ops.len(), 2, "Agent A should have 2 operations");

    let agent_b_ops = branch_manager.list_branches_by_agent("agent-B");
    assert_eq!(agent_b_ops.len(), 1, "Agent B should have 1 operation");

    // Verify no unassigned ops
    let all_branches = branch_manager.list_branches();
    for b in all_branches {
        if matches!(b.status, BranchStatus::Active) {
            assert!(b.agent_id.is_some(), "All active branches should have agent_id");
        }
    }

    // agents_command should run without error
    commands::agents_command().await?;

    Ok(())
}

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

    commands::init_command(false).await?;

    // Start with a specific agent ID
    commands::start_command("tracked op".to_string(), true, false, false, None, None, None, None, Some("test-agent-42".to_string()), false).await?;

    // Verify ops.json contains the agent_id
    let ops_path = repo_path.join(".codetree").join("ops.json");
    let ops_content = std::fs::read_to_string(&ops_path)?;
    assert!(ops_content.contains("test-agent-42"), "ops.json should contain agent_id: {}", ops_content);

    Ok(())
}

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

    commands::init_command(false).await?;

    // Start with files (locks them)
    commands::start_command(
        "lock finish test".to_string(),
        true, true, false,
        Some(vec!["src/fin.rs".to_string()]),
        None, None, None,
        None, false,
    ).await?;

    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let branch_name = branch_manager.list_branches()
        .into_iter()
        .find(|b| matches!(b.status, BranchStatus::Active))
        .map(|b| b.name.clone())
        .unwrap();

    // Add a commit so finish can merge
    let git_manager = VcsManager::new(repo_path.clone())?;
    git_manager.checkout_branch(&branch_name).await?;
    tokio::fs::create_dir_all(repo_path.join("src")).await?;
    tokio::fs::write(repo_path.join("src/fin.rs"), "// fin\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("Lock finish commit").await?;

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

    // Verify lock is released
    let locks_path = repo_path.join(".codetree").join("locks.json");
    let lock_manager = codetree::lock::LockManager::load(locks_path)?;
    assert!(!lock_manager.is_locked("src/fin.rs"), "Lock should be released after finish");

    Ok(())
}

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

    commands::init_command(false).await?;

    // Start with files
    commands::start_command(
        "unlock test".to_string(),
        true, true, false,
        Some(vec!["src/unlock.rs".to_string()]),
        None, None, None,
        None, false,
    ).await?;

    // Verify locked
    let locks_path = repo_path.join(".codetree").join("locks.json");
    let lock_manager = codetree::lock::LockManager::load(locks_path.clone())?;
    assert!(lock_manager.is_locked("src/unlock.rs"));

    // Manually unlock
    commands::unlock_command("src/unlock.rs".to_string()).await?;

    // Verify unlocked
    let lock_manager = codetree::lock::LockManager::load(locks_path)?;
    assert!(!lock_manager.is_locked("src/unlock.rs"), "unlock_command should release the lock");

    Ok(())
}

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

    // Op A locks src/shared.rs
    commands::start_command(
        "Lock owner".to_string(),
        true, true, false,
        Some(vec!["src/shared.rs".to_string()]),
        None, None, None,
        None, false,
    ).await?;

    // Op B — no files assigned, but tries to save src/shared.rs
    commands::start_command(
        "Lock violator".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()?;

    // Checkout the violator branch
    let violator_branch = branches.iter()
        .find(|b| b.name.contains("lock_violator"))
        .map(|b| b.name.clone())
        .unwrap();
    git_manager.checkout_branch(&violator_branch).await?;

    // Create the locked file and try to save
    tokio::fs::create_dir_all(repo_path.join("src")).await?;
    tokio::fs::write(repo_path.join("src/shared.rs"), "// violator\n").await?;

    let result = commands::save_command(vec!["violate lock".to_string()], false, false, None).await;
    assert!(result.is_err(), "Save should be rejected when touching a file locked by another op");

    Ok(())
}

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

    commands::init_command(false).await?;

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

    let git_manager = VcsManager::new(repo_path.clone())?;
    let branch_manager = BranchManager::new(
        repo_path.join(".codetree").join("branches.json")
    ).await?;
    let active_ops: Vec<_> = branch_manager.list_branches()
        .into_iter()
        .filter(|b| matches!(b.status, BranchStatus::Active))
        .collect();
    assert_eq!(active_ops.len(), 2);

    // Add both to a candidate group
    let candidates_path = repo_path.join(".codetree").join("candidates.json");
    let mut cand_mgr = codetree::candidates::CandidateManager::new(candidates_path.clone());
    cand_mgr.add_candidate("auth-fix", &active_ops[0].name)?;
    cand_mgr.add_candidate("auth-fix", &active_ops[1].name)?;
    cand_mgr.save()?;

    // Add a commit to the winner so merge has content
    let winner = &active_ops[0].name;
    git_manager.checkout_branch(winner).await?;
    tokio::fs::write(repo_path.join("solution.rs"), "// winning solution\n").await?;
    git_manager.add_all().await?;
    git_manager.commit("Winning solution").await?;

    // Promote the winner
    commands::promote_command("auth-fix".to_string(), winner.clone()).await?;

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

    // Verify loser is archived
    let loser = &active_ops[1].name;
    let loser_info = branch_manager.get_branch(loser).unwrap();
    assert_eq!(loser_info.status, BranchStatus::Archived);

    // Verify candidate group is cleaned up
    let loaded_cands = codetree::candidates::CandidateManager::load(candidates_path)?;
    assert!(loaded_cands.get_group("auth-fix").is_none(), "Candidate group should be deleted after promote");

    Ok(())
}

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

    // Freeze a directory
    commands::freeze_command("src/protected/".to_string()).await?;

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

    // Create a file under the frozen directory
    std::fs::create_dir_all(repo_path.join("src/protected"))?;
    std::fs::write(repo_path.join("src/protected/file.rs"), "content")?;

    // Save should be rejected
    let result = commands::save_command(vec!["modify frozen dir".to_string()], false, false, None).await;
    assert!(result.is_err(), "Save should be rejected for files under a frozen directory");

    Ok(())
}

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

    // Configure validation with a failing command
    let config_path = repo_path.join(".codetree").join("config.toml");
    let mut config = Config::load(&config_path).await?;
    config.validation.mode = "off".to_string();
    config.validation.command = Some("false".to_string());
    config.save(&config_path).await?;

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

    tokio::fs::write(repo_path.join("validate_test.rs"), "// test\n").await?;

    // Save with --validate should fail (command is "false")
    let result = commands::save_command(vec![], true, false, None).await;
    assert!(result.is_err(), "Save with --validate and failing command should be blocked");

    Ok(())
}

/// Two agents starting operations with disjoint files concurrently must both
/// succeed and both locks must survive in locks.json. With the old
/// load→modify→save pattern this race silently dropped one agent's lock
/// (last-writer-wins); `LockManager::update_atomically` serializes the cycle.
#[tokio::test]
async fn test_concurrent_starts_disjoint_files_both_locks_survive() -> 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 mut handles = Vec::new();
    for (desc, file) in [("Concurrent Op A", "a_shared.rs"), ("Concurrent Op B", "b_shared.rs")] {
        let files = vec![file.to_string()];
        handles.push(tokio::spawn(async move {
            commands::start_command(
                desc.to_string(), true, false, false, Some(files),
                None, None, None, None, false,
            ).await
        }));
    }
    let mut results = Vec::new();
    for h in handles {
        results.push(h.await.unwrap());
    }
    assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 2,
        "both agents should acquire their disjoint locks: {:?}",
        results.iter().map(|r| r.as_ref().err().map(|e| e.to_string())).collect::<Vec<_>>());

    // Both locks must be present — neither agent's update was lost.
    let locks = codetree::lock::LockManager::load(repo_path.join(".codetree").join("locks.json"))?;
    let entries = locks.list_locks();
    assert_eq!(entries.len(), 2);
    let files: std::collections::HashSet<_> = entries.iter().map(|(f, _)| f.clone()).collect();
    assert!(files.contains("a_shared.rs") && files.contains("b_shared.rs"));

    Ok(())
}

/// A file locked by operation A must block operation B's start (atomic
/// acquire path returns the conflict), and releasing it via the unlock path
/// must let B proceed. Exercises the lockfile-serialized RMW wiring end to end.
#[tokio::test]
async fn test_lock_conflict_then_release_via_atomic_rmw() -> 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 files = vec!["contested.rs".to_string()];

    // Agent A acquires the lock.
    commands::start_command(
        "Holder Op".to_string(), true, false, false, Some(files.clone()),
        None, None, None, None, false,
    ).await?;

    // Agent B must be rejected with a conflict naming the holder.
    let err = commands::start_command(
        "Conflicting Op".to_string(), true, false, false, Some(files.clone()),
        None, None, None, None, false,
    ).await.unwrap_err();
    assert!(err.to_string().contains("locked by operation"),
        "unexpected error: {}", err);

    // Release A's lock through the atomic path.
    commands::unlock_command("contested.rs".to_string()).await?;

    // Agent B now succeeds.
    commands::start_command(
        "Conflicting Op".to_string(), true, false, false, Some(files.clone()),
        None, None, None, None, false,
    ).await?;

    let locks = codetree::lock::LockManager::load(repo_path.join(".codetree").join("locks.json"))?;
    assert_eq!(locks.lock_holder("contested.rs").map(|s| s.to_string()).unwrap(),
        locks.list_locks().iter().find(|(f, _)| f == "contested.rs").unwrap().1.clone());

    Ok(())
}

/// The atomic write path must leave no staging/lock litter in refs/heads, and
/// branch listings must ignore any litter produced by crashed writers.
#[tokio::test]
async fn test_ref_writes_atomic_and_listings_clean() -> Result<()> {
    let (_temp_dir, repo_path) = create_test_repo().await?;
    let mgr = VcsManager::new(repo_path.clone())?;
    let refs = mgr.repo().refs();

    for i in 0..5 {
        refs.set_branch(&format!("branch-{}", i), &format!("commit-{}", i))?;
        refs.set_head("main")?;
    }

    let heads_dir = repo_path.join(".codetree").join("refs").join("heads");
    let listing: Vec<_> = std::fs::read_dir(&heads_dir)?
        .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
        .collect();
    for name in &listing {
        assert!(!name.ends_with(".lock") && !name.starts_with('.'),
            "atomic-write litter leaked into refs listing: {}", name);
    }
    assert!(listing.iter().any(|n| n == "main"));

    Ok(())
}