codetree 0.2.0

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
use crate::error::{Context, Result};

use crate::branch::{BranchManager, BranchStatus};
use crate::freeze::FrozenPaths;
use crate::vcs::VcsManager;
use crate::lock::LockManager;
use crate::ops::{Operation, OperationLog};

use super::{load_config, run_hooks, clear_snapshots, auto_snapshot};

pub async fn save_command(messages: Vec<String>, validate: bool, no_validate: bool, prompt: Option<String>) -> Result<()> {
    let config = load_config(None).await?;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let mut git_manager = VcsManager::new(current_dir.clone())?;
    git_manager.set_max_file_size(config.git.max_file_size);
    let mut branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let current_branch = git_manager.get_current_branch().await?;
    let git_status = git_manager.get_status().await?;

    let all_changed: Vec<String> = git_status.modified.into_iter()
        .chain(git_status.untracked)
        .chain(git_status.staged)
        .collect();

    if all_changed.is_empty() {
        println!("No changes to save");
        return Ok(());
    }

    let is_tracked = branch_manager.get_branch(&current_branch).is_some();
    let branchless_bookmarks: Vec<_> = branch_manager.list_branches()
        .into_iter()
        .filter(|b| b.branchless && matches!(b.status, BranchStatus::Active))
        .collect();
    let in_branchless_mode = !is_tracked && !branchless_bookmarks.is_empty();

    let bookmark_name = if in_branchless_mode {
        if branchless_bookmarks.len() == 1 {
            branchless_bookmarks[0].name.clone()
        } else {
            let names: Vec<_> = branchless_bookmarks.iter().map(|b| b.name.clone()).collect();
            return Err(format!(
                "Multiple active branchless bookmarks on '{}': {}. Use `codetree switch <bookmark>` first.",
                current_branch, names.join(", ")
            ).into());
        }
    } else {
        current_branch.clone()
    };

    let frozen_path = current_dir.join(".codetree").join("frozen.json");
    let frozen = FrozenPaths::load(frozen_path)?;
    if let Some(frozen_file) = frozen.check_paths(&all_changed) {
        return Err(format!(
            "Cannot save: file '{}' is frozen. Use `codetree unfreeze '{}'` to allow changes.",
            frozen_file, frozen_file
        ).into());
    }

    let locks_path = current_dir.join(".codetree").join("locks.json");
    let lock_manager = LockManager::load(locks_path)?;
    for file in &all_changed {
        if lock_manager.is_locked_by_other(file, &bookmark_name) {
            let holder = lock_manager.lock_holder(file).unwrap_or("unknown");
            return Err(format!(
                "Cannot save: file '{}' is locked by operation '{}'. Wait for it to finish or use `codetree unlock '{}'`.",
                file, holder, file
            ).into());
        }
    }

    let should_validate = !no_validate && (validate || config.validation.is_required());

    if should_validate {
        if let Some(cmd) = &config.validation.command {
            info!("Running validation: {}", cmd);
            let output = tokio::process::Command::new("sh")
                .arg("-c")
                .arg(cmd)
                .current_dir(&current_dir)
                .output()
                .await
                .context("Failed to run validation command")?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                let stdout = String::from_utf8_lossy(&output.stdout);
                return Err(format!(
                    "Validation failed (exit code {}). Aborting save.\n--- stdout ---\n{}\n--- stderr ---\n{}",
                    output.status.code().unwrap_or(-1),
                    stdout.trim(),
                    stderr.trim()
                ).into());
            }
            info!("Validation passed");
        } else {
            if config.validation.is_required() {
                return Err("Validation is required but no validation command is configured. Set [validation] command in config.toml.".into());
            }
            if validate {
                return Err("--validate flag used but no validation command is configured. Set [validation] command in config.toml.".into());
            }
        }
    }

    run_hooks(&config, "pre_save", &current_dir).await?;

    let scoped_files = branch_manager.get_branch(&bookmark_name)
        .map(|b| b.change_group.files.clone())
        .filter(|f| !f.is_empty());

    let commit_message = if !messages.is_empty() {
        // Multiple -m flags combine as "title\n\nbody" (Sapling-style).
        if messages.len() == 1 {
            messages[0].clone()
        } else {
            let title = &messages[0];
            let body = &messages[1..].join("\n");
            format!("{}\n\n{}", title, body)
        }
    } else {
        let summary = if all_changed.len() == 1 {
            all_changed[0].clone()
        } else if all_changed.len() <= 4 {
            all_changed.join(", ")
        } else {
            format!("{} files", all_changed.len())
        };

        if let Some(branch) = branch_manager.get_branch(&bookmark_name) {
            if let Some(template_name) = &branch.template {
                if let Some(tmpl) = 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)
        }
    };

    if let Some(files) = scoped_files {
        let changed_assigned: Vec<String> = all_changed.iter()
            .filter(|f| files.contains(*f))
            .cloned()
            .collect();
        if changed_assigned.is_empty() {
            println!("No changes in assigned files to save");
            return Ok(());
        }
        git_manager.add_files(&changed_assigned).await
            .context("Failed to stage assigned files")?;
    } else {
        git_manager.add_all().await
            .context("Failed to stage changes")?;
    }

    let commit_hash = if in_branchless_mode {
        let bookmark = branch_manager.get_branch(&bookmark_name).unwrap();
        let should_amend = bookmark.last_commit.as_ref().and_then(|last| {
            let head = git_manager.get_commit_history(&current_branch, 1).ok()?;
            head.first().map(|h| h.hash == *last)
        }).unwrap_or(false);

        if should_amend {
            info!("Absorbing changes into branchless bookmark '{}'", bookmark_name);
            let hash = git_manager.amend_commit().await
                .context("Failed to amend commit for branchless absorb")?;
            println!("Absorbed changes into '{}' (amended)", bookmark_name);
            hash
        } else {
            info!("Creating new commit for branchless bookmark '{}'", bookmark_name);
            let hash = git_manager.commit(&commit_message).await
                .context("Failed to commit changes")?;
            println!("Saved changes to '{}' (new commit)", bookmark_name);
            hash
        }
    } else {
        let hash = git_manager.commit(&commit_message).await
            .context("Failed to commit changes")?;
        println!("Saved changes to branch '{}'", bookmark_name);
        hash
    };

    if in_branchless_mode {
        branch_manager.set_branch_last_commit(&bookmark_name, &commit_hash).await?;
    }

    if !all_changed.is_empty() {
        branch_manager.update_branch_files(&bookmark_name, &all_changed).await?;
    }

    let ops_path = current_dir.join(".codetree").join("ops.json");
    let mut op_log = OperationLog::new(&ops_path).await?;
    op_log.push(Operation::Save {
        branch: bookmark_name.clone(),
        message: commit_message.clone(),
        timestamp: crate::branch::now_ts(),
    });
    op_log.save(&ops_path).await?;

    // Provenance sidecar: map commit → operation/agent/prompt for `codetree why`.
    // Stored outside the hashed commit object — SHA-1 is the Git-compat contract.
    let agent_id = branch_manager.get_branch(&bookmark_name)
        .and_then(|b| b.agent_id.clone());
    let mut provenance = crate::provenance::ProvenanceLog::load(&current_dir)?;
    provenance.record(&commit_hash, &bookmark_name, agent_id, prompt);
    provenance.save(&current_dir)?;

    println!("Message: {}", commit_message);

    // The real commit supersedes any pending auto-snapshots.
    clear_snapshots().await;

    run_hooks(&config, "post_save", &current_dir).await?;

    Ok(())
}

