beads_rust 0.3.2

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
#![allow(clippy::all, clippy::pedantic, clippy::nursery)]
//! Conformance Tests: Text Output Parity (beads_rust-g1ig)
//!
//! These tests verify br (Rust) produces identical human-readable text output
//! to bd (Go) for stable commands with color/whitespace normalization.
//!
//! Commands tested: list, show, ready, blocked, stats, orphans

mod common;

use common::harness::ConformanceWorkspace;
use regex::Regex;
use std::sync::LazyLock;

/// Skip test when `bd` is not a usable classic conformance reference.
macro_rules! skip_if_no_bd {
    () => {
        if let Some(reason) = common::bd_skip_reason() {
            eprintln!("Skipping conformance test: {reason}");
            return;
        }
    };
}

// ============================================================================
// Text Normalization for Conformance
// ============================================================================

/// Pre-compiled regex patterns for text normalization
static ANSI_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*m").expect("ansi regex"));
static ID_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b[a-zA-Z0-9_]+-[a-z0-9]{3,}\b").expect("id regex"));
static TS_FULL_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})?")
        .expect("full timestamp regex")
});
static DATE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\d{4}-\d{2}-\d{2}").expect("date regex"));
static DURATION_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\d+(\.\d+)?\s*(ms|µs|ns|s|m|h|d)").expect("duration regex"));
static TRAILING_WS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"[ \t]+$").expect("trailing whitespace regex"));
static MULTIPLE_BLANK_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\n{3,}").expect("multiple blank lines regex"));
static HOME_PATH_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"/home/[a-zA-Z0-9_-]+").expect("home path regex"));
static USERS_PATH_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"/Users/[a-zA-Z0-9_-]+").expect("users path regex"));
static TMP_PATH_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?:/data)?/tmp/[A-Za-z0-9_-]*/?\.tmp[a-zA-Z0-9]+|/var/folders/[a-zA-Z0-9/_-]+")
        .expect("tmp path regex")
});
static VERSION_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\((?:[A-Za-z0-9._/-]+)@[a-f0-9]+\)").expect("version regex"));
static SEMVER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?").expect("semver regex"));

/// Normalize text output for conformance comparison.
///
/// This strips ANSI codes, normalizes IDs/timestamps/paths, and cleans up
/// whitespace differences to allow comparing br and bd output.
fn normalize_text_for_conformance(text: &str) -> String {
    let mut normalized = text.to_string();

    // 1. Normalize line endings (CRLF → LF)
    normalized = normalized.replace("\r\n", "\n");

    // 2. Strip ANSI escape sequences
    normalized = ANSI_RE.replace_all(&normalized, "").to_string();

    // 3. Normalize issue IDs to a placeholder
    normalized = ID_RE.replace_all(&normalized, "ISSUE_ID").to_string();

    // 4. Mask full timestamps
    normalized = TS_FULL_RE.replace_all(&normalized, "TIMESTAMP").to_string();

    // 5. Mask dates
    normalized = DATE_RE.replace_all(&normalized, "DATE").to_string();

    // 6. Mask durations
    normalized = DURATION_RE.replace_all(&normalized, "DURATION").to_string();

    // 7. Mask home paths
    normalized = HOME_PATH_RE.replace_all(&normalized, "/HOME").to_string();
    normalized = USERS_PATH_RE.replace_all(&normalized, "/HOME").to_string();

    // 8. Mask temp paths
    normalized = TMP_PATH_RE.replace_all(&normalized, "/TMP").to_string();

    // 9. Mask version/git hash info
    normalized = VERSION_RE
        .replace_all(&normalized, "(BRANCH@HASH)")
        .to_string();
    normalized = SEMVER_RE.replace_all(&normalized, "VERSION").to_string();

    // 10. Strip trailing whitespace per line
    let lines: Vec<&str> = normalized.lines().collect();
    let trimmed: Vec<String> = lines
        .iter()
        .map(|line| TRAILING_WS_RE.replace_all(line, "").to_string())
        .collect();
    normalized = trimmed.join("\n");

    // 11. Collapse multiple blank lines
    normalized = MULTIPLE_BLANK_RE
        .replace_all(&normalized, "\n\n")
        .to_string();

    // 12. Trim leading/trailing whitespace from the entire output
    normalized = normalized.trim().to_string();

    normalized
}

