minibeads 0.17.0

A minimal, markdown-based drop-in replacement for the beads issue tracker
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
mod code_patch;
mod format;
mod hash;
mod lock;
mod storage;
mod sync;
mod types;

// Include build-time information generated by build.rs
mod built_info {
    include!(concat!(env!("OUT_DIR"), "/built.rs"));
}

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::collections::HashMap;
use std::env;
use std::path::{Path, PathBuf};
use storage::Storage;
use types::{DependencyType, IssueType, Status};

/// Generate long version string with git info and build date
fn long_version() -> &'static str {
    // Allocate version string at runtime, leak it to get 'static lifetime
    // This is called once during CLI initialization
    Box::leak(
        {
            let mut version = env!("CARGO_PKG_VERSION").to_string();

            // Add build date from compile time
            version.push_str(&format!("\nBuilt: {}", env!("BUILD_DATE")));

            // Add git commit if available and working copy is clean
            if let (Some(commit), Some(false)) =
                (built_info::GIT_COMMIT_HASH_SHORT, built_info::GIT_DIRTY)
            {
                version.push_str(&format!("\nCommit: {}", commit));
            }

            version
        }
        .into_boxed_str(),
    )
}

#[derive(Parser)]
#[command(
    name = "mb",
    about = "Minibeads - A minimal issue tracker",
    long_version = long_version(),
)]
struct Cli {
    #[command(flatten)]
    global_opts: GlobalOpts,

    #[command(subcommand)]
    command: Commands,
}

#[derive(clap::Args)]
#[command(next_help_heading = "Global Options")]
struct GlobalOpts {
    /// Path to .beads directory (minibeads-specific, preferred over --db)
    #[arg(long = "mb-beads-dir", global = true)]
    mb_beads_dir: Option<PathBuf>,

    /// Path to database (for upstream compatibility - use --mb-beads-dir instead)
    /// Treated as syntactic sugar for specifying the .beads directory.
    /// When path ends with .db, the parent directory is used.
    #[arg(long, global = true)]
    db: Option<PathBuf>,

    /// Actor name for audit trail
    #[arg(long, global = true)]
    actor: Option<String>,

    /// Output JSON format
    #[arg(long, global = true)]
    json: bool,

    /// Validation mode for parsing issues (minibeads-specific)
    #[arg(
        long = "mb-validation",
        global = true,
        default_value = "error",
        value_name = "MODE"
    )]
    mb_validation: ValidationMode,

    /// Disable command logging to .beads/command_history.log (minibeads-specific)
    #[arg(long = "mb-no-cmd-logging", global = true)]
    mb_no_cmd_logging: bool,

    /// Disable auto-flush (ignored for compatibility)
    #[arg(long, global = true)]
    no_auto_flush: bool,

    /// Disable auto-import (ignored for compatibility)
    #[arg(long, global = true)]
    no_auto_import: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ValidationMode {
    Silent,
    Warn,
    Error,
}