/// Absorb uncommitted changes into the best-matching commit in the branch
/// history (Sapling-style). Figures out which commit to amend based on file
/// overlap, then rebuilds descendants.
///
/// With `route`, changes are instead routed back to the operations that own
/// them after a `codetree megamerge` (TODO Round 13: hunk-routing absorb).
pub async fn absorb_command(route: bool) -> Result<()> {
    if route {
        let current_dir = std::env::current_dir()
            .context("Failed to get current directory")?;
        let git_manager = VcsManager::new(current_dir.clone())?;
        let mut branch_manager = BranchManager::new(
            current_dir.join(".codetree").join("branches.json")
        ).await?;

        let report = super::megamerge::route_changes(&git_manager, &mut branch_manager).await?;
        if report.routed.is_empty() {
            println!("No changes to route");
        }
        for change in &report.routed {
            println!("Routed {} hunk(s) in {} → {}",
                change.hunks, change.file, change.operation);
        }
        for item in &report.unrouted {
            println!("Unrouted {}", item);
        }
        if !report.operations.is_empty() {
            println!("Updated operation(s): {}", report.operations.join(", "));
        }
        return Ok(());
    }

    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let result = git_manager.absorb().await?;

    let target_short = &result.target_commit[..7.min(result.target_commit.len())];
    let head_short = &result.new_head[..7.min(result.new_head.len())];

    if result.was_head {
        println!("Absorbed {} file(s) into HEAD (amended)", result.absorbed_files.len());
    } else {
        println!("Absorbed {} file(s) into commit {}", result.absorbed_files.len(), target_short);
        println!("Rebuilt descendants → new HEAD: {}", head_short);
    }
    for file in &result.absorbed_files {
        println!("  - {}", file);
    }

    Ok(())
}

