beads_rust 0.2.12

Agent-first issue tracker (SQLite + JSONL)
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
//! Comprehensive git safety regression tests for the full br CLI.
//!
//! This test suite implements beads_rust-k1px:
//! - E2E assertions that NO br command invokes git operations or touches .git
//! - Run representative commands across the full CLI surface
//! - Validate .git tree is unchanged after each command batch
//! - Fail fast with artifact diff if any command touches .git
//!
//! Unlike `e2e_sync_git_safety.rs` (which focuses on sync), this tests ALL commands.

#![allow(
    clippy::items_after_statements,
    clippy::too_many_lines,
    clippy::cognitive_complexity
)]

mod common;

use common::cli::{BrWorkspace, run_br};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::process::Command;

/// Compute SHA256 hash of a file.
fn hash_file(path: &Path) -> Option<String> {
    fs::read(path).ok().map(|contents| {
        let mut hasher = Sha256::new();
        hasher.update(&contents);
        beads_rust::util::hex_encode(&hasher.finalize())
    })
}

/// Recursively collect file hashes from a directory.
fn collect_dir_hashes(dir: &Path, base: &Path, hashes: &mut BTreeMap<String, String>) {
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            let rel_path = path
                .strip_prefix(base)
                .unwrap_or(&path)
                .to_string_lossy()
                .to_string();

            if path.is_file() {
                if let Some(hash) = hash_file(&path) {
                    hashes.insert(rel_path, hash);
                }
            } else if path.is_dir() {
                collect_dir_hashes(&path, base, hashes);
            }
        }
    }
}

/// Snapshot the .git directory.
fn snapshot_git_dir(root: &Path) -> BTreeMap<String, String> {
    let mut hashes = BTreeMap::new();
    let git_dir = root.join(".git");
    if git_dir.exists() {
        collect_dir_hashes(&git_dir, &git_dir, &mut hashes);
    }
    hashes
}

/// Filter out transient git files that can change during normal operations.
fn filter_transient_git_files(hashes: &BTreeMap<String, String>) -> BTreeMap<String, String> {
    hashes
        .iter()
        .filter(|(k, _)| {
            let is_lock = Path::new(k)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("lock"));
            !is_lock
                && !k.contains("index")
                && !k.contains("FETCH_HEAD")
                && !k.contains("ORIG_HEAD")
                && !k.contains("logs/") // reflog can be written during reads in some git versions
        })
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect()
}

/// Get HEAD commit hash.
fn get_head_commit(root: &Path) -> Option<String> {
    Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(root)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

/// Get commit count.
fn get_commit_count(root: &Path) -> usize {
    Command::new("git")
        .args(["rev-list", "--count", "HEAD"])
        .current_dir(root)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map_or(0, |o| {
            String::from_utf8_lossy(&o.stdout)
                .trim()
                .parse()
                .unwrap_or(0)
        })
}

/// Initialize a git repo with an initial commit.
fn init_git_repo(workspace: &BrWorkspace) {
    let init = Command::new("git")
        .args(["init"])
        .current_dir(&workspace.root)
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");

    let _ = Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(&workspace.root)
        .output();
    let _ = Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(&workspace.root)
        .output();

    // Create source files
    let src_dir = workspace.root.join("src");
    fs::create_dir_all(&src_dir).expect("create src dir");
    fs::write(
        src_dir.join("main.rs"),
        "fn main() { println!(\"Hello\"); }",
    )
    .expect("write main.rs");
    fs::write(
        workspace.root.join("Cargo.toml"),
        "[package]\nname = \"test\"\nversion = \"0.1.0\"\n",
    )
    .expect("write Cargo.toml");
    fs::write(workspace.root.join("README.md"), "# Test Project\n").expect("write README");

    // Initial commit
    let _ = Command::new("git")
        .args(["add", "."])
        .current_dir(&workspace.root)
        .output();
    let commit = Command::new("git")
        .args(["commit", "-m", "Initial commit"])
        .current_dir(&workspace.root)
        .output()
        .expect("git commit");
    assert!(commit.status.success(), "initial commit failed");
}

/// Git safety check result.
#[derive(Debug)]
struct GitSafetyCheck {
    #[allow(dead_code)]
    command: String,
    passed: bool,
    violations: Vec<String>,
    #[allow(dead_code)]
    head_changed: bool,
    #[allow(dead_code)]
    commit_count_changed: bool,
}

impl GitSafetyCheck {
    fn new(command: &str) -> Self {
        Self {
            command: command.to_string(),
            passed: true,
            violations: Vec::new(),
            head_changed: false,
            commit_count_changed: false,
        }
    }

    fn add_violation(&mut self, msg: &str) {
        self.violations.push(msg.to_string());
        self.passed = false;
    }
}

/// Verify .git is unchanged between snapshots.
fn verify_git_unchanged(
    before: &BTreeMap<String, String>,
    after: &BTreeMap<String, String>,
    head_before: Option<&String>,
    head_after: Option<&String>,
    count_before: usize,
    count_after: usize,
    command: &str,
) -> GitSafetyCheck {
    let mut check = GitSafetyCheck::new(command);

    // Check HEAD didn't change
    if head_before != head_after {
        check.head_changed = true;
        check.add_violation(&format!("HEAD changed: {head_before:?} -> {head_after:?}"));
    }

    // Check commit count didn't change
    if count_before != count_after {
        check.commit_count_changed = true;
        check.add_violation(&format!(
            "Commit count changed: {count_before} -> {count_after}"
        ));
    }

    // Filter transient files
    let before_filtered = filter_transient_git_files(before);
    let after_filtered = filter_transient_git_files(after);

    // Check for new files
    for path in after_filtered.keys() {
        if !before_filtered.contains_key(path) {
            check.add_violation(&format!("New file in .git/: {path}"));
        }
    }

    // Check for modified files
    for (path, hash_before) in &before_filtered {
        if let Some(hash_after) = after_filtered.get(path)
            && hash_before != hash_after
        {
            check.add_violation(&format!("Modified file in .git/: {path}"));
        }
    }

    // Check for deleted files
    for path in before_filtered.keys() {
        if !after_filtered.contains_key(path) {
            check.add_violation(&format!("Deleted file from .git/: {path}"));
        }
    }

    check
}

/// Macro to run a command and verify git safety.
macro_rules! check_git_safety {
    ($workspace:expr, $before:expr, $head_before:expr, $count_before:expr, $args:expr, $label:expr) => {{
        let result = run_br($workspace, $args, $label);
        let after = snapshot_git_dir(&$workspace.root);
        let head_after = get_head_commit(&$workspace.root);
        let count_after = get_commit_count(&$workspace.root);

        let check = verify_git_unchanged(
            &$before,
            &after,
            $head_before.as_ref(),
            head_after.as_ref(),
            $count_before,
            count_after,
            $label,
        );

        assert!(
            check.passed,
            "GIT SAFETY VIOLATION in '{}' command:\n{}\nstdout: {}\nstderr: {}",
            $label,
            check.violations.join("\n"),
            result.stdout,
            result.stderr
        );

        // Update for next check
        (after, head_after, count_after, result)
    }};
}

/// Main test: verify all CLI commands don't touch .git
#[test]
fn regression_full_cli_does_not_touch_git() {
    let workspace = BrWorkspace::new();

    // Initialize git repo
    init_git_repo(&workspace);

    // Take baseline snapshot
    let baseline_git = snapshot_git_dir(&workspace.root);
    let baseline_head = get_head_commit(&workspace.root);
    let baseline_count = get_commit_count(&workspace.root);

    eprintln!(
        "Baseline: {} git files, HEAD={:?}, {} commits",
        baseline_git.len(),
        baseline_head,
        baseline_count
    );

    // ========================================================================
    // PHASE 1: Initialization & workspace commands
    // ========================================================================
    eprintln!("\n[PHASE 1] Testing initialization & workspace commands...");

    // init
    let (git_snap, head, count, init_result) = check_git_safety!(
        &workspace,
        baseline_git,
        baseline_head,
        baseline_count,
        ["init"],
        "init"
    );
    assert!(init_result.status.success(), "init failed");

    // version (read-only)
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["version"], "version");

    // version --json
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["version", "--json"],
        "version_json"
    );

    // where (read-only)
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["where"], "where");

    // info (read-only)
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["info"], "info");

    // doctor (read-only diagnostics)
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["doctor"], "doctor");

    // ========================================================================
    // PHASE 2: Issue CRUD operations
    // ========================================================================
    eprintln!("\n[PHASE 2] Testing issue CRUD operations...");

    // create (with --no-auto-flush to isolate the command)
    let (git_snap, head, count, create1) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        [
            "create",
            "Test issue 1",
            "-p",
            "1",
            "-t",
            "task",
            "--no-auto-flush"
        ],
        "create1"
    );
    assert!(create1.status.success(), "create1 failed");
    let id1 = create1
        .stdout
        .lines()
        .next()
        .and_then(|l| l.strip_prefix("Created "))
        .and_then(|l| l.split(':').next())
        .unwrap_or("")
        .trim()
        .to_string();

    // create with description
    let (git_snap, head, count, create2) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        [
            "create",
            "Test issue 2",
            "-d",
            "Description here",
            "-t",
            "bug",
            "--no-auto-flush"
        ],
        "create2"
    );
    let id2 = create2
        .stdout
        .lines()
        .next()
        .and_then(|l| l.strip_prefix("Created "))
        .and_then(|l| l.split(':').next())
        .unwrap_or("")
        .trim()
        .to_string();

    // q (quick capture)
    let (git_snap, head, count, q_result) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["q", "Quick issue", "--no-auto-flush"],
        "quick_capture"
    );
    let id3 = q_result.stdout.trim().to_string();

    // list
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["list"], "list");

    // list --json
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["list", "--json"],
        "list_json"
    );

    // show
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["show", &id1], "show");

    // show --json
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["show", &id1, "--json"],
        "show_json"
    );

    // update
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["update", &id1, "--priority", "0", "--no-auto-flush"],
        "update"
    );

    // update status
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["update", &id1, "--status", "in_progress", "--no-auto-flush"],
        "update_status"
    );

    // ========================================================================
    // PHASE 3: Queries and filters
    // ========================================================================
    eprintln!("\n[PHASE 3] Testing queries and filters...");

    // ready
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["ready"], "ready");

    // ready --json
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["ready", "--json"],
        "ready_json"
    );

    // blocked
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["blocked"], "blocked");

    // search
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["search", "Test"],
        "search"
    );

    // count
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["count"], "count");

    // count --by status
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["count", "--by", "status"],
        "count_by_status"
    );

    // stats
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["stats"], "stats");

    // stale
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["stale"], "stale");

    // ========================================================================
    // PHASE 4: Dependencies
    // ========================================================================
    eprintln!("\n[PHASE 4] Testing dependency management...");

    // dep add
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["dep", "add", &id1, &id2, "--no-auto-flush"],
        "dep_add"
    );

    // dep list
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["dep", "list", &id1],
        "dep_list"
    );

    // dep tree
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["dep", "tree", &id1],
        "dep_tree"
    );

    // dep cycles
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["dep", "cycles"],
        "dep_cycles"
    );

    // dep remove
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["dep", "remove", &id1, &id2, "--no-auto-flush"],
        "dep_remove"
    );

    // dep relate (soft relation)
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["dep", "relate", &id1, &id3, "--no-auto-flush"],
        "dep_relate"
    );

    // dep unrelate
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["dep", "unrelate", &id1, &id3, "--no-auto-flush"],
        "dep_unrelate"
    );

    // ========================================================================
    // PHASE 5: Labels
    // ========================================================================
    eprintln!("\n[PHASE 5] Testing label management...");

    // label add
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["label", "add", &id1, "priority", "--no-auto-flush"],
        "label_add"
    );

    // label list
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["label", "list", &id1],
        "label_list"
    );

    // label remove
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["label", "remove", &id1, "priority", "--no-auto-flush"],
        "label_remove"
    );

    // ========================================================================
    // PHASE 6: Comments
    // ========================================================================
    eprintln!("\n[PHASE 6] Testing comments...");

    // comments add with --message flag
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        [
            "comments",
            "add",
            &id1,
            "--message",
            "This is a test comment",
            "--author",
            "test",
            "--no-auto-flush"
        ],
        "comments_add"
    );

    // comments list
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["comments", "list", &id1],
        "comments_list"
    );

    // ========================================================================
    // PHASE 7: Defer/Undefer
    // ========================================================================
    eprintln!("\n[PHASE 7] Testing defer/undefer...");

    // defer
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["defer", &id3, "--days", "7", "--no-auto-flush"],
        "defer"
    );

    // undefer
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["undefer", &id3, "--no-auto-flush"],
        "undefer"
    );

    // ========================================================================
    // PHASE 8: Config
    // ========================================================================
    eprintln!("\n[PHASE 8] Testing config...");

    // config list
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["config", "--list"],
        "config_list"
    );

    // config get
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["config", "--get", "id.prefix"],
        "config_get"
    );

    // ========================================================================
    // PHASE 9: Graph
    // ========================================================================
    eprintln!("\n[PHASE 9] Testing graph...");

    // graph
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["graph"], "graph");

    // graph --json
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["graph", "--json"],
        "graph_json"
    );

    // ========================================================================
    // PHASE 10: Saved queries
    // ========================================================================
    eprintln!("\n[PHASE 10] Testing saved queries...");

    // query add
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["query", "add", "open-bugs", "status:open type:bug"],
        "query_add"
    );

    // query list
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["query", "list"],
        "query_list"
    );

    // query run
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["query", "run", "open-bugs"],
        "query_run"
    );

    // query delete
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["query", "delete", "open-bugs"],
        "query_delete"
    );

    // ========================================================================
    // PHASE 11: History
    // ========================================================================
    eprintln!("\n[PHASE 11] Testing history...");

    // history list
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["history", "list"],
        "history_list"
    );

    // ========================================================================
    // PHASE 12: Audit
    // ========================================================================
    eprintln!("\n[PHASE 12] Testing audit...");

    // audit (append interaction)
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["audit", "--message", "Test audit entry", "--label", "test"],
        "audit"
    );

    // ========================================================================
    // PHASE 13: Lint & Orphans
    // ========================================================================
    eprintln!("\n[PHASE 13] Testing lint and orphans...");

    // lint
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["lint"], "lint");

    // orphans
    let (git_snap, head, count, _) =
        check_git_safety!(&workspace, git_snap, head, count, ["orphans"], "orphans");

    // ========================================================================
    // PHASE 14: Epic commands
    // ========================================================================
    eprintln!("\n[PHASE 14] Testing epic commands...");

    // Create an epic
    let (git_snap, head, count, epic_result) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        [
            "create",
            "Epic: Main feature",
            "-t",
            "epic",
            "--no-auto-flush"
        ],
        "create_epic"
    );
    let epic_id = epic_result
        .stdout
        .lines()
        .next()
        .and_then(|l| l.strip_prefix("Created "))
        .and_then(|l| l.split(':').next())
        .unwrap_or("")
        .trim()
        .to_string();

    // Make id1 a child of epic
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        [
            "dep",
            "add",
            &id1,
            &epic_id,
            "-t",
            "parent-child",
            "--no-auto-flush"
        ],
        "dep_add_parent"
    );

    // epic status
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["epic", "status", &epic_id],
        "epic_status"
    );

    // ========================================================================
    // PHASE 15: Changelog
    // ========================================================================
    eprintln!("\n[PHASE 15] Testing changelog...");

    // Close an issue first
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["close", &id2, "--reason", "Done", "--no-auto-flush"],
        "close_for_changelog"
    );

    // changelog
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["changelog"],
        "changelog"
    );

    // changelog --json
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["changelog", "--json"],
        "changelog_json"
    );

    // ========================================================================
    // PHASE 16: Sync operations (brief, detailed tests in e2e_sync_git_safety)
    // ========================================================================
    eprintln!("\n[PHASE 16] Testing sync operations...");

    // sync --flush-only
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["sync", "--flush-only"],
        "sync_flush"
    );

    // sync --status
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["sync", "--status"],
        "sync_status"
    );

    // sync --import-only --force
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["sync", "--import-only", "--force"],
        "sync_import"
    );

    // ========================================================================
    // PHASE 17: Close/Reopen/Delete
    // ========================================================================
    eprintln!("\n[PHASE 17] Testing close/reopen/delete...");

    // close
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["close", &id1, "--reason", "Completed", "--no-auto-flush"],
        "close"
    );

    // reopen
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["reopen", &id1, "--no-auto-flush"],
        "reopen"
    );

    // delete (creates tombstone)
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["delete", &id3, "--reason", "Not needed", "--no-auto-flush"],
        "delete"
    );

    // ========================================================================
    // PHASE 18: Completions (special case - generates to stdout)
    // ========================================================================
    eprintln!("\n[PHASE 18] Testing completions...");

    // completions bash
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["completions", "bash"],
        "completions_bash"
    );

    // completions zsh
    let (git_snap, head, count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["completions", "zsh"],
        "completions_zsh"
    );

    // completions fish
    let (_git_snap, _head, _count, _) = check_git_safety!(
        &workspace,
        git_snap,
        head,
        count,
        ["completions", "fish"],
        "completions_fish"
    );

    // ========================================================================
    // Final verification
    // ========================================================================
    eprintln!("\n[FINAL] Verifying baseline comparison...");

    let final_head = get_head_commit(&workspace.root);
    let final_count = get_commit_count(&workspace.root);

    assert_eq!(
        baseline_head, final_head,
        "HEAD changed during full CLI test!\nBaseline: {baseline_head:?}\nFinal: {final_head:?}"
    );

    assert_eq!(
        baseline_count, final_count,
        "Commit count changed during full CLI test!\nBaseline: {baseline_count}\nFinal: {final_count}"
    );

    eprintln!(
        "\n[PASS] Full CLI git safety test passed!\n\
         - Tested all major command categories\n\
         - HEAD unchanged: {final_head:?}\n\
         - Commit count unchanged: {final_count}"
    );
}

/// Test that auto-flush doesn't touch .git
#[test]
fn regression_auto_flush_does_not_touch_git() {
    let workspace = BrWorkspace::new();
    init_git_repo(&workspace);

    // Initialize beads
    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    // Take baseline
    let baseline_git = snapshot_git_dir(&workspace.root);
    let baseline_head = get_head_commit(&workspace.root);
    let baseline_count = get_commit_count(&workspace.root);

    // Create WITHOUT --no-auto-flush (should auto-flush)
    let create = run_br(&workspace, ["create", "Auto-flush test"], "create_auto");
    assert!(create.status.success());

    // Verify .git unchanged
    let after_git = snapshot_git_dir(&workspace.root);
    let after_head = get_head_commit(&workspace.root);
    let after_count = get_commit_count(&workspace.root);

    let check = verify_git_unchanged(
        &baseline_git,
        &after_git,
        baseline_head.as_ref(),
        after_head.as_ref(),
        baseline_count,
        after_count,
        "auto-flush",
    );

    assert!(
        check.passed,
        "GIT SAFETY VIOLATION: auto-flush touched .git:\n{}",
        check.violations.join("\n")
    );

    eprintln!("[PASS] Auto-flush does not touch .git");
}

/// Test that auto-import doesn't touch .git
#[test]
fn regression_auto_import_does_not_touch_git() {
    let workspace = BrWorkspace::new();
    init_git_repo(&workspace);

    // Initialize and create issues
    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let _ = run_br(
        &workspace,
        ["create", "Issue 1", "--no-auto-flush"],
        "create1",
    );

    // Manually flush
    let _ = run_br(&workspace, ["sync", "--flush-only"], "flush");

    // Touch the JSONL to make it newer
    let jsonl_path = workspace.root.join(".beads").join("issues.jsonl");
    if jsonl_path.exists() {
        let content = fs::read_to_string(&jsonl_path).expect("read");
        std::thread::sleep(std::time::Duration::from_millis(50));
        fs::write(&jsonl_path, content).expect("write");
    }

    // Take baseline
    let baseline_git = snapshot_git_dir(&workspace.root);
    let baseline_head = get_head_commit(&workspace.root);
    let baseline_count = get_commit_count(&workspace.root);

    // Run list (should trigger auto-import)
    let list = run_br(&workspace, ["list"], "list_auto_import");
    assert!(list.status.success());

    // Verify .git unchanged
    let after_git = snapshot_git_dir(&workspace.root);
    let after_head = get_head_commit(&workspace.root);
    let after_count = get_commit_count(&workspace.root);

    let check = verify_git_unchanged(
        &baseline_git,
        &after_git,
        baseline_head.as_ref(),
        after_head.as_ref(),
        baseline_count,
        after_count,
        "auto-import",
    );

    assert!(
        check.passed,
        "GIT SAFETY VIOLATION: auto-import touched .git:\n{}",
        check.violations.join("\n")
    );

    eprintln!("[PASS] Auto-import does not touch .git");
}