impl std::str::FromStr for ValidationMode {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "silent" => Ok(ValidationMode::Silent),
            "warn" => Ok(ValidationMode::Warn),
            "error" => Ok(ValidationMode::Error),
            _ => Err(anyhow::anyhow!(
                "Invalid validation mode: '{}'. Valid values are: silent, warn, error",
                s
            )),
        }
    }
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize beads in current directory
    Init {
        /// Issue prefix (e.g., 'myproject' for myproject-1, myproject-2)
        #[arg(short, long)]
        prefix: Option<String>,

        /// Use hash-based issue IDs instead of sequential numbers (minibeads-specific)
        #[arg(long = "mb-hash-ids")]
        mb_hash_ids: bool,
    },

    /// Create a new issue
    Create {
        /// Issue title (positional argument, or use --title flag)
        title: Option<String>,

        /// Issue title (alternative to positional argument)
        #[arg(long = "title", allow_hyphen_values = true)]
        title_flag: Option<String>,

        /// Priority (0-4, 0=highest)
        #[arg(short, long, default_value = "2")]
        priority: i32,

        /// Issue type
        #[arg(short = 't', long, default_value = "task")]
        issue_type: IssueType,

        /// Description
        #[arg(short, long, default_value = "", allow_hyphen_values = true)]
        description: String,

        /// Design notes
        #[arg(long, allow_hyphen_values = true)]
        design: Option<String>,

        /// Acceptance criteria
        #[arg(long, allow_hyphen_values = true)]
        acceptance: Option<String>,

        /// Assignee
        #[arg(short = 'a', long)]
        assignee: Option<String>,

        /// Labels (can be specified multiple times)
        #[arg(short, long)]
        label: Vec<String>,

        /// External reference
        #[arg(long)]
        external_ref: Option<String>,

        /// Explicit issue ID
        #[arg(long)]
        id: Option<String>,

        /// Dependencies (comma-separated). Formats:
        /// Simple: "bd-1,bd-2" (defaults to 'blocks')
        /// Advanced: "blocks:bd-1,related:bd-2,discovered-from:bd-3"
        #[arg(long)]
        deps: Option<String>,

        /// Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')
        #[arg(long)]
        parent: Option<String>,

        /// Force creation even if prefix doesn't match database prefix
        #[arg(long)]
        force: bool,

        /// Create multiple issues from markdown file
        #[arg(short = 'f', long)]
        file: Option<PathBuf>,
    },

    /// List issues
    List {
        /// Filter by status
        #[arg(short = 's', long)]
        status: Option<Status>,

        /// Filter by priority (comma-separated list, e.g., "1,2,3")
        #[arg(short = 'p', long)]
        priority: Option<String>,

        /// Filter by type
        #[arg(long)]
        r#type: Option<IssueType>,

        /// Filter by assignee
        #[arg(long)]
        assignee: Option<String>,

        /// Filter by labels (must have ALL specified labels)
        #[arg(short = 'l', long = "label")]
        labels: Vec<String>,

        /// Filter by specific issue IDs (comma-separated)
        #[arg(long)]
        id: Option<String>,

        /// Filter by title substring (case-insensitive)
        #[arg(long)]
        title: Option<String>,

        /// Maximum number of issues to return
        #[arg(long)]
        limit: Option<usize>,

        /// Group issues by priority with headers
        #[arg(long)]
        group_priority: bool,
    },

    /// Show issue details
    Show {
        /// Issue IDs (supports shorthand: "14" expands to "prefix-14")
        issue_ids: Vec<String>,
    },

    /// Update one or more issues
    Update {
        /// Issue IDs to update
        issue_ids: Vec<String>,

        /// New status
        #[arg(short = 's', long)]
        status: Option<Status>,

        /// New priority
        #[arg(short, long)]
        priority: Option<i32>,

        /// New assignee
        #[arg(short = 'a', long)]
        assignee: Option<String>,

        /// New title
        #[arg(long, allow_hyphen_values = true)]
        title: Option<String>,

        /// New description
        #[arg(short, long, allow_hyphen_values = true)]
        description: Option<String>,

        /// New design notes
        #[arg(long, allow_hyphen_values = true)]
        design: Option<String>,

        /// New acceptance criteria
        #[arg(long, allow_hyphen_values = true)]
        acceptance: Option<String>,

        /// Additional notes
        #[arg(long, allow_hyphen_values = true)]
        notes: Option<String>,

        /// New external reference
        #[arg(long)]
        external_ref: Option<String>,
    },

    /// Close one or more issues
    Close {
        /// Issue IDs to close
        issue_ids: Vec<String>,

        /// Reason for closing
        #[arg(short, long, default_value = "Completed", allow_hyphen_values = true)]
        reason: String,
    },

    /// Reopen closed issues
    Reopen {
        /// Issue IDs to reopen
        issue_ids: Vec<String>,

        /// Reason for reopening
        #[arg(short, long, allow_hyphen_values = true)]
        reason: Option<String>,
    },

    /// Rename an issue ID (minibeads-specific)
    MbRename {
        /// Current issue ID
        old_id: String,

        /// New issue ID
        new_id: String,

        /// Preview changes without applying them
        #[arg(long)]
        dry_run: bool,

        /// Repair broken references (scan all issues and fix stale references)
        #[arg(long)]
        repair: bool,

        /// Also patch code references (requires interactive TTY) (minibeads-specific)
        #[arg(long = "mb-patch-code")]
        mb_patch_code: bool,
    },

    /// Rename the issue prefix for all issues
    RenamePrefix {
        /// New prefix to use
        new_prefix: String,

        /// Preview changes without applying them
        #[arg(long)]
        dry_run: bool,

        /// Force rename even if issues would conflict
        #[arg(long)]
        force: bool,
    },

    /// Manage dependencies
    Dep {
        #[command(subcommand)]
        command: DepCommands,
    },

    /// Get statistics
    Stats,

    /// Get blocked issues
    Blocked,

    /// Export issues to JSONL format
    Export {
        /// Output file path (defaults to stdout)
        #[arg(short = 'o', long)]
        output: Option<PathBuf>,

        /// Use default file output (.beads/issues.jsonl) instead of stdout
        #[arg(long = "mb-output-default")]
        mb_output_default: bool,

        /// Filter by status
        #[arg(long)]
        status: Option<Status>,

        /// Filter by priority
        #[arg(long)]
        priority: Option<i32>,

        /// Filter by type
        #[arg(long)]
        r#type: Option<IssueType>,

        /// Filter by assignee
        #[arg(long)]
        assignee: Option<String>,
    },

    /// Bidirectional sync between markdown and JSONL formats
    Sync {
        /// Path to JSONL file (defaults to .beads/issues.jsonl)
        #[arg(long)]
        jsonl: Option<PathBuf>,

        /// Preview changes without applying them
        #[arg(long)]
        dry_run: bool,

        /// Direction: 'both' (default), 'to-jsonl', or 'to-markdown'
        #[arg(long, default_value = "both")]
        direction: String,
    },

    /// Find ready work (issues with no blockers)
    Ready {
        /// Filter by assignee
        #[arg(short = 'a', long)]
        assignee: Option<String>,

        /// Filter by priority
        #[arg(short, long)]
        priority: Option<i32>,

        /// Maximum number of issues to return
        #[arg(short = 'n', long, default_value = "10")]
        limit: usize,

        /// Sort policy: priority (by priority), oldest (by creation date), hybrid (priority + age)
        #[arg(short = 's', long, default_value = "hybrid")]
        sort: String,
    },

    /// Show quickstart guide
    Quickstart,

    /// Show version information
    #[command(alias = "v")]
    Version,

    /// Migrate between numeric and hash-based IDs (minibeads-specific)
    MbMigrate {
        /// Migration direction: 'hash' (numeric -> hash) or 'numeric' (hash/mixed -> numeric)
        #[arg(long, default_value = "hash")]
        to: String,

        /// Preview changes without applying them
        #[arg(long)]
        dry_run: bool,

        /// Also patch code references (requires interactive TTY) (minibeads-specific)
        #[arg(long = "mb-patch-code")]
        mb_patch_code: bool,

        /// Don't update config-minibeads.yaml (minibeads-specific)
        #[arg(long = "no-change-config")]
        no_change_config: bool,

        /// Repack numeric IDs to fill gaps (e.g., 1,3,5 -> 1,2,3) (minibeads-specific)
        #[arg(long = "repack-contiguous")]
        repack_contiguous: bool,

        /// Starting ID for closed issues when repacking (only valid with --repack-contiguous)
        /// Example: --closed-issue-start=1000 packs open issues as 1,2,3... and closed as 1000,1001,1002...
        #[arg(long = "closed-issue-start")]
        closed_issue_start: Option<u32>,
    },
}