/// Rewrite a commit's message. Rebuilds descendants on the current branch.
pub async fn reword_command(commit: String, message: String, dry_run: bool) -> Result<()> {
    if !dry_run {
        auto_snapshot().await;
    }
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    if dry_run {
        let repo = git_manager.repo();
        let head_id = repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let target_id = git_manager.resolve_commit_pub(&commit, &head_id)?;
        let target_commit = repo.read_commit(&target_id)?;
        println!("Dry run: would reword commit '{}' ({})",
            commit,
            target_commit.message.lines().next().unwrap_or(""));
        println!("  New message: \"{}\"", message);
        println!("  Descendants would be rebuilt.");
        return Ok(());
    }

    let new_head = git_manager.reword(&commit, &message).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Rewrote message on commit '{}'", commit);
    println!("New message: {}", message);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Squash a commit into its parent. Combines both messages and trees.
pub async fn squash_command(commit: String, dry_run: bool) -> Result<()> {
    if !dry_run {
        auto_snapshot().await;
    }
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    if dry_run {
        let repo = git_manager.repo();
        let head_id = repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let target_id = git_manager.resolve_commit_pub(&commit, &head_id)?;
        let target_commit = repo.read_commit(&target_id)?;
        let parent_msg = if !target_commit.parents.is_empty() {
            repo.read_commit(&target_commit.parents[0])?
                .message.lines().next().unwrap_or("").to_string()
        } else {
            "(root)".to_string()
        };
        println!("Dry run: would squash commit '{}' ({}) into its parent ({})",
            commit,
            target_commit.message.lines().next().unwrap_or(""),
            parent_msg);
        println!("  Descendants would be rebuilt.");
        return Ok(());
    }

    let new_head = git_manager.squash(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Squashed commit '{}' into its parent", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Move (reparent) a commit onto a new parent.
pub async fn move_command(commit: String, onto: String, dry_run: bool) -> Result<()> {
    if !dry_run {
        auto_snapshot().await;
    }
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    if dry_run {
        let repo = git_manager.repo();
        let head_id = repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let target_id = git_manager.resolve_commit_pub(&commit, &head_id)?;
        let onto_id = git_manager.resolve_commit_pub(&onto, &head_id)?;
        let target_commit = repo.read_commit(&target_id)?;
        let onto_commit = repo.read_commit(&onto_id)?;
        println!("Dry run: would move commit '{}' ({}) onto '{}' ({})",
            commit,
            target_commit.message.lines().next().unwrap_or(""),
            onto,
            onto_commit.message.lines().next().unwrap_or(""));
        println!("Descendants would be rebuilt.");
        return Ok(());
    }

    let new_head = git_manager.move_commit(&commit, &onto).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Moved commit '{}' onto '{}'", commit, onto);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Unsquash a commit: split it back into two commits.
pub async fn unsquash_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.unsquash(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Unsquashed commit '{}' into two commits", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Revert a commit: create a new commit that undoes the target's changes.
pub async fn revert_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.revert(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Reverted commit '{}'", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Amend working-tree changes into a specific commit (not just HEAD).
pub async fn amend_to_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.amend_to(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Amended working-tree changes into commit '{}'", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Squash HEAD into a specific ancestor commit.
pub async fn squash_into_command(into: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.squash_into(&into).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Squashed HEAD into commit '{}'", into);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Fold a range of commits into one (Sapling-style fold).
pub async fn fold_command(from: String, dry_run: bool) -> Result<()> {
    if !dry_run {
        auto_snapshot().await;
    }
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    if dry_run {
        let repo = git_manager.repo();
        let head_id = repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let from_id = git_manager.resolve_commit_pub(&from, &head_id)?;
        let from_commit = repo.read_commit(&from_id)?;
        println!("Dry run: would fold commits from '{}' to HEAD into one", from);
        println!("  From commit: {} ({})",
            &from_id[..7.min(from_id.len())],
            from_commit.message.lines().next().unwrap_or(""));
        println!("  All messages in range would be combined.");
        return Ok(());
    }

    let new_head = git_manager.fold(&from).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Folded commits from '{}' to HEAD into one", from);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Abandon a commit: remove it and rebuild descendants onto its parent.
pub async fn abandon_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.abandon(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Abandoned commit '{}'", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Forget a commit: abandon it AND remove it from the object store.
pub async fn forget_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.forget(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Forgot commit '{}' (removed from object store)", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Revive an abandoned commit: restore it onto HEAD.
pub async fn revive_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.revive(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Revived commit '{}' onto HEAD", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Duplicate a commit: create a copy on top of HEAD.
pub async fn duplicate_command(commit: String) -> Result<()> {
    auto_snapshot().await;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let new_head = git_manager.duplicate(&commit).await?;

    let short = &new_head[..7.min(new_head.len())];
    println!("Duplicated commit '{}' onto HEAD", commit);
    println!("New HEAD: {}", short);

    Ok(())
}

/// Describe a commit: alias for reword with jj-compatible naming.
pub async fn describe_command(commit: String, message: String, dry_run: bool) -> Result<()> {
    reword_command(commit, message, dry_run).await
}

/// Create an empty commit on top of HEAD (jj-style `new`). Useful as a clean
/// checkpoint before experimenting — the agent can `undo` back to it without
/// losing the working tree.
pub async fn new_command(message: Option<String>) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let msg = message.unwrap_or_else(|| "Empty checkpoint".to_string());
    let commit_hash = git_manager.commit_empty(&msg).await?;

    let branch = git_manager.get_current_branch().await
        .unwrap_or_else(|_| "HEAD".to_string());

    println!("Created empty commit on '{}': {}", branch, &commit_hash[..7.min(commit_hash.len())]);
    println!("Message: {}", msg);

    Ok(())
}

/// Run a validation command at a specific commit without permanently
/// checking out (git-branchless `test`). Saves the current working tree,
/// restores the target commit's tree, runs the command, then restores the
/// original state. Returns an error if the command fails.
pub async fn test_command(commit: String, command: Vec<String>) -> Result<()> {
    use crate::commands::auto_snapshot;

    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    // Resolve the commit hash (support "HEAD", short hashes, branch names).
    let target_hash = if commit == "HEAD" {
        git_manager.get_head_hash()?
    } else {
        // Try as a branch name first, then as a commit hash.
        match git_manager.repo().refs().get_branch(&commit)? {
            Some(h) => h,
            None => commit.clone(),
        }
    };

    // Verify the commit exists.
    let _target_commit = git_manager.repo().read_commit(&target_hash)
        .with_context(|| format!("Commit '{}' not found", commit))?;

    // Snapshot the current working tree so we can restore it.
    auto_snapshot().await;

    let original_head = git_manager.get_head_hash().ok();

    // Restore working tree to the target commit.
    git_manager.sync_index_to_commit(&target_hash)?;
    git_manager.restore_working_tree_pub(&target_hash)?;

    // Run the command.
    if command.is_empty() {
        bail!("No command specified to run");
    }
    let program = &command[0];
    let args = &command[1..];

    let status = std::process::Command::new(program)
        .args(args)
        .current_dir(&current_dir)
        .status();

    let exit_ok = matches!(status, Ok(s) if s.success());

    // Restore the original working tree.
    if let Some(orig) = original_head {
        let _ = git_manager.sync_index_to_commit(&orig);
        let _ = git_manager.restore_working_tree_pub(&orig);
    }

    let target_short = &target_hash[..7.min(target_hash.len())];
    if exit_ok {
        println!("PASS: command {:?} succeeded at commit {}", command.join(" "), target_short);
        Ok(())
    } else {
        let code = status.ok().and_then(|s| s.code()).unwrap_or(-1);
        println!("FAIL: command {:?} failed (exit {}) at commit {}", command.join(" "), code, target_short);
        Err(format!("Test command failed (exit {}) at commit {}", code, target_short).into())
    }
}

pub async fn split_command(files: Vec<String>, message1: Option<String>, message2: Option<String>) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let current_branch = git_manager.get_current_branch().await?;
    let head_id = git_manager.repo().refs().resolve_head()?
        .context("HEAD does not point to a commit")?;
    let head_commit = git_manager.repo().read_commit(&head_id)?;

    if head_commit.parents.is_empty() {
        bail!("Cannot split the initial commit (no parent to reset to)");
    }

    let parent_id = head_commit.parents[0].clone();

    let parent_tree = {
        let parent_commit = git_manager.repo().read_commit(&parent_id)?;
        git_manager.repo().read_tree(&parent_commit.tree)?
    };
    let head_tree = git_manager.repo().read_tree(&head_commit.tree)?;

    let parent_files: std::collections::HashSet<String> = parent_tree.entries.iter()
        .map(|e| e.name.clone())
        .collect();

    let changed_files: Vec<String> = head_tree.entries.iter()
        .filter(|e| {
            !parent_files.contains(&e.name) ||
            parent_tree.entries.iter().find(|p| p.name == e.name).map(|p| p.id != e.id).unwrap_or(true)
        })
        .map(|e| e.name.clone())
        .collect();

    if changed_files.is_empty() {
        bail!("HEAD commit has no changes to split");
    }

    let changed_set: std::collections::HashSet<&String> = changed_files.iter().collect();
    for f in &files {
        if !changed_set.contains(f) {
            bail!("File '{}' is not part of the HEAD commit's changes", f);
        }
    }

    info!("Splitting commit '{}' on branch '{}'", &head_id[..7.min(head_id.len())], current_branch);
    info!("First commit: {} files ({})", files.len(), files.join(", "));
    let remaining: Vec<String> = changed_files.iter()
        .filter(|f| !files.contains(f))
        .cloned()
        .collect();
    info!("Second commit: {} files ({})", remaining.len(), remaining.join(", "));

    git_manager.repo().refs().set_branch(&current_branch, &parent_id)?;
    git_manager.sync_index_to_commit(&parent_id)?;
    git_manager.restore_working_tree_pub(&head_id)?;

    git_manager.add_files(&files).await?;
    let msg1 = message1.unwrap_or_else(|| format!("Split: {}", files.join(", ")));
    let commit1 = git_manager.commit(&msg1).await?;
    println!("Created first commit: {} — \"{}\"", &commit1[..7.min(commit1.len())], msg1);

    git_manager.add_all().await?;
    let msg2 = message2.unwrap_or_else(|| format!("Split: {}", remaining.join(", ")));
    let commit2 = git_manager.commit(&msg2).await?;
    println!("Created second commit: {} — \"{}\"", &commit2[..7.min(commit2.len())], msg2);

    println!("Split complete on branch '{}': 1 commit → 2 commits", current_branch);
    Ok(())
}

pub async fn watch_command(debounce_secs: u64) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;

    let (tx, mut rx) = tokio::sync::mpsc::channel(100);
    let watch_dir = current_dir.clone();

    std::thread::spawn(move || {
        use notify::Watcher;
        let (event_tx, event_rx) = std::sync::mpsc::channel();
        let mut watcher = match notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
            let _ = event_tx.send(res);
        }) {
            Ok(w) => w,
            Err(e) => {
                eprintln!("Failed to create watcher: {}", e);
                return;
            }
        };

        if let Err(e) = watcher.watch(&watch_dir, notify::RecursiveMode::Recursive) {
            eprintln!("Failed to watch directory: {}", e);
            return;
        }

        loop {
            if let Ok(Ok(event)) = event_rx.recv() {
                let is_boring = event.paths.iter().any(|p| {
                    let s = p.to_string_lossy();
                    s.contains("/.git/") || s.contains("/.codetree/") || s.contains("/target/")
                });
                if !is_boring {
                    let _ = tx.blocking_send(());
                }
            }
        }
    });

    println!("Watching {} for changes (debounce: {}s)", current_dir.display(), debounce_secs);
    println!("Press Ctrl+C to stop\n");

    let debounce_duration = tokio::time::Duration::from_secs(debounce_secs);
    let mut debounce = tokio::time::interval(debounce_duration);
    debounce.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    debounce.reset();

    let mut pending = false;
    let mut save_count = 0;

    loop {
        tokio::select! {
            Some(()) = rx.recv() => {
                pending = true;
                debounce.reset();
            }
            _ = debounce.tick() => {
                if pending {
                    match save_command(vec![], false, false, None).await {
                        Ok(()) => {
                            save_count += 1;
                            println!("[watch] Auto-save #{} completed", save_count);
                        }
                        Err(e) => {
                            if !e.to_string().contains("No changes") {
                                println!("[watch] Auto-save failed: {}", e);
                            }
                        }
                    }
                    pending = false;
                }
            }
        }
    }
}

/// Run a fixing/formatting command and amend the changes into HEAD (jj-style fix).
pub async fn fix_command(command: Vec<String>) -> Result<()> {
    if command.is_empty() {
        bail!("No command specified. Usage: codetree fix -- <command...>");
    }

    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let program = &command[0];
    let args = &command[1..];

    let status = std::process::Command::new(program)
        .args(args)
        .current_dir(&current_dir)
        .status()
        .with_context(|| format!("Failed to run command: {}", program))?;

    if !status.success() {
        bail!("Fix command exited with non-zero status");
    }

    // Stage all changes made by the fix command.
    git_manager.add_all().await?;

    // Check if there are any changes to amend.
    let status_result = git_manager.get_status().await?;
    if status_result.modified.is_empty() && status_result.staged.is_empty() {
        println!("Fix command made no changes.");
        return Ok(());
    }

    // Amend HEAD with the changes.
    let new_head = git_manager.amend_commit().await?;
    let short = &new_head[..7.min(new_head.len())];
    println!("Fixed and amended HEAD: {}", short);

    Ok(())
}