1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
use codetree::error::Result;
use clap::{Parser, Subcommand};
use std::process;
use codetree::commands::*;
#[derive(Parser)]
#[command(name = "codetree")]
#[command(about = "AI-native version control system for autonomous agents")]
#[command(version)]
#[command(long_about = "CodeTree is a standalone VCS for autonomous agents — it owns its object\nstore in .codetree/ and does not depend on Git. Agents work in operations\n(start, save, finish, withdraw); CodeTree manages isolation, history, and\nmerging natively.\n\nRun 'codetree-mcp' to start the MCP server for AI assistant integration.")]
struct Cli {
#[command(subcommand)]
command: Commands,
/// Enable verbose logging
#[arg(short, long, global = true, help = "Enable detailed logging output")]
verbose: bool,
/// Enable quiet mode (minimal output)
#[arg(short, long, global = true, conflicts_with = "verbose", help = "Suppress non-essential output")]
quiet: bool,
/// Output JSON for machine-readable consumption
#[arg(long, global = true, help = "Output results as JSON")]
json: bool,
}
#[derive(Subcommand)]
enum BisectSub {
/// Start a bisect session (marks current HEAD as bad)
Start,
/// Mark a commit as good (narrows the search)
Good {
/// Commit spec (default: current HEAD)
commit: Option<String>,
},
/// Mark a commit as bad (narrows the search)
Bad {
/// Commit spec (default: current HEAD)
commit: Option<String>,
},
/// Show the current bisect state
Log,
/// End the bisect session and restore the original HEAD
Reset,
}
#[derive(Subcommand)]
enum TagSub {
/// Create a tag pointing at a commit (default: HEAD)
Create {
/// Tag name
name: String,
/// Commit hash, "HEAD", or "HEAD~N" (default: HEAD)
commit: Option<String>,
/// Create an annotated tag with a message
#[arg(short, long)]
message: Option<String>,
},
/// List all tags
List,
/// Delete a tag
Delete {
/// Tag name
name: String,
},
}
#[derive(Subcommand)]
enum ConfigSub {
/// Get a config value by dotted key (e.g., "git.base_branch")
Get {
/// Dotted key (section.field)
key: String,
},
/// Set a config value by dotted key
Set {
/// Dotted key (section.field)
key: String,
/// New value
value: String,
},
/// List all config values
List,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize codetree in the current repository
#[command(alias = "i")]
Init {
/// Force initialization even if already initialized
#[arg(short, long, help = "Overwrite existing configuration")]
force: bool,
},
/// Start a new mini-operation (parallel by default — stays on current branch)
#[command(alias = "st")]
Start {
/// Description of the mini-operation
#[arg(help = "Description for the operation (used in auto-generated branch name)")]
description: String,
/// Checkout the newly created branch (old behavior; default is parallel)
#[arg(short, long, help = "Checkout the new branch after creation")]
checkout: bool,
/// Create a git worktree for this operation
#[arg(short, long, help = "Create a git worktree for the operation")]
worktree: bool,
/// Branchless mode: track as bookmark without creating a git branch
#[arg(short, long, help = "Track operation as bookmark without creating a git branch")]
branchless: bool,
/// Files assigned to this operation (pre-declares scope)
#[arg(short, long, help = "Files assigned to this operation", num_args = 1.., value_delimiter = ',')]
files: Option<Vec<String>>,
/// Operations this one depends on (must finish first)
#[arg(short, long, help = "Branch names this operation depends on", num_args = 1.., value_delimiter = ',')]
depends_on: Option<Vec<String>>,
/// Operation template (refactor, bugfix, feature)
#[arg(short = 'p', long, help = "Use a predefined operation template for branch prefix and commit format")]
template: Option<String>,
/// Tags for grouping operations (e.g., "sprint-42", "bugfix-week")
#[arg(short = 'g', long, help = "Tags for grouping operations", num_args = 1.., value_delimiter = ',')]
tags: Option<Vec<String>>,
/// Agent ID for multi-agent tracking (defaults to hostname+PID)
#[arg(short = 'a', long, help = "Agent identifier for multi-agent tracking")]
agent: Option<String>,
/// Wait for file locks to be released instead of failing immediately
#[arg(long, help = "Wait for file locks to become available (polls every 2s, up to 5min)")]
wait: bool,
},
/// Save all current changes to the active operation branch
#[command(alias = "sv")]
Save {
/// Custom commit message (multiple -m flags combine as title + body)
#[arg(short, long, help = "Commit message (repeatable: -m title -m body)")]
message: Vec<String>,
/// Run validation before committing (overrides config)
#[arg(long, help = "Run validation command before committing")]
validate: bool,
/// Skip validation even if config requires it
#[arg(long, help = "Skip validation even if config requires it")]
no_validate: bool,
},
/// Merge an operation branch back to the base branch
#[command(alias = "m")]
Merge {
/// Branch name to merge (defaults to current branch)
#[arg(help = "Branch to merge (defaults to current)")]
branch: Option<String>,
/// Squash all feature-branch commits into a single commit
#[arg(short, long, help = "Combine all commits into one before merging")]
squash: bool,
},
/// Show current branch status and changes
#[command(alias = "s")]
Status,
/// List all managed operation branches
#[command(alias = "ls")]
List {
/// Filter by tag
#[arg(short, long, help = "Only show operations with this tag")]
tag: Option<String>,
/// Revset-style query (e.g. "active && tag:sprint-42")
#[arg(short = 'Q', long, help = "Filter with revset-style query: active, merged, archived, branchless, stale, tag:<name>. Combine with && (AND) and || (OR)")]
query: Option<String>,
/// Output format template (e.g. "{name} {status} {description}")
#[arg(short = 'F', long, help = "Custom output format. Placeholders: {name}, {status}, {description}, {created}, {tags}, {stale}")]
format: Option<String>,
},
/// Switch to an active operation branch
#[command(alias = "sw")]
Switch {
/// Branch name to switch to
#[arg(help = "Branch to switch to")]
branch: String,
},
/// Switch to the next active operation (wraps around)
#[command(alias = "n")]
Next,
/// Switch to the previous active operation (wraps around)
#[command(alias = "p")]
Prev,
/// Finish an operation: merge back to base and clean up
#[command(alias = "f")]
Finish {
/// Branch to finish (defaults to current)
#[arg(help = "Branch to finish (defaults to current branch)")]
branch: Option<String>,
/// Finish all operations with this tag
#[arg(short, long, help = "Finish all operations with this tag")]
tag: Option<String>,
/// Preview what would happen without making changes
#[arg(long, help = "Preview without making changes")]
dry_run: bool,
},
/// Withdraw an operation: fully revert and remove it
#[command(alias = "w")]
Withdraw {
/// Branch to withdraw
#[arg(help = "Branch or bookmark to fully revert")]
branch: Option<String>,
/// Withdraw all operations with this tag
#[arg(short, long, help = "Withdraw all operations with this tag")]
tag: Option<String>,
},
/// Compare diffs across all active operations
#[command(alias = "cmp")]
Compare,
/// Create an empty commit on top of HEAD (jj-style checkpoint)
New {
/// Commit message (defaults to "Empty checkpoint")
#[arg(short, long, help = "Commit message for the empty commit")]
message: Option<String>,
},
/// Absorb uncommitted changes into the best-matching commit (Sapling-style)
#[command(alias = "ab")]
Absorb,
/// Run a validation command at a specific commit (git-branchless test)
Test {
/// Commit hash, branch name, or "HEAD"
commit: String,
/// Command and arguments to run (use -- to separate from codetree flags)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
command: Vec<String>,
},
/// Rewrite a commit's message (jj-style reword)
Reword {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
/// New commit message
#[arg(short, long)]
message: String,
/// Preview without executing
#[arg(long)]
dry_run: bool,
},
/// Squash a commit into its parent (jj-style squash)
Squash {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
/// Preview without executing
#[arg(long)]
dry_run: bool,
},
/// Move (reparent) a commit onto a new parent (git-branchless move)
Move {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
/// New parent commit
#[arg(long)]
onto: String,
/// Preview the move without executing
#[arg(long)]
dry_run: bool,
},
/// Reverse of squash: split a commit back into two (jj-style unsquash)
Unsquash {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Revert a commit: create a new commit that undoes its changes
Revert {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Amend working-tree changes into a specific commit (Sapling amend --to)
AmendTo {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Squash HEAD into a specific ancestor commit (jj squash --into)
SquashInto {
/// Ancestor commit to squash into
into: String,
},
/// Fold a range of commits into one (Sapling-style fold)
Fold {
/// Starting commit (folds from this commit to HEAD)
#[arg(long)]
from: String,
/// Preview without executing
#[arg(long)]
dry_run: bool,
},
/// Show linear commit history (Sapling-style log)
Log {
/// Starting commit (default: HEAD)
commit: Option<String>,
/// Maximum number of commits to show
#[arg(short, long)]
limit: Option<usize>,
/// Print only the commit count
#[arg(long)]
count: bool,
},
/// Show a commit's diff (what changed in that commit)
Show {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
/// Show mutation history (predecessors from rewrites)
#[arg(short = 't', long)]
mutation: bool,
},
/// Show diff between working tree and HEAD (or a specified commit)
Diff {
/// Compare working tree against this commit (default: HEAD)
commit: Option<String>,
},
/// Show which commit last modified each line of a file (blame/annotate)
Blame {
/// File path to annotate
file: String,
},
/// Show commit history for a specific file
Filelog {
/// File path
file: String,
},
/// Remove untracked files from the working tree
Clean,
/// Garbage collect unreachable objects
Gc,
/// Show the operation log (undo/redo history)
OpLog,
/// Binary search for the commit that introduced a bug
Bisect {
#[command(subcommand)]
action: BisectSub,
},
/// Manage tags (named pointers to commits)
Tag {
#[command(subcommand)]
action: TagSub,
},
/// Abandon a commit: remove it and rebuild descendants onto its parent (jj-style)
Abandon {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Revive an abandoned commit onto HEAD (jj-style)
Revive {
/// Commit hash or hash prefix
commit: String,
},
/// Duplicate a commit on top of HEAD (jj-style)
Duplicate {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Describe (reword) a commit — jj-compatible alias for reword
Describe {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
/// New commit message
#[arg(short, long)]
message: String,
/// Preview without executing
#[arg(long)]
dry_run: bool,
},
/// Manage configuration (get/set/list)
Config {
#[command(subcommand)]
action: ConfigSub,
},
/// Search file contents in HEAD's tree (jj file search)
FileSearch {
/// Search pattern (case-insensitive substring)
pattern: String,
/// Search file names only (not contents)
#[arg(long)]
name_only: bool,
},
/// List all files in a commit's tree (default: HEAD)
FileList {
/// Commit hash, "HEAD", or "HEAD~N" (default: HEAD)
commit: Option<String>,
},
/// List all branch heads
Heads,
/// Move to the next commit in the stack (child of HEAD)
NextCommit,
/// Move to the previous commit in the stack (parent of HEAD)
PrevCommit,
/// Repair broken commit graphs after rewrites
RestackGraph,
/// Run a fixing command and amend changes into HEAD (jj-style fix)
Fix {
/// Command and arguments to run (use -- to separate from codetree flags)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
command: Vec<String>,
},
/// Show evolution history of a commit (jj evolog)
Evolog {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Show diff between two arbitrary commits (jj interdiff)
Interdiff {
/// First commit
commit_a: String,
/// Second commit
commit_b: String,
},
/// Restore a commit's tree from another commit (jj restore)
Restore {
/// Source commit to restore from
#[arg(long)]
from: String,
/// Target commit to restore to
#[arg(long)]
to: String,
},
/// Hide a commit from smartlog (Sapling hide)
Hide {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Unhide a previously hidden commit (Sapling unhide)
Unhide {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// List fork points (commits with multiple children)
Forks,
/// Find the merge point (common ancestor) of two commits
MergePoint {
/// First commit
commit_a: String,
/// Second commit
commit_b: String,
},
/// Verify a commit's integrity (hash, tree, parents, blobs)
Verify {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Run a command across each commit in a range (jj run)
Run {
/// Starting commit (runs from this commit to HEAD)
#[arg(long)]
from: String,
/// Command and arguments to run (use -- to separate)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
command: Vec<String>,
},
/// Check if merging a branch would conflict (speculative merge)
SpeculativeMerge {
/// Branch name to test merging into HEAD
branch: String,
},
/// Rename a branch (jj bookmark rename)
BranchRename {
/// Old branch name
old_name: String,
/// New branch name
new_name: String,
},
/// Advance a branch to a target commit (jj bookmark advance)
BranchAdvance {
/// Branch name to advance
name: String,
/// Target commit (defaults to HEAD)
commit: Option<String>,
},
/// Forget a commit: abandon and remove from object store (jj forget)
Forget {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Checkout a specific commit (detached HEAD, Sapling-style goto)
Goto {
/// Commit hash, "HEAD", or "HEAD~N"
commit: String,
},
/// Check if a branch is ready to merge (read-only)
Ready {
/// Branch to check (defaults to current branch)
branch: Option<String>,
},
/// Import commits from a Git repository into CodeTree
Import {
/// Force reimport (removes existing .codetree/)
#[arg(short, long)]
force: bool,
},
/// Export commits from CodeTree to a Git repository
Export,
/// Create a bundle (tar archive) of the CodeTree repository
Bundle {
/// Output file path (defaults to codetree-bundle-<timestamp>.tar.gz)
#[arg(short, long)]
output: Option<String>,
},
/// Restore a CodeTree repository from a bundle
Unbundle {
/// Path to the bundle file
bundle: String,
},
/// Split the HEAD commit into two by file selection
#[command(alias = "sp")]
Split {
/// Files to put in the first commit (rest go in the second)
#[arg(short, long, help = "Files for the first commit", num_args = 1.., value_delimiter = ',')]
files: Vec<String>,
/// Message for the first commit
#[arg(short = 'm', long = "message1", help = "Commit message for the first commit")]
message1: Option<String>,
/// Message for the second commit
#[arg(short = 'M', long = "message2", help = "Commit message for the second commit")]
message2: Option<String>,
},
/// Rebase all active operation branches onto the base branch
#[command(alias = "rb")]
Rebase {
/// Preview what would happen without making changes
#[arg(long, help = "Preview without making changes")]
dry_run: bool,
/// Run continuously, rebasing every N seconds (daemon mode)
#[arg(long, help = "Run as a daemon, rebasing every N seconds")]
watch: Option<u64>,
},
/// Fix broken stacking relationships after manual rebases or amends
#[command(alias = "rs")]
Restack,
/// Pull from remote and rebase all active branches (git-branchless sync)
#[command(alias = "sy")]
Sync,
/// Publish operation as a GitHub PR
#[command(alias = "pub")]
Publish {
/// Branch to publish (defaults to current)
#[arg(help = "Branch to publish as PR")]
branch: Option<String>,
},
/// Watch working tree and auto-save after a debounce period
Watch {
/// Debounce duration in seconds (default: 2)
#[arg(short, long, help = "Seconds of inactivity before auto-saving", default_value = "2")]
debounce: u64,
},
/// Undo an operation (last by default, or specify by index)
#[command(alias = "u")]
Undo {
/// Operation index to undo (0-based; omit for most recent)
#[arg(help = "Operation index to undo (omit for most recent)")]
index: Option<usize>,
/// List all undoable operations with their indices
#[arg(short, long, help = "List all undoable operations")]
list: bool,
},
/// Redo an operation that was previously undone
#[command(alias = "r")]
Redo {
/// Operation index to redo (0-based; omit for most recent)
#[arg(help = "Operation index to redo (omit for most recent)")]
index: Option<usize>,
/// List all redoable operations with their indices
#[arg(short, long, help = "List all redoable operations")]
list: bool,
},
/// Show a tree view of active operations and their relationship to base
#[command(alias = "sl")]
Smartlog {
/// Show individual commits within each operation
#[arg(short, long)]
verbose: bool,
/// Highlight current position and dim others
#[arg(short, long, help = "Highlight current operation")]
position: bool,
/// Maximum number of operations to show (pagination)
#[arg(short = 'L', long, help = "Limit number of operations shown")]
limit: Option<usize>,
/// Skip the first N operations (pagination)
#[arg(short = 'O', long, help = "Offset for pagination")]
offset: Option<usize>,
/// Reverse display order (newest first)
#[arg(short = 'R', long)]
reverse: bool,
/// Skip rendering HEAD and main branch (exact mode)
#[arg(short = 'E', long)]
exact: bool,
},
/// Show current position in the version tree
#[command(name = "whereami", alias = "wa")]
WhereAmI,
/// Resolve merge conflicts manually and cache the resolutions
#[command(alias = "rv")]
Resolve,
/// Manually create a working-copy snapshot
#[command(alias = "snap")]
Snapshot {
/// Also back up operation state (branches.json, ops.json)
#[arg(long)]
ops: bool,
},
/// List stored working-copy snapshots
#[command(alias = "snaps")]
Snapshots,
/// Restore a working-copy snapshot to the working tree
#[command(alias = "rsnap")]
RestoreSnapshot {
/// Snapshot id (from `codetree snapshots`)
#[arg(help = "Snapshot id to restore")]
id: usize,
/// Also restore operation state (branches.json, ops.json)
#[arg(long)]
ops: bool,
},
/// Manage git worktrees for operations
#[command(alias = "wt")]
Worktree {
#[command(subcommand)]
action: WorktreeAction,
},
/// Freeze a file or directory — prevents any modification by operations
Freeze {
/// Path to freeze (file or directory)
#[arg(help = "Path to freeze")]
path: String,
},
/// Unfreeze a file or directory — allows modifications again
Unfreeze {
/// Path to unfreeze
#[arg(help = "Path to unfreeze")]
path: String,
/// Skip confirmation prompt
#[arg(short, long, help = "Skip confirmation")]
force: bool,
},
/// List all frozen paths
Frozen,
/// Release a file lock manually (e.g., if an agent crashed)
Unlock {
/// Path to unlock
#[arg(help = "Path to unlock")]
path: String,
},
/// List all active file locks and which operation holds them
Locks,
/// Evaluate candidates in a candidate group
Evaluate {
/// Candidate group name
#[arg(help = "Candidate group to evaluate")]
group: String,
},
/// Promote a candidate operation — merge it and withdraw all others in the group
Promote {
/// Candidate group name
#[arg(help = "Candidate group")]
group: String,
/// Operation name to promote
#[arg(help = "Operation to promote")]
operation: String,
},
/// List all known agents and their active operations
Agents,
}
#[derive(Subcommand)]
enum WorktreeAction {
/// Add a worktree for an active branch
Add {
/// Branch to create worktree for
#[arg(help = "Branch to create worktree for")]
branch: String,
},
/// Remove a worktree
Remove {
/// Branch whose worktree to remove
#[arg(help = "Branch whose worktree to remove")]
branch: String,
},
/// List all worktrees
List,
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
if cli.verbose {
eprintln!("[DEBUG] CodeTree starting up...");
}
let json = cli.json;
let result = match cli.command {
Commands::Init { force } => {
init_command(force).await
}
Commands::Start { description, checkout, worktree, branchless, files, depends_on, template, tags, agent, wait } => {
let agent_id = agent.or_else(|| {
let hostname = std::env::var("HOSTNAME")
.or_else(|_| std::env::var("USER"))
.unwrap_or_else(|_| "unknown".to_string());
Some(format!("{}-{}", hostname, std::process::id()))
});
start_command(description, !checkout || worktree || branchless, worktree, branchless, files, depends_on, template, tags, agent_id, wait).await
}
Commands::Finish { branch, tag, dry_run } => {
finish_command(branch, tag, dry_run).await
}
Commands::Withdraw { branch, tag } => {
withdraw_command(branch, tag).await
}
Commands::Compare => {
compare_command().await
}
Commands::New { message } => {
new_command(message).await
}
Commands::Absorb => {
absorb_command().await
}
Commands::Test { commit, command } => {
test_command(commit, command).await
}
Commands::Reword { commit, message, dry_run } => {
reword_command(commit, message, dry_run).await
}
Commands::Squash { commit, dry_run } => {
squash_command(commit, dry_run).await
}
Commands::Move { commit, onto, dry_run } => {
move_command(commit, onto, dry_run).await
}
Commands::Unsquash { commit } => {
unsquash_command(commit).await
}
Commands::Revert { commit } => {
revert_command(commit).await
}
Commands::AmendTo { commit } => {
amend_to_command(commit).await
}
Commands::SquashInto { into } => {
squash_into_command(into).await
}
Commands::Fold { from, dry_run } => {
fold_command(from, dry_run).await
}
Commands::Log { commit, limit, count } => {
log_command(commit, limit, count).await
}
Commands::Show { commit, mutation } => {
show_command(commit, mutation).await
}
Commands::Diff { commit } => {
diff_command(commit).await
}
Commands::Blame { file } => {
blame_command(file).await
}
Commands::Filelog { file } => {
filelog_command(file).await
}
Commands::Clean => {
clean_command().await
}
Commands::Gc => {
gc_command().await
}
Commands::OpLog => {
op_log_command().await
}
Commands::Bisect { action } => {
let bisect_action = match action {
BisectSub::Start => BisectAction::Start,
BisectSub::Good { commit } => BisectAction::Good(commit),
BisectSub::Bad { commit } => BisectAction::Bad(commit),
BisectSub::Log => BisectAction::Log,
BisectSub::Reset => BisectAction::Reset,
};
bisect_command(bisect_action).await
}
Commands::Tag { action } => {
let tag_action = match action {
TagSub::Create { name, commit, message } => TagAction::Create { name, commit, annotate: message },
TagSub::List => TagAction::List,
TagSub::Delete { name } => TagAction::Delete { name },
};
tag_command(tag_action).await
}
Commands::Abandon { commit } => {
abandon_command(commit).await
}
Commands::Revive { commit } => {
revive_command(commit).await
}
Commands::Duplicate { commit } => {
duplicate_command(commit).await
}
Commands::Describe { commit, message, dry_run } => {
describe_command(commit, message, dry_run).await
}
Commands::Config { action } => {
let config_action = match action {
ConfigSub::Get { key } => ConfigAction::Get(key),
ConfigSub::Set { key, value } => ConfigAction::Set(key, value),
ConfigSub::List => ConfigAction::List,
};
config_command(config_action).await
}
Commands::FileSearch { pattern, name_only } => {
file_search_command(pattern, name_only).await
}
Commands::FileList { commit } => {
file_list_command(commit).await
}
Commands::Heads => {
heads_command().await
}
Commands::NextCommit => {
next_commit_command().await
}
Commands::PrevCommit => {
prev_commit_command().await
}
Commands::RestackGraph => {
restack_graph_command().await
}
Commands::Fix { command } => {
fix_command(command).await
}
Commands::Evolog { commit } => {
evolog_command(commit).await
}
Commands::Interdiff { commit_a, commit_b } => {
interdiff_command(commit_a, commit_b).await
}
Commands::Restore { from, to } => {
restore_command(from, to).await
}
Commands::Hide { commit } => {
hide_command(commit).await
}
Commands::Unhide { commit } => {
unhide_command(commit).await
}
Commands::Forks => {
forks_command().await
}
Commands::MergePoint { commit_a, commit_b } => {
merge_point_command(commit_a, commit_b).await
}
Commands::Verify { commit } => {
verify_command(commit).await
}
Commands::Run { from, command } => {
run_command(from, command).await
}
Commands::SpeculativeMerge { branch } => {
speculative_merge_command(branch).await
}
Commands::Goto { commit } => {
goto_command(commit).await
}
Commands::Ready { branch } => {
ready_command(branch, json).await
}
Commands::Import { force } => {
import_command(force).await
}
Commands::Export => {
export_command().await
}
Commands::Bundle { output } => {
bundle_command(output).await
}
Commands::Unbundle { bundle } => {
unbundle_command(bundle).await
}
Commands::Split { files, message1, message2 } => {
split_command(files, message1, message2).await
}
Commands::Rebase { dry_run, watch } => {
if let Some(interval) = watch {
println!("Auto-rebase daemon started (interval: {}s). Press Ctrl+C to stop.", interval);
loop {
if let Err(e) = rebase_command(dry_run).await {
eprintln!("Rebase error: {}", e);
}
println!("\n--- Waiting {}s before next rebase cycle ---", interval);
tokio::time::sleep(std::time::Duration::from_secs(interval)).await;
}
} else {
rebase_command(dry_run).await
}
}
Commands::Restack => {
restack_command().await
}
Commands::Sync => {
sync_command().await
}
Commands::Publish { branch } => {
publish_command(branch).await
}
Commands::Watch { debounce } => {
watch_command(debounce).await
}
Commands::Switch { branch } => {
switch_command(branch).await
}
Commands::Next => {
next_command().await
}
Commands::Prev => {
prev_command().await
}
Commands::Save { message, validate, no_validate } => {
save_command(message, validate, no_validate).await
}
Commands::BranchRename { old_name, new_name } => {
branch_rename_command(old_name, new_name).await
}
Commands::BranchAdvance { name, commit } => {
branch_advance_command(name, commit).await
}
Commands::Forget { commit } => {
forget_command(commit).await
}
Commands::Merge { branch, squash } => {
merge_command(branch, squash).await
}
Commands::Status => {
status_command(json).await
}
Commands::List { tag, query, format } => {
list_command(tag, query, json, format).await
}
Commands::Undo { index, list } => {
undo_command(index, list).await
}
Commands::Redo { index, list } => {
redo_command(index, list).await
}
Commands::Smartlog { verbose, position, limit, offset, reverse, exact } => {
smartlog_command(verbose, position, limit, offset, reverse, exact).await
}
Commands::WhereAmI => {
whereami_command().await
}
Commands::Resolve => {
resolve_command().await
}
Commands::Snapshot { ops } => {
snapshot_command(ops).await
}
Commands::Snapshots => {
snapshots_command().await
}
Commands::RestoreSnapshot { id, ops } => {
restore_snapshot_command(id, ops).await
}
Commands::Worktree { action } => {
match action {
WorktreeAction::Add { branch } => {
worktree_add_command(branch).await
}
WorktreeAction::Remove { branch } => {
worktree_remove_command(branch).await
}
WorktreeAction::List => {
worktree_list_command().await
}
}
}
Commands::Freeze { path } => {
freeze_command(path).await
}
Commands::Unfreeze { path, force } => {
unfreeze_command(path, force).await
}
Commands::Frozen => {
frozen_command().await
}
Commands::Unlock { path } => {
unlock_command(path).await
}
Commands::Locks => {
locks_command().await
}
Commands::Evaluate { group } => {
evaluate_command(group).await
}
Commands::Promote { group, operation } => {
promote_command(group, operation).await
}
Commands::Agents => {
agents_command().await
}
};
if let Err(error) = result {
if !cli.quiet {
eprintln!("Error: {}", error);
}
process::exit(1);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::Cli;
use clap::Parser;
// Regression: `list` used to bind `-q` to both `query` and the global
// `quiet`, panicking in debug builds at parse time for any `list` call.
#[test]
fn list_parses_without_short_flag_collision() {
// Bare `list` must parse.
let cli = Cli::try_parse_from(["codetree", "list"]);
assert!(cli.is_ok(), "bare `list` should parse: {:?}", cli.err());
// `list -Q active` uses the query short flag.
let cli = Cli::try_parse_from(["codetree", "list", "-Q", "active"]);
assert!(cli.is_ok(), "`list -Q active` should parse: {:?}", cli.err());
// `list --query active` uses the long flag.
let cli = Cli::try_parse_from(["codetree", "list", "--query", "active"]);
assert!(cli.is_ok(), "`list --query active` should parse: {:?}", cli.err());
// `list -q` is the global quiet flag, not query — must parse.
let cli = Cli::try_parse_from(["codetree", "list", "-q"]);
assert!(cli.is_ok(), "`list -q` (quiet) should parse: {:?}", cli.err());
// `list -t sprint-42` tag filter.
let cli = Cli::try_parse_from(["codetree", "list", "-t", "sprint-42"]);
assert!(cli.is_ok(), "`list -t sprint-42` should parse: {:?}", cli.err());
}
}