#[derive(Subcommand)]
enum DepCommands {
    /// Add a dependency
    Add {
        /// Issue that has the dependency
        issue_id: String,

        /// Issue that issue_id depends on
        depends_on_id: String,

        /// Dependency type
        #[arg(short = 't', long, default_value = "blocks")]
        r#type: DependencyType,
    },

    /// Remove a dependency
    Remove {
        /// Issue that has the dependency
        issue_id: String,

        /// Issue that issue_id depends on (to remove)
        depends_on_id: String,
    },

    /// Show dependency tree
    Tree {
        /// Issue ID to show tree for (supports shorthand: "14" expands to "prefix-14")
        issue_id: String,

        /// Maximum tree depth to display (safety limit)
        #[arg(short = 'd', long, default_value = "50")]
        max_depth: usize,

        /// Show all paths to nodes (no deduplication for diamond dependencies)
        #[arg(long)]
        show_all_paths: bool,
    },

    /// Detect dependency cycles
    Cycles,
}

/// Print a dependency tree in a visual format
fn print_dependency_tree(node: &types::TreeNode, depth: usize, prefix: &str, is_last: bool) {
    // Print the current node
    let connector = if depth == 0 {
        ""
    } else if is_last {
        "└── "
    } else {
        "├── "
    };

    let dep_type_str = if let Some(ref dt) = node.dep_type {
        format!(" ({})", dt)
    } else {
        String::new()
    };

    let suffix = if node.is_cycle {
        " [CYCLE DETECTED]"
    } else if node.depth_exceeded {
        " [MAX DEPTH EXCEEDED]"
    } else {
        ""
    };

    println!(
        "{}{}{}: {} [{}] (P{}){}{}",
        prefix, connector, node.id, node.title, node.status, node.priority, dep_type_str, suffix
    );

    // Don't recurse if cycle or depth exceeded
    if node.is_cycle || node.depth_exceeded {
        return;
    }

    // Print children
    let child_prefix = if depth == 0 {
        String::new()
    } else if is_last {
        format!("{}    ", prefix)
    } else {
        format!("{}│   ", prefix)
    };

    for (i, child) in node.children.iter().enumerate() {
        let is_last_child = i == node.children.len() - 1;
        print_dependency_tree(child, depth + 1, &child_prefix, is_last_child);
    }
}

fn main() {
    if let Err(e) = run() {
        eprintln!("Error: {:#}", e);
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    let cli = Cli::parse();

    // Extract fields needed for get_storage before matching on cli.command
    // This avoids borrowing issues when we try to call get_storage(mb_beads_dir, db) inside match arms
    let mb_beads_dir = &cli.global_opts.mb_beads_dir;
    let db = &cli.global_opts.db;
    let json = cli.global_opts.json;
    let mb_no_cmd_logging = cli.global_opts.mb_no_cmd_logging;

    match cli.command {
        Commands::Init {
            prefix,
            mb_hash_ids,
        } => {
            // IMPORTANT: init always creates .beads in current directory
            // It does NOT use find_beads_dir() or respect --db/--mb-beads-dir flags
            // This ensures init always initializes in CWD, never in ancestor directories
            if mb_beads_dir.is_some() || db.is_some() {
                eprintln!("Note: 'mb init' always creates .beads/ in current directory");
                eprintln!("      --db and --mb-beads-dir flags are ignored for 'init'");
            }

            let beads_dir = PathBuf::from(".beads");
            let storage = Storage::init(beads_dir, prefix, mb_hash_ids)?;

            // Log command after successful init
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            if !json {
                println!(
                    "Initialized beads database with prefix: {}",
                    storage.get_prefix()?
                );
            }
            Ok(())
        }

        Commands::Create {
            title,
            title_flag,
            priority,
            issue_type,
            description,
            design,
            acceptance,
            assignee,
            label,
            external_ref,
            id,
            deps,
            parent,
            force: _force,
            file,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            // Handle bulk creation from file
            if let Some(_file_path) = file {
                anyhow::bail!(
                    "--file flag not yet implemented. Bulk creation from markdown files coming soon."
                );
            }

            // Determine title from either positional argument or --title flag
            let actual_title = match (title, title_flag) {
                (Some(t), None) => t,
                (None, Some(t)) => t,
                (Some(_), Some(_)) => {
                    anyhow::bail!("Cannot specify both positional title and --title flag");
                }
                (None, None) => {
                    anyhow::bail!("Title is required. Use positional argument or --title flag.");
                }
            };

            // Parse dependencies
            // Supports two formats:
            // 1. Simple: "bd-1,bd-2" (defaults to 'blocks' type)
            // 2. Advanced: "blocks:bd-1,related:bd-2,discovered-from:bd-3"
            let mut parsed_deps = if let Some(deps_str) = deps {
                deps_str
                    .split(',')
                    .filter_map(|s| {
                        let s = s.trim();
                        if s.is_empty() {
                            return None;
                        }

                        // Check if it contains a colon (advanced format)
                        if let Some(colon_idx) = s.find(':') {
                            let (type_str, id) = s.split_at(colon_idx);
                            let id = id[1..].trim(); // Skip the colon

                            // Parse the dependency type
                            match type_str.parse::<DependencyType>() {
                                Ok(dep_type) => Some((id.to_string(), dep_type)),
                                Err(_) => {
                                    eprintln!(
                                        "Warning: Invalid dependency type '{}', skipping '{}'",
                                        type_str, s
                                    );
                                    None
                                }
                            }
                        } else {
                            // Simple format: just the ID, default to Blocks
                            Some((s.to_string(), DependencyType::Blocks))
                        }
                    })
                    .collect()
            } else {
                Vec::new()
            };

            // Add parent as a parent-child dependency if specified
            if let Some(parent_id) = parent {
                parsed_deps.push((parent_id, DependencyType::ParentChild));
            }

            let issue = storage.create_issue(
                actual_title,
                description,
                design,
                acceptance,
                priority,
                issue_type,
                assignee,
                label,
                external_ref,
                id,
                parsed_deps,
            )?;

            if json {
                println!("{}", serde_json::to_string_pretty(&issue)?);
            } else {
                println!("Created issue: {}", issue.id);
            }
            Ok(())
        }

        Commands::List {
            status,
            priority,
            r#type,
            assignee,
            labels,
            id,
            title,
            limit,
            group_priority,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            // Parse comma-separated priorities
            let priority_list = if let Some(priority_str) = priority {
                let priorities: Result<Vec<i32>, _> = priority_str
                    .split(',')
                    .map(|s| s.trim().parse::<i32>())
                    .collect();
                Some(priorities.context("Invalid priority value")?)
            } else {
                None
            };

            let mut issues =
                storage.list_issues(status, priority_list, r#type, assignee.as_deref(), None)?;

            // Apply label filter (must have ALL specified labels)
            if !labels.is_empty() {
                issues.retain(|issue| labels.iter().all(|label| issue.labels.contains(label)));
            }

            // Apply ID filter (comma-separated list of specific IDs)
            if let Some(id_filter) = id {
                let target_ids: Vec<String> =
                    id_filter.split(',').map(|s| s.trim().to_string()).collect();
                issues.retain(|issue| target_ids.contains(&issue.id));
            }

            // Apply title filter (case-insensitive substring match)
            if let Some(title_filter) = title {
                let title_lower = title_filter.to_lowercase();
                issues.retain(|issue| issue.title.to_lowercase().contains(&title_lower));
            }

            // Apply limit if specified
            if let Some(limit_val) = limit {
                issues.truncate(limit_val);
            }

            if json {
                println!("{}", serde_json::to_string_pretty(&issues)?);
            } else if group_priority {
                // Group by priority and display with headers
                use std::collections::BTreeMap;

                // Group issues by priority using BTreeMap for sorted keys
                let mut groups: BTreeMap<i32, Vec<&types::Issue>> = BTreeMap::new();
                for issue in &issues {
                    groups.entry(issue.priority).or_default().push(issue);
                }

                // Display each priority group with header
                for (priority, group_issues) in groups {
                    // Print priority header
                    let header_text = format!("Priority {}", priority);
                    let header_width = 60;
                    let padding = (header_width - header_text.len() - 2) / 2;
                    println!("{}", "=".repeat(header_width));
                    println!(
                        "|{}{}{}|",
                        " ".repeat(padding),
                        header_text,
                        " ".repeat(header_width - padding - header_text.len() - 2)
                    );
                    println!("{}", "=".repeat(header_width));

                    // Print issues in this group (without priority tag)
                    for issue in group_issues {
                        println!("{}: {} [{}]", issue.id, issue.title, issue.status);
                    }
                    println!();
                }
            } else {
                // Standard output
                for issue in issues {
                    println!(
                        "{}: {} [{}] (priority: {})",
                        issue.id, issue.title, issue.status, issue.priority
                    );
                }
            }
            Ok(())
        }

        Commands::Show { issue_ids } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            if issue_ids.is_empty() {
                anyhow::bail!("No issue IDs provided. Usage: mb show <issue-id> [issue-ids...]");
            }

            let prefix = storage.get_prefix()?;
            let mut issues = Vec::new();

            // Normalize issue IDs (expand numeric shorthand like "14" -> "prefix-14")
            for id_str in &issue_ids {
                let normalized_id = if id_str.parse::<u32>().is_ok() {
                    format!("{}-{}", prefix, id_str)
                } else {
                    id_str.clone()
                };

                let issue = storage
                    .get_issue(&normalized_id)?
                    .ok_or_else(|| anyhow::anyhow!("Issue not found: {}", normalized_id))?;
                issues.push(issue);
            }

            if json {
                println!("{}", serde_json::to_string_pretty(&issues)?);
            } else {
                for (idx, issue) in issues.iter().enumerate() {
                    if idx > 0 {
                        println!("\n{}", "=".repeat(70));
                        println!();
                    }

                    println!("ID: {}", issue.id);
                    println!("Title: {}", issue.title);
                    println!("Status: {}", issue.status);
                    println!("Priority: {}", issue.priority);
                    println!("Type: {}", issue.issue_type);
                    if !issue.assignee.is_empty() {
                        println!("Assignee: {}", issue.assignee);
                    }
                    if !issue.description.is_empty() {
                        println!("\nDescription:\n{}", issue.description);
                    }
                    if !issue.depends_on.is_empty() {
                        println!("\nDependencies:");
                        for (dep_id, dep_type) in &issue.depends_on {
                            println!("  {} ({})", dep_id, dep_type);
                        }
                    }
                }
            }
            Ok(())
        }

        Commands::Update {
            issue_ids,
            status,
            priority,
            assignee,
            title,
            description,
            design,
            acceptance,
            notes,
            external_ref,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            let mut updates = HashMap::new();
            if let Some(s) = status {
                updates.insert("status".to_string(), s.to_string());
            }
            if let Some(p) = priority {
                updates.insert("priority".to_string(), p.to_string());
            }
            if let Some(a) = assignee {
                updates.insert("assignee".to_string(), a);
            }
            if let Some(t) = title {
                updates.insert("title".to_string(), t);
            }
            if let Some(d) = description {
                updates.insert("description".to_string(), d);
            }
            if let Some(d) = design {
                updates.insert("design".to_string(), d);
            }
            if let Some(a) = acceptance {
                updates.insert("acceptance_criteria".to_string(), a);
            }
            if let Some(n) = notes {
                updates.insert("notes".to_string(), n);
            }
            if let Some(e) = external_ref {
                updates.insert("external_ref".to_string(), e);
            }

            // Update all specified issues
            let mut updated_issues = Vec::new();
            for issue_id in &issue_ids {
                let issue = storage.update_issue(issue_id, updates.clone())?;
                updated_issues.push(issue);
            }

            if json {
                println!("{}", serde_json::to_string_pretty(&updated_issues)?);
            } else {
                for issue in &updated_issues {
                    println!("Updated issue: {}", issue.id);
                }
            }
            Ok(())
        }

        Commands::Close { issue_ids, reason } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            // Close all specified issues
            let mut closed_issues = Vec::new();
            for issue_id in &issue_ids {
                let issue = storage.close_issue(issue_id, &reason)?;
                closed_issues.push(issue);
            }

            if json {
                println!("{}", serde_json::to_string_pretty(&closed_issues)?);
            } else {
                for issue in &closed_issues {
                    println!("Closed issue: {}", issue.id);
                }
            }
            Ok(())
        }

        Commands::Reopen {
            issue_ids,
            reason: _,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            let mut reopened = Vec::new();

            for issue_id in issue_ids {
                let issue = storage.reopen_issue(&issue_id)?;
                reopened.push(issue);
            }

            if json {
                println!("{}", serde_json::to_string_pretty(&reopened)?);
            } else {
                for issue in reopened {
                    println!("Reopened issue: {}", issue.id);
                }
            }
            Ok(())
        }

        Commands::MbRename {
            old_id,
            new_id,
            dry_run,
            repair,
            mb_patch_code,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            if repair {
                // Repair mode: scan all issues and fix broken references
                let changes = storage.repair_references(dry_run)?;

                if json {
                    println!("{}", serde_json::to_string_pretty(&changes)?);
                } else if dry_run {
                    println!("Dry run - would make the following changes:");
                    for change in &changes {
                        println!("  {}", change);
                    }
                } else if changes.len() == 1 && changes[0] == "No broken references found" {
                    println!("No broken references found");
                } else {
                    println!("Repaired {} broken reference(s)", changes.len());
                    for change in &changes {
                        println!("  {}", change);
                    }
                }
            } else {
                // Rename mode
                let changes = storage.rename_issue(&old_id, &new_id, dry_run)?;

                if json {
                    println!("{}", serde_json::to_string_pretty(&changes)?);
                } else if dry_run {
                    println!("Dry run - would make the following changes:");
                    for change in &changes {
                        println!("  {}", change);
                    }
                } else {
                    println!("Successfully renamed {} to {}", old_id, new_id);
                    if changes.len() > 2 {
                        println!("Updated {} file(s) with references", changes.len() - 2);
                    }

                    // Patch code references if requested
                    if mb_patch_code {
                        if let Err(e) = code_patch::patch_code_for_rename(&old_id, &new_id) {
                            eprintln!("Warning: Code patching failed: {}", e);
                        }
                    }
                }
            }
            Ok(())
        }

        Commands::RenamePrefix {
            new_prefix,
            dry_run,
            force,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            let changes = storage.rename_prefix(&new_prefix, dry_run, force)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&changes)?);
            } else if dry_run {
                println!("Dry run - would make the following changes:");
                for change in &changes {
                    println!("  {}", change);
                }
            } else {
                println!("Successfully renamed prefix to '{}'", new_prefix);
                println!("Renamed {} issue(s)", changes.len() / 2); // Each issue has 2 changes: file rename + content update
            }
            Ok(())
        }

        Commands::Dep { command } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            match command {
                DepCommands::Add {
                    issue_id,
                    depends_on_id,
                    r#type,
                } => {
                    storage.add_dependency(&issue_id, &depends_on_id, r#type)?;

                    if !json {
                        println!(
                            "Added dependency: {} depends on {} ({})",
                            issue_id, depends_on_id, r#type
                        );
                    }
                }
                DepCommands::Remove {
                    issue_id,
                    depends_on_id,
                } => {
                    storage.remove_dependency(&issue_id, &depends_on_id)?;

                    if !json {
                        println!(
                            "Removed dependency: {} no longer depends on {}",
                            issue_id, depends_on_id
                        );
                    }
                }
                DepCommands::Tree {
                    issue_id,
                    max_depth,
                    show_all_paths,
                } => {
                    let tree = storage.get_dependency_tree(&issue_id, max_depth, show_all_paths)?;

                    if json {
                        println!("{}", serde_json::to_string_pretty(&tree)?);
                    } else {
                        print_dependency_tree(&tree, 0, "", true);
                    }
                }
                DepCommands::Cycles => {
                    let cycles = storage.detect_dependency_cycles()?;

                    if json {
                        println!("{}", serde_json::to_string_pretty(&cycles)?);
                    } else if cycles.is_empty() {
                        println!("No dependency cycles detected.");
                    } else {
                        println!("Found {} dependency cycle(s):\n", cycles.len());
                        for (i, cycle) in cycles.iter().enumerate() {
                            println!("Cycle {}:", i + 1);
                            for (j, issue_id) in cycle.iter().enumerate() {
                                if j == cycle.len() - 1 {
                                    println!("  {} -> {} (completes cycle)", issue_id, cycle[0]);
                                } else {
                                    println!("  {} ->", issue_id);
                                }
                            }
                            println!();
                        }
                    }
                }
            }
            Ok(())
        }

        Commands::Stats => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            let stats = storage.get_stats()?;

            if json {
                println!("{}", serde_json::to_string_pretty(&stats)?);
            } else {
                println!("Total issues: {}", stats.total_issues);
                println!("Open: {}", stats.open_issues);
                println!("In Progress: {}", stats.in_progress_issues);
                println!("Blocked: {}", stats.blocked_issues);
                println!("Closed: {}", stats.closed_issues);
                println!("Ready: {}", stats.ready_issues);
                println!(
                    "Average lead time: {:.1} hours",
                    stats.average_lead_time_hours
                );
            }
            Ok(())
        }

        Commands::Blocked => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            let blocked = storage.get_blocked()?;

            if json {
                println!("{}", serde_json::to_string_pretty(&blocked)?);
            } else {
                for item in blocked {
                    println!(
                        "{}: {} - blocked by: {}",
                        item.issue.id,
                        item.issue.title,
                        item.blocked_by.join(", ")
                    );
                }
            }
            Ok(())
        }

        Commands::Export {
            output,
            mb_output_default,
            status,
            priority,
            r#type,
            assignee,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            // Determine output destination
            if let Some(path) = output {
                // -o flag provided: write to specified file
                let count = storage.export_to_jsonl(
                    &path,
                    status,
                    priority,
                    r#type,
                    assignee.as_deref(),
                )?;
                eprintln!("Exported {} issues to {}", count, path.display());
            } else if mb_output_default {
                // --mb-output-default: write to .beads/issues.jsonl
                let path = storage.get_beads_dir().join("issues.jsonl");
                let count = storage.export_to_jsonl(
                    &path,
                    status,
                    priority,
                    r#type,
                    assignee.as_deref(),
                )?;
                eprintln!("Exported {} issues to {}", count, path.display());
            } else {
                // Default: write to stdout (matching upstream bd)
                // Convert single priority to vector for list_issues
                let priority_list = priority.map(|p| vec![p]);
                let issues = storage.list_issues(
                    status,
                    priority_list,
                    r#type,
                    assignee.as_deref(),
                    None,
                )?;
                for issue in &issues {
                    let json = serde_json::to_string(&issue)?;
                    println!("{}", json);
                }
            }
            Ok(())
        }

        Commands::Sync {
            jsonl,
            dry_run,
            direction,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            let beads_dir = storage.get_beads_dir();
            let jsonl_path = jsonl.unwrap_or_else(|| beads_dir.join("issues.jsonl"));

            // Load issues from both sources
            let markdown_issues = sync::load_markdown_issues(&beads_dir)?;
            let jsonl_issues = sync::load_jsonl_issues(&jsonl_path)?;

            // Create sync engine and analyze
            let engine = sync::SyncEngine::new();
            let plan = engine.analyze(markdown_issues.clone(), jsonl_issues.clone())?;

            // Filter plan based on direction
            let filtered_plan = match direction.as_str() {
                "both" => plan,
                "to-jsonl" => sync::SyncPlan {
                    markdown_only: plan.markdown_only,
                    jsonl_only: Vec::new(),
                    markdown_newer: plan.markdown_newer,
                    jsonl_newer: Vec::new(),
                    no_change: plan.no_change,
                    conflicts: plan.conflicts,
                },
                "to-markdown" => sync::SyncPlan {
                    markdown_only: Vec::new(),
                    jsonl_only: plan.jsonl_only,
                    markdown_newer: Vec::new(),
                    jsonl_newer: plan.jsonl_newer,
                    no_change: plan.no_change,
                    conflicts: plan.conflicts,
                },
                _ => {
                    anyhow::bail!(
                        "Invalid direction '{}'. Use 'both', 'to-jsonl', or 'to-markdown'",
                        direction
                    );
                }
            };

            // Report plan
            if !json && !filtered_plan.is_empty() {
                println!("Sync plan:");
                if !filtered_plan.markdown_only.is_empty() {
                    println!("  Create in JSONL ({}):", filtered_plan.markdown_only.len());
                    for id in &filtered_plan.markdown_only {
                        println!("    {}", id);
                    }
                }
                if !filtered_plan.jsonl_only.is_empty() {
                    println!("  Create in markdown ({}):", filtered_plan.jsonl_only.len());
                    for id in &filtered_plan.jsonl_only {
                        println!("    {}", id);
                    }
                }
                if !filtered_plan.markdown_newer.is_empty() {
                    println!(
                        "  Update JSONL from markdown ({}):",
                        filtered_plan.markdown_newer.len()
                    );
                    for id in &filtered_plan.markdown_newer {
                        println!("    {}", id);
                    }
                }
                if !filtered_plan.jsonl_newer.is_empty() {
                    println!(
                        "  Update markdown from JSONL ({}):",
                        filtered_plan.jsonl_newer.len()
                    );
                    for id in &filtered_plan.jsonl_newer {
                        println!("    {}", id);
                    }
                }
                if !filtered_plan.conflicts.is_empty() {
                    println!("  Conflicts ({}):", filtered_plan.conflicts.len());
                    for id in &filtered_plan.conflicts {
                        println!("    {}", id);
                    }
                }
                println!();
            }

            // Apply sync
            let report = engine.apply(
                &filtered_plan,
                &markdown_issues,
                &jsonl_issues,
                &beads_dir,
                dry_run,
            )?;

            // Report results
            if json {
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                if dry_run {
                    println!("[DRY RUN] Would make {} changes", report.total_changes());
                } else {
                    println!("Sync complete: {} changes applied", report.total_changes());
                }
                if report.created_in_jsonl > 0 {
                    println!("  Created in JSONL: {}", report.created_in_jsonl);
                }
                if report.created_in_markdown > 0 {
                    println!("  Created in markdown: {}", report.created_in_markdown);
                }
                if report.updated_jsonl > 0 {
                    println!("  Updated JSONL: {}", report.updated_jsonl);
                }
                if report.updated_markdown > 0 {
                    println!("  Updated markdown: {}", report.updated_markdown);
                }
                if report.skipped_conflicts > 0 {
                    println!("  Skipped conflicts: {}", report.skipped_conflicts);
                }
                if !report.errors.is_empty() {
                    println!("\nErrors:");
                    for error in &report.errors {
                        println!("  {}", error);
                    }
                }
            }
            Ok(())
        }

        Commands::Ready {
            assignee,
            priority,
            limit,
            sort,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            // Validate sort policy
            let sort_policy = match sort.as_str() {
                "priority" | "oldest" | "hybrid" => sort.as_str(),
                _ => {
                    eprintln!("Warning: Invalid sort policy '{}', using 'hybrid'", sort);
                    "hybrid"
                }
            };

            let ready = storage.get_ready(assignee.as_deref(), priority, limit, sort_policy)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&ready)?);
            } else {
                for issue in ready {
                    println!(
                        "{}: {} [priority: {}]",
                        issue.id, issue.title, issue.priority
                    );
                }
            }
            Ok(())
        }

        Commands::Quickstart => {
            print_quickstart();
            Ok(())
        }

        Commands::Version => {
            println!("mb version 0.12.0");
            Ok(())
        }

        Commands::MbMigrate {
            to,
            dry_run,
            mb_patch_code,
            no_change_config,
            repack_contiguous,
            closed_issue_start,
        } => {
            let storage = get_storage(mb_beads_dir, db)?;

            // Log command after storage is validated
            if !mb_no_cmd_logging {
                let _ = log_command(&storage.get_beads_dir(), &env::args().collect::<Vec<_>>());
            }

            // Validate that --closed-issue-start is only valid with --repack-contiguous
            if closed_issue_start.is_some() && !repack_contiguous {
                anyhow::bail!("--closed-issue-start is only valid with --repack-contiguous");
            }

            // Handle --repack-contiguous separately (fills gaps in numeric IDs)
            if repack_contiguous {
                let (changes, id_mapping) =
                    storage.repack_numeric_ids(dry_run, closed_issue_start)?;

                if json {
                    println!("{}", serde_json::to_string_pretty(&changes)?);
                } else if dry_run {
                    println!("Dry run - would make the following changes:");
                    for change in &changes {
                        println!("  {}", change);
                    }
                } else {
                    let issue_count = changes
                        .iter()
                        .filter(|c| c.starts_with("Rename file:"))
                        .count();
                    if issue_count > 0 {
                        println!(
                            "Successfully repacked {} issue(s) to fill gaps",
                            issue_count
                        );

                        // Patch code references if requested
                        if mb_patch_code {
                            if let Err(e) = code_patch::patch_code_for_migration(&id_mapping) {
                                eprintln!("Warning: Code patching failed: {}", e);
                            }
                        }
                    } else {
                        // No changes made
                        for change in &changes {
                            println!("{}", change);
                        }
                    }
                }
                return Ok(());
            }

            match to.as_str() {
                "hash" => {
                    let update_config = !no_change_config;
                    let (changes, id_mapping) =
                        storage.migrate_to_hash_ids(dry_run, update_config)?;

                    if json {
                        println!("{}", serde_json::to_string_pretty(&changes)?);
                    } else if dry_run {
                        println!("Dry run - would make the following changes:");
                        for change in &changes {
                            println!("  {}", change);
                        }
                    } else {
                        println!(
                            "Successfully migrated {} issue(s) to hash-based IDs",
                            changes.len() / 3
                        );
                        if update_config {
                            println!("Updated config-minibeads.yaml: mb-hash-ids: true");
                        }

                        // Patch code references if requested
                        if mb_patch_code {
                            if let Err(e) = code_patch::patch_code_for_migration(&id_mapping) {
                                eprintln!("Warning: Code patching failed: {}", e);
                            }
                        }
                    }
                }
                "numeric" => {
                    let update_config = !no_change_config;
                    let (changes, id_mapping) =
                        storage.migrate_to_numeric_ids(dry_run, update_config)?;

                    if json {
                        println!("{}", serde_json::to_string_pretty(&changes)?);
                    } else if dry_run {
                        println!("Dry run - would make the following changes:");
                        for change in &changes {
                            println!("  {}", change);
                        }
                    } else {
                        let issue_count = changes
                            .iter()
                            .filter(|c| c.starts_with("Rename file:"))
                            .count();
                        println!(
                            "Successfully migrated {} issue(s) to numeric IDs",
                            issue_count
                        );
                        if update_config {
                            println!("Updated config-minibeads.yaml: mb-hash-ids: false");
                        }

                        // Patch code references if requested
                        if mb_patch_code {
                            if let Err(e) = code_patch::patch_code_for_migration(&id_mapping) {
                                eprintln!("Warning: Code patching failed: {}", e);
                            }
                        }
                    }
                }
                _ => {
                    anyhow::bail!(
                        "Invalid migration target '{}'. Use '--to=hash' or '--to=numeric'",
                        to
                    );
                }
            }
            Ok(())
        }
    }
}

fn get_storage(mb_beads_dir: &Option<PathBuf>, db: &Option<PathBuf>) -> Result<Storage> {
    // Priority order for determining .beads directory:
    // 1. --mb-beads-dir flag (preferred, minibeads-specific)
    // 2. --db flag (for upstream compatibility, treated as syntactic sugar for BEADS_DIR)
    // 3. MB_BEADS_DIR environment variable (minibeads-specific)
    // 4. BEADS_DB environment variable (for upstream compatibility)
    // 5. Search for .beads in current directory and ancestors

    let beads_dir = if let Some(dir) = mb_beads_dir {
        // --mb-beads-dir: use directly
        dir.clone()
    } else if let Some(db_path) = db {
        // --db: syntactic sugar for BEADS_DIR
        // If it points to a .db file, use its parent directory
        if db_path.extension().is_some_and(|e| e == "db") {
            db_path
                .parent()
                .ok_or_else(|| anyhow::anyhow!("Invalid database path"))?
                .to_path_buf()
        } else {
            db_path.clone()
        }
    } else if let Ok(beads_dir) = env::var("MB_BEADS_DIR") {
        PathBuf::from(beads_dir)
    } else if let Ok(beads_db) = env::var("BEADS_DB") {
        let db_path = PathBuf::from(beads_db);
        if db_path.extension().is_some_and(|e| e == "db") {
            db_path
                .parent()
                .ok_or_else(|| anyhow::anyhow!("Invalid BEADS_DB path"))?
                .to_path_buf()
        } else {
            db_path
        }
    } else {
        // Search for .beads directory
        find_beads_dir()?
    };

    Storage::open(beads_dir).context("Failed to open storage")
}

fn find_beads_dir() -> Result<PathBuf> {
    let mut current = env::current_dir()?;

    loop {
        let beads_dir = current.join(".beads");
        if beads_dir.exists() && beads_dir.is_dir() {
            return Ok(beads_dir);
        }

        if !current.pop() {
            anyhow::bail!("No .beads directory found. Run 'mb init' to initialize a new database.");
        }
    }
}

/// Log command to command_history.log
fn log_command(beads_dir: &Path, args: &[String]) -> Result<()> {
    use std::fs::OpenOptions;
    use std::io::Write;

    let log_path = beads_dir.join("command_history.log");
    let timestamp = chrono::Utc::now().to_rfc3339();

    // Skip the first argument (binary path) and quote each CLI argument
    let command_line = if args.len() > 1 {
        args[1..]
            .iter()
            .map(|arg| format!("\"{}\"", arg))
            .collect::<Vec<_>>()
            .join(" ")
    } else {
        String::new()
    };

    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)
        .context("Failed to open command history log")?;

    writeln!(file, "<<BD_INVOKE>> {} {}", timestamp, command_line)
        .context("Failed to write to command history log")?;

    Ok(())
}

fn print_quickstart() {
    println!(
        r#"mb - Dependency-Aware Issue Tracker

Issues chained together like beads (minibeads).

GETTING STARTED
  mb init   Initialize mb in your project
            Creates .beads/ directory with project-specific database
            Auto-detects prefix from directory name (e.g., myapp-1, myapp-2)

  mb init --prefix api   Initialize with custom prefix
            Issues will be named: api-1, api-2, ...

CREATING ISSUES
  mb create "Fix login bug"
  mb create "Add auth" -p 0 -t feature
  mb create "Write tests" -d "Unit tests for auth" --assignee alice

VIEWING ISSUES
  mb list       List all issues
  mb list --status open  List by status
  mb list --priority 0  List by priority (0-4, 0=highest)
  mb show myapp-1       Show issue details

MANAGING DEPENDENCIES
  mb dep add myapp-1 myapp-2     Add dependency (myapp-2 blocks myapp-1)

DEPENDENCY TYPES
  blocks  Task B must complete before task A
  related  Soft connection, doesn't block progress
  parent-child  Epic/subtask hierarchical relationship
  discovered-from  Auto-created when AI discovers related work

READY WORK
  mb ready       Show issues ready to work on
            Ready = status is 'open' AND no blocking dependencies
            Perfect for agents to claim next work!

UPDATING ISSUES
  mb update myapp-1 --status in_progress
  mb update myapp-1 --priority 0
  mb update myapp-1 --assignee bob

CLOSING ISSUES
  mb close myapp-1
  mb close myapp-1 --reason "Fixed in PR #42"

DATABASE LOCATION
  mb automatically discovers your database in this priority order:
    1. --mb-beads-dir /path/to/.beads   (minibeads-specific, preferred)
    2. --db /path/to/.beads             (upstream compatibility)
    3. $MB_BEADS_DIR environment variable
    4. $BEADS_DB environment variable   (upstream compatibility)
    5. .beads/ in current directory or ancestors

  Note: --db is treated as syntactic sugar for specifying BEADS_DIR.
        When path ends with .db, the parent directory is used.
        Use --mb-beads-dir for minibeads-specific workflows.

COMPATIBILITY NOTE
  The binary is named 'mb' (minibeads) to distinguish it from upstream 'bd'.
  You can symlink 'mb' to 'bd' if needed for compatibility with existing tools.

Ready to start!
Run mb create "My first issue" to create your first issue.
"#
    );
}