/// Result of comparing text outputs between br and bd
#[derive(Debug)]
struct TextComparisonResult {
    matches: bool,
    br_normalized: String,
    bd_normalized: String,
    diff_summary: String,
}

impl TextComparisonResult {
    fn compare(br_output: &str, bd_output: &str) -> Self {
        let br_normalized = normalize_text_for_conformance(br_output);
        let bd_normalized = normalize_text_for_conformance(bd_output);
        let matches = br_normalized == bd_normalized;

        let diff_summary = if matches {
            "Outputs match after normalization".to_string()
        } else {
            let br_lines: Vec<&str> = br_normalized.lines().collect();
            let bd_lines: Vec<&str> = bd_normalized.lines().collect();

            let mut diffs = Vec::new();
            let max_lines = br_lines.len().max(bd_lines.len());

            for i in 0..max_lines {
                let br_line = br_lines.get(i).map(|s| *s).unwrap_or("<missing>");
                let bd_line = bd_lines.get(i).map(|s| *s).unwrap_or("<missing>");
                if br_line != bd_line {
                    diffs.push(format!(
                        "Line {}: br='{}' vs bd='{}'",
                        i + 1,
                        br_line,
                        bd_line
                    ));
                }
            }

            if diffs.len() > 10 {
                format!(
                    "{} differences found (showing first 10):\n{}",
                    diffs.len(),
                    diffs[..10].join("\n")
                )
            } else {
                format!("{} differences found:\n{}", diffs.len(), diffs.join("\n"))
            }
        };

        Self {
            matches,
            br_normalized,
            bd_normalized,
            diff_summary,
        }
    }
}

/// Extract issue ID from create output
fn extract_id_from_create(stdout: &str) -> String {
    // br output: "✓ Created bd-abc123: Title" (with checkmark)
    // bd output: "Created bd-abc123: Title" (no checkmark)
    for line in stdout.lines() {
        let line = line.trim();
        // Handle br format with checkmark: "✓ Created ID: Title"
        if let Some(rest) = line.strip_prefix("✓ Created ") {
            if let Some(id) = rest.split(':').next() {
                let id = id.trim();
                if !id.is_empty() && !id.starts_with("issue") {
                    return id.to_string();
                }
            }
        }
        // Handle bd format (and br without checkmark): "Created ID: Title"
        if let Some(rest) = line.strip_prefix("Created ") {
            if let Some(id) = rest.split(':').next() {
                let id = id.trim();
                if !id.is_empty() && !id.starts_with("issue") {
                    return id.to_string();
                }
            }
        }
    }
    String::new()
}

// ============================================================================
// Text Output Conformance Tests
// ============================================================================

/// Test: `list` command with empty database
#[test]
fn conformance_text_list_empty() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "list_empty");
    let (br_init, bd_init) = workspace.init_both();

    assert!(br_init.success, "br init failed: {}", br_init.stderr);
    assert!(bd_init.success, "bd init failed: {}", bd_init.stderr);

    // Run list command (text output, no --json)
    let br_list = workspace.run_br(["list"], "list");
    let bd_list = workspace.run_bd(["list"], "list");

    assert!(br_list.success, "br list failed: {}", br_list.stderr);
    assert!(bd_list.success, "bd list failed: {}", bd_list.stderr);

    let result = TextComparisonResult::compare(&br_list.stdout, &bd_list.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'list' (empty):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `list` command with issues
#[test]
fn conformance_text_list_with_issues() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "list_with_issues");
    workspace.init_both();

    // Create identical issues in both workspaces
    workspace.run_br(["create", "First issue"], "create1");
    workspace.run_bd(["create", "First issue"], "create1");
    workspace.run_br(["create", "Second issue"], "create2");
    workspace.run_bd(["create", "Second issue"], "create2");
    workspace.run_br(["create", "Third issue"], "create3");
    workspace.run_bd(["create", "Third issue"], "create3");

    // Run list command
    let br_list = workspace.run_br(["list"], "list");
    let bd_list = workspace.run_bd(["list"], "list");

    assert!(br_list.success, "br list failed: {}", br_list.stderr);
    assert!(bd_list.success, "bd list failed: {}", bd_list.stderr);

    let result = TextComparisonResult::compare(&br_list.stdout, &bd_list.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'list' (with issues):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `show` command
#[test]
fn conformance_text_show() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "show");
    workspace.init_both();

    // Create issues and capture IDs
    let br_create = workspace.run_br(["create", "Test issue for show"], "create");
    let bd_create = workspace.run_bd(["create", "Test issue for show"], "create");

    let br_id = extract_id_from_create(&br_create.stdout);
    let bd_id = extract_id_from_create(&bd_create.stdout);

    // Run show command
    let br_show = workspace.run_br(["show", &br_id], "show");
    let bd_show = workspace.run_bd(["show", &bd_id], "show");

    assert!(br_show.success, "br show failed: {}", br_show.stderr);
    assert!(bd_show.success, "bd show failed: {}", bd_show.stderr);

    let result = TextComparisonResult::compare(&br_show.stdout, &bd_show.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'show':\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `ready` command with empty database
#[test]
fn conformance_text_ready_empty() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "ready_empty");
    workspace.init_both();

    let br_ready = workspace.run_br(["ready"], "ready");
    let bd_ready = workspace.run_bd(["ready"], "ready");

    assert!(br_ready.success, "br ready failed: {}", br_ready.stderr);
    assert!(bd_ready.success, "bd ready failed: {}", bd_ready.stderr);

    let result = TextComparisonResult::compare(&br_ready.stdout, &bd_ready.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'ready' (empty):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `ready` command with issues
#[test]
fn conformance_text_ready_with_issues() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "ready_with_issues");
    workspace.init_both();

    // Create issues with different priorities
    workspace.run_br(
        ["create", "High priority task", "--priority", "1"],
        "create1",
    );
    workspace.run_bd(
        ["create", "High priority task", "--priority", "1"],
        "create1",
    );
    workspace.run_br(
        ["create", "Medium priority task", "--priority", "2"],
        "create2",
    );
    workspace.run_bd(
        ["create", "Medium priority task", "--priority", "2"],
        "create2",
    );
    workspace.run_br(
        ["create", "Low priority task", "--priority", "3"],
        "create3",
    );
    workspace.run_bd(
        ["create", "Low priority task", "--priority", "3"],
        "create3",
    );

    let br_ready = workspace.run_br(["ready"], "ready");
    let bd_ready = workspace.run_bd(["ready"], "ready");

    assert!(br_ready.success, "br ready failed: {}", br_ready.stderr);
    assert!(bd_ready.success, "bd ready failed: {}", bd_ready.stderr);

    let result = TextComparisonResult::compare(&br_ready.stdout, &bd_ready.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'ready' (with issues):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `blocked` command with empty database
#[test]
fn conformance_text_blocked_empty() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "blocked_empty");
    workspace.init_both();

    let br_blocked = workspace.run_br(["blocked"], "blocked");
    let bd_blocked = workspace.run_bd(["blocked"], "blocked");

    assert!(
        br_blocked.success,
        "br blocked failed: {}",
        br_blocked.stderr
    );
    assert!(
        bd_blocked.success,
        "bd blocked failed: {}",
        bd_blocked.stderr
    );

    let result = TextComparisonResult::compare(&br_blocked.stdout, &bd_blocked.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'blocked' (empty):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `blocked` command with blocked issues
#[test]
#[ignore = "text formatting differences between br and bd for blocked output"]
fn conformance_text_blocked_with_issues() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "blocked_with_issues");
    workspace.init_both();

    // Create issues and add dependencies to create blocked issues
    let br_blocker = workspace.run_br(["create", "Blocker issue"], "create_blocker");
    let bd_blocker = workspace.run_bd(["create", "Blocker issue"], "create_blocker");
    let br_blocked = workspace.run_br(["create", "Blocked issue"], "create_blocked");
    let bd_blocked = workspace.run_bd(["create", "Blocked issue"], "create_blocked");

    let br_blocker_id = extract_id_from_create(&br_blocker.stdout);
    let bd_blocker_id = extract_id_from_create(&bd_blocker.stdout);
    let br_blocked_id = extract_id_from_create(&br_blocked.stdout);
    let bd_blocked_id = extract_id_from_create(&bd_blocked.stdout);

    // Add dependency: blocked depends on blocker
    workspace.run_br(["dep", "add", &br_blocked_id, &br_blocker_id], "dep_add");
    workspace.run_bd(["dep", "add", &bd_blocked_id, &bd_blocker_id], "dep_add");

    let br_result = workspace.run_br(["blocked"], "blocked");
    let bd_result = workspace.run_bd(["blocked"], "blocked");

    assert!(br_result.success, "br blocked failed: {}", br_result.stderr);
    assert!(bd_result.success, "bd blocked failed: {}", bd_result.stderr);

    let result = TextComparisonResult::compare(&br_result.stdout, &bd_result.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'blocked' (with issues):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `stats` command (alias for status)
#[test]
fn conformance_text_stats_empty() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "stats_empty");
    workspace.init_both();

    // Use --no-activity to skip git activity tracking which could differ
    let br_stats = workspace.run_br(["stats", "--no-activity"], "stats");
    let bd_stats = workspace.run_bd(["stats", "--no-activity"], "stats");

    assert!(br_stats.success, "br stats failed: {}", br_stats.stderr);
    assert!(bd_stats.success, "bd stats failed: {}", bd_stats.stderr);

    let result = TextComparisonResult::compare(&br_stats.stdout, &bd_stats.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'stats' (empty):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `stats` command with issues
#[test]
#[ignore = "text formatting differences between br and bd for stats output"]
fn conformance_text_stats_with_issues() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "stats_with_issues");
    workspace.init_both();

    // Create some issues
    workspace.run_br(["create", "Open issue 1"], "create1");
    workspace.run_bd(["create", "Open issue 1"], "create1");
    workspace.run_br(["create", "Open issue 2"], "create2");
    workspace.run_bd(["create", "Open issue 2"], "create2");

    // Create and close an issue
    let br_close = workspace.run_br(["create", "Issue to close"], "create_close");
    let bd_close = workspace.run_bd(["create", "Issue to close"], "create_close");
    let br_close_id = extract_id_from_create(&br_close.stdout);
    let bd_close_id = extract_id_from_create(&bd_close.stdout);
    workspace.run_br(["close", &br_close_id], "close");
    workspace.run_bd(["close", &bd_close_id], "close");

    let br_stats = workspace.run_br(["stats", "--no-activity"], "stats");
    let bd_stats = workspace.run_bd(["stats", "--no-activity"], "stats");

    assert!(br_stats.success, "br stats failed: {}", br_stats.stderr);
    assert!(bd_stats.success, "bd stats failed: {}", bd_stats.stderr);

    let result = TextComparisonResult::compare(&br_stats.stdout, &bd_stats.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'stats' (with issues):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `orphans` command with empty database
#[test]
fn conformance_text_orphans_empty() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "orphans_empty");
    workspace.init_both();

    let br_orphans = workspace.run_br(["orphans"], "orphans");
    let bd_orphans = workspace.run_bd(["orphans"], "orphans");

    // Exit code behavior should match
    assert_eq!(
        br_orphans.success, bd_orphans.success,
        "Exit code mismatch for 'orphans' (empty): br={}, bd={}",
        br_orphans.exit_code, bd_orphans.exit_code
    );

    let result = TextComparisonResult::compare(&br_orphans.stdout, &bd_orphans.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'orphans' (empty):\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `list` with status filter
#[test]
#[ignore = "text formatting differences between br and bd for list output"]
fn conformance_text_list_status_filter() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "list_status_filter");
    workspace.init_both();

    // Create issues with different statuses
    workspace.run_br(["create", "Open issue"], "create_open");
    workspace.run_bd(["create", "Open issue"], "create_open");

    let br_create = workspace.run_br(["create", "Issue to close"], "create_close");
    let bd_create = workspace.run_bd(["create", "Issue to close"], "create_close");
    let br_id = extract_id_from_create(&br_create.stdout);
    let bd_id = extract_id_from_create(&bd_create.stdout);
    workspace.run_br(["close", &br_id], "close");
    workspace.run_bd(["close", &bd_id], "close");

    // List only open issues
    let br_list = workspace.run_br(["list", "--status", "open"], "list_open");
    let bd_list = workspace.run_bd(["list", "--status", "open"], "list_open");

    assert!(
        br_list.success,
        "br list --status failed: {}",
        br_list.stderr
    );
    assert!(
        bd_list.success,
        "bd list --status failed: {}",
        bd_list.stderr
    );

    let result = TextComparisonResult::compare(&br_list.stdout, &bd_list.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'list --status open':\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `list` with type filter
#[test]
fn conformance_text_list_type_filter() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "list_type_filter");
    workspace.init_both();

    // Create issues with different types
    workspace.run_br(["create", "Bug report", "--type", "bug"], "create_bug");
    workspace.run_bd(["create", "Bug report", "--type", "bug"], "create_bug");
    workspace.run_br(
        ["create", "Feature request", "--type", "feature"],
        "create_feature",
    );
    workspace.run_bd(
        ["create", "Feature request", "--type", "feature"],
        "create_feature",
    );
    workspace.run_br(["create", "Regular task", "--type", "task"], "create_task");
    workspace.run_bd(["create", "Regular task", "--type", "task"], "create_task");

    // List only bugs
    let br_list = workspace.run_br(["list", "--type", "bug"], "list_bug");
    let bd_list = workspace.run_bd(["list", "--type", "bug"], "list_bug");

    assert!(br_list.success, "br list --type failed: {}", br_list.stderr);
    assert!(bd_list.success, "bd list --type failed: {}", bd_list.stderr);

    let result = TextComparisonResult::compare(&br_list.stdout, &bd_list.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'list --type bug':\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `list` with priority filter
#[test]
fn conformance_text_list_priority_filter() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "list_priority_filter");
    workspace.init_both();

    // Create issues with different priorities
    workspace.run_br(["create", "Critical issue", "--priority", "0"], "create_p0");
    workspace.run_bd(["create", "Critical issue", "--priority", "0"], "create_p0");
    workspace.run_br(["create", "High priority", "--priority", "1"], "create_p1");
    workspace.run_bd(["create", "High priority", "--priority", "1"], "create_p1");
    workspace.run_br(
        ["create", "Medium priority", "--priority", "2"],
        "create_p2",
    );
    workspace.run_bd(
        ["create", "Medium priority", "--priority", "2"],
        "create_p2",
    );

    // List only critical (P0) issues
    let br_list = workspace.run_br(["list", "--priority", "0"], "list_p0");
    let bd_list = workspace.run_bd(["list", "--priority", "0"], "list_p0");

    assert!(
        br_list.success,
        "br list --priority failed: {}",
        br_list.stderr
    );
    assert!(
        bd_list.success,
        "bd list --priority failed: {}",
        bd_list.stderr
    );

    let result = TextComparisonResult::compare(&br_list.stdout, &bd_list.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'list --priority 0':\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

/// Test: `show` with non-existent issue
///
/// NOTE: This test documents an intentional behavioral difference:
/// - br: Returns exit code 3 (error) for not-found issues
/// - bd: Returns exit code 0 (success) with error message to stderr
///
/// br's behavior is more correct (non-zero exit for errors), so we don't
/// match bd's permissive behavior here. This test verifies both produce
/// appropriate error messages.
#[test]
fn conformance_text_show_not_found() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "show_not_found");
    workspace.init_both();

    let br_show = workspace.run_br(["show", "nonexistent-id"], "show");
    let bd_show = workspace.run_bd(["show", "nonexistent-id"], "show");

    // INTENTIONAL DIFFERENCE: br returns error (exit 3), bd returns success (exit 0)
    // br's behavior is more correct - errors should have non-zero exit codes
    // We verify br fails as expected, not that it matches bd's permissive behavior
    assert!(
        !br_show.success,
        "br should return error for not-found issue, got exit code {}",
        br_show.exit_code
    );

    // Both should print a not-found diagnostic even though legacy bd differs
    // on exit status and output stream.
    assert!(
        br_show.stderr.contains("not found") || br_show.stderr.contains("IssueNotFound"),
        "br should print not-found error, got: {}",
        br_show.stderr
    );
    let bd_diagnostic = format!("{}\n{}", bd_show.stdout, bd_show.stderr).to_lowercase();
    assert!(
        bd_diagnostic.contains("not found")
            || bd_diagnostic.contains("no such")
            || bd_diagnostic.contains("not exist"),
        "bd should print not-found error, got stdout: {}, stderr: {}",
        bd_show.stdout,
        bd_show.stderr
    );

    workspace.finish(true);
}

/// Test: `ready` with limit
#[test]
fn conformance_text_ready_with_limit() {
    skip_if_no_bd!();
    common::init_test_logging();

    let mut workspace = ConformanceWorkspace::new("conformance_text", "ready_with_limit");
    workspace.init_both();

    // Create multiple issues
    for i in 1..=5 {
        let title = format!("Task {}", i);
        workspace.run_br(["create", &title], &format!("create_{}", i));
        workspace.run_bd(["create", &title], &format!("create_{}", i));
    }

    // Get only first 2 ready issues
    let br_ready = workspace.run_br(["ready", "--limit", "2"], "ready");
    let bd_ready = workspace.run_bd(["ready", "--limit", "2"], "ready");

    assert!(
        br_ready.success,
        "br ready --limit failed: {}",
        br_ready.stderr
    );
    assert!(
        bd_ready.success,
        "bd ready --limit failed: {}",
        bd_ready.stderr
    );

    let result = TextComparisonResult::compare(&br_ready.stdout, &bd_ready.stdout);

    assert!(
        result.matches,
        "Text output mismatch for 'ready --limit 2':\n{}\n\nbr output:\n{}\n\nbd output:\n{}",
        result.diff_summary, result.br_normalized, result.bd_normalized
    );

    workspace.finish(true);
}

// ============================================================================
// Unit Tests for Normalization
// ============================================================================

#[cfg(test)]
mod normalization_tests {
    use super::*;

    #[test]
    fn test_normalize_ansi_codes() {
        let input = "\x1b[31mRed\x1b[0m normal \x1b[1;32mgreen\x1b[0m";
        let result = normalize_text_for_conformance(input);
        assert!(!result.contains("\x1b["));
        assert!(result.contains("Red"));
        assert!(result.contains("green"));
    }

    #[test]
    fn test_normalize_issue_ids() {
        let input = "Issue bd-abc123 depends on beads_rust-xyz789";
        let result = normalize_text_for_conformance(input);
        assert!(result.contains("ISSUE_ID"));
        assert!(!result.contains("bd-abc123"));
        assert!(!result.contains("beads_rust-xyz789"));
    }

    #[test]
    fn test_normalize_timestamps() {
        let input = "Created: 2026-01-17T12:30:45.123456Z";
        let result = normalize_text_for_conformance(input);
        assert!(result.contains("TIMESTAMP"));
        assert!(!result.contains("2026-01-17T12:30:45"));
    }

    #[test]
    fn test_normalize_dates() {
        let input = "Due: 2026-01-17";
        let result = normalize_text_for_conformance(input);
        assert!(result.contains("DATE"));
        assert!(!result.contains("2026-01-17"));
    }

    #[test]
    fn test_normalize_durations() {
        let input = "Completed in 123ms, total 5s";
        let result = normalize_text_for_conformance(input);
        assert!(result.contains("DURATION"));
        assert!(!result.contains("123ms"));
    }

    #[test]
    fn test_normalize_paths() {
        let input = "Config at /home/user/.config/br";
        let result = normalize_text_for_conformance(input);
        assert!(result.contains("/HOME"));
        assert!(!result.contains("/home/user"));
    }

    #[test]
    fn test_normalize_line_endings() {
        let input = "line1\r\nline2\r\n";
        let result = normalize_text_for_conformance(input);
        assert!(!result.contains("\r\n"));
    }

    #[test]
    fn test_normalize_trailing_whitespace() {
        let input = "line1   \nline2\t\t\n";
        let result = normalize_text_for_conformance(input);
        let lines: Vec<&str> = result.lines().collect();
        for line in lines {
            assert!(!line.ends_with(' '));
            assert!(!line.ends_with('\t'));
        }
    }

    #[test]
    fn test_comparison_result_match() {
        let text = "Issue ISSUE_ID is open";
        let result = TextComparisonResult::compare(text, text);
        assert!(result.matches);
    }

    #[test]
    fn test_comparison_result_mismatch() {
        let br = "Issue bd-abc: open";
        let bd = "Issue bd-xyz: closed";
        let result = TextComparisonResult::compare(br, bd);
        // After normalization, "bd-abc" and "bd-xyz" become "ISSUE_ID"
        // but "open" vs "closed" will differ
        assert!(!result.matches);
    }
}