minibeads 0.13.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
//! Random beads action generator for property-based testing
//!
//! This module provides a reusable library for generating and executing
//! random sequences of beads commands against minibeads or upstream bd.
//!
//! ## Key Assumption: Sequential Issue Numbering
//!
//! **IMPORTANT**: This generator assumes that beads implementations always number
//! new issues sequentially as `N+1` where `N` is the maximum previous issue ID.
//!
//! This assumption allows us to:
//! - Generate valid action sequences without executing commands
//! - Predict which issue IDs will exist at any point in the sequence
//! - Generate contextually valid actions (e.g., only update issues that exist)
//! - Verify correctness by checking that created issues match predictions
//!
//! ### Verification Strategy
//!
//! When executing action sequences, we VERIFY this assumption by:
//! 1. Each `Create` action includes an `expected_id` field
//! 2. After executing `bd create`, we parse the output to extract the actual issue ID
//! 3. We assert that `actual_id == expected_id`
//! 4. If the assertion fails, the test fails with a clear error message
//!
//! This verification ensures that:
//! - Our model of issue state matches reality
//! - The beads implementation follows sequential numbering
//! - All subsequent actions operate on the correct issues
//!
//! ### Example
//!
//! ```text
//! Action sequence:
//!   1. Init { prefix: "test" }
//!   2. Create { expected_id: "test-1", ...}  →  Verify actual ID is "test-1"
//!   3. Create { expected_id: "test-2", ... } →  Verify actual ID is "test-2"
//!   4. Update { issue_id: "test-1", ... }     →  Valid because test-1 exists
//!   5. Close { issue_id: "test-2", ... }      →  Valid because test-2 exists
//! ```

use anyhow::{Context, Result};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use std::collections::HashSet;
use std::process::Command;

// Re-export production types instead of defining duplicates
pub use crate::types::{DependencyType, IssueType, Status};

/// Represents a beads command/action
#[derive(Debug, Clone, PartialEq)]
pub enum BeadsAction {
    /// Initialize beads in directory
    Init {
        prefix: Option<String>,
        mb_hash_ids: Option<bool>,
    },

    /// Create a new issue with expected ID for verification
    Create {
        expected_id: String,
        title: String,
        priority: i32,
        issue_type: IssueType,
        description: Option<String>,
    },

    /// List issues with optional filters
    List {
        status: Option<Status>,
        priority: Option<i32>,
    },

    /// Show a specific issue
    Show { issue_id: String },

    /// Update an issue
    Update {
        issue_id: String,
        status: Option<Status>,
        priority: Option<i32>,
    },

    /// Close an issue
    Close { issue_id: String, reason: String },

    /// Reopen an issue
    Reopen { issue_id: String },

    /// Add a dependency
    AddDependency {
        issue_id: String,
        depends_on: String,
        dep_type: DependencyType,
    },

    /// Export to JSONL
    Export { output: String },
}

impl std::fmt::Display for BeadsAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BeadsAction::Init {
                prefix,
                mb_hash_ids,
            } => {
                let mut parts = vec!["init".to_string()];
                if let Some(p) = prefix {
                    parts.push(format!("--prefix {}", p));
                }
                if let Some(true) = mb_hash_ids {
                    parts.push("--mb-hash-ids".to_string());
                }
                write!(f, "{}", parts.join(" "))
            }
            BeadsAction::Create {
                expected_id,
                priority,
                issue_type,
                ..
            } => write!(
                f,
                "create {} (p:{}, type:{})",
                expected_id,
                priority,
                issue_type.as_str()
            ),
            BeadsAction::List { status, priority } => {
                let mut parts = vec!["list".to_string()];
                if let Some(s) = status {
                    parts.push(format!("status:{}", s.as_str()));
                }
                if let Some(p) = priority {
                    parts.push(format!("priority:{}", p));
                }
                write!(f, "{}", parts.join(" "))
            }
            BeadsAction::Show { issue_id } => write!(f, "show {}", issue_id),
            BeadsAction::Update {
                issue_id,
                status,
                priority,
            } => {
                let mut parts = vec![format!("update {}", issue_id)];
                if let Some(s) = status {
                    parts.push(format!("status:{}", s.as_str()));
                }
                if let Some(p) = priority {
                    parts.push(format!("priority:{}", p));
                }
                write!(f, "{}", parts.join(" "))
            }
            BeadsAction::Close { issue_id, .. } => write!(f, "close {}", issue_id),
            BeadsAction::Reopen { issue_id } => write!(f, "reopen {}", issue_id),
            BeadsAction::AddDependency {
                issue_id,
                depends_on,
                dep_type,
            } => write!(
                f,
                "dep add {}{} ({})",
                issue_id,
                depends_on,
                dep_type.as_str()
            ),
            BeadsAction::Export { output } => write!(f, "export to {}", output),
        }
    }
}

/// Generates random beads action sequences
///
/// Maintains state to ensure generated actions are contextually valid:
/// - Tracks which issues exist (for Update, Show, Close, etc.)
/// - Tracks which issues are closed (for Reopen)
/// - Predicts issue IDs using sequential numbering assumption
pub struct ActionGenerator {
    rng: StdRng,
    prefix: String,
    next_issue_num: usize,
    existing_issues: Vec<String>, // Maintains creation order
    closed_issues: HashSet<String>,
    use_hash_ids: bool,
}

impl ActionGenerator {
    /// Create a new generator with the given seed
    pub fn new(seed: u64) -> Self {
        Self::new_with_mode(seed, false)
    }

    /// Create a new generator with explicit hash ID mode
    pub fn new_with_mode(seed: u64, use_hash_ids: bool) -> Self {
        Self {
            rng: StdRng::seed_from_u64(seed),
            prefix: "test".to_string(),
            next_issue_num: 1,
            existing_issues: Vec::new(),
            closed_issues: HashSet::new(),
            use_hash_ids,
        }
    }

    /// Generate a sequence of random actions
    ///
    /// Always starts with Init, then generates num_actions random valid actions
    pub fn generate_sequence(&mut self, num_actions: usize) -> Vec<BeadsAction> {
        let mut actions = Vec::new();

        // Always start with init
        actions.push(BeadsAction::Init {
            prefix: Some(self.prefix.clone()),
            mb_hash_ids: Some(self.use_hash_ids),
        });

        // Generate random actions
        for _ in 0..num_actions {
            actions.push(self.generate_action());
        }

        actions
    }

    /// Generate a single random action based on current state
    fn generate_action(&mut self) -> BeadsAction {
        // Weight actions based on what makes sense
        let action_type = if self.existing_issues.is_empty() {
            // If no issues exist, must create one
            0
        } else {
            // Otherwise, pick randomly
            // Bias towards creating issues (30% chance) to build up state
            let rand_val = self.rng.gen_range(0..100);
            if rand_val < 30 {
                0 // Create
            } else if rand_val < 45 {
                1 // List
            } else if rand_val < 55 {
                2 // Show
            } else if rand_val < 70 {
                3 // Update
            } else if rand_val < 80 {
                4 // Close
            } else if rand_val < 85 {
                5 // Reopen
            } else if rand_val < 95 {
                6 // AddDependency
            } else {
                7 // Export
            }
        };

        match action_type {
            0 => self.generate_create(),
            1 => self.generate_list(),
            2 => self.generate_show(),
            3 => self.generate_update(),
            4 => self.generate_close(),
            5 => self.generate_reopen(),
            6 => self.generate_add_dependency(),
            7 => self.generate_export(),
            _ => unreachable!(),
        }
    }

    fn generate_create(&mut self) -> BeadsAction {
        let title = format!("Issue {}", self.rng.gen_range(1000..9999));
        let priority = self.rng.gen_range(0..5);
        let issue_type = match self.rng.gen_range(0..5) {
            0 => IssueType::Bug,
            1 => IssueType::Feature,
            2 => IssueType::Task,
            3 => IssueType::Epic,
            _ => IssueType::Chore,
        };

        let description = if self.rng.gen_bool(0.5) {
            Some(format!("Description for {}", title))
        } else {
            None
        };

        // Compute expected ID based on mode
        let expected_id = if self.use_hash_ids {
            // For hash mode, use a placeholder since hash IDs are timestamp-based
            // and cannot be predicted in advance (they depend on execution-time timestamp)
            format!("{}-HASH", self.prefix)
        } else {
            // Use sequential numbering
            format!("{}-{}", self.prefix, self.next_issue_num)
        };

        // Track the issue (will be updated with actual ID for hash mode)
        self.next_issue_num += 1;
        if !self.use_hash_ids {
            // Only pre-add for numeric mode; hash mode adds after execution
            self.existing_issues.push(expected_id.clone());
        }

        BeadsAction::Create {
            expected_id,
            title,
            priority,
            issue_type,
            description,
        }
    }

    fn generate_list(&mut self) -> BeadsAction {
        let status = if self.rng.gen_bool(0.3) {
            Some(match self.rng.gen_range(0..4) {
                0 => Status::Open,
                1 => Status::InProgress,
                2 => Status::Blocked,
                _ => Status::Closed,
            })
        } else {
            None
        };

        let priority = if self.rng.gen_bool(0.3) {
            Some(self.rng.gen_range(0..5))
        } else {
            None
        };

        BeadsAction::List { status, priority }
    }

    fn generate_show(&mut self) -> BeadsAction {
        let issue_id = self.pick_random_issue();
        BeadsAction::Show { issue_id }
    }

    fn generate_update(&mut self) -> BeadsAction {
        let issue_id = self.pick_random_issue();

        let status = if self.rng.gen_bool(0.5) {
            Some(match self.rng.gen_range(0..3) {
                0 => Status::Open,
                1 => Status::InProgress,
                _ => Status::Blocked,
            })
        } else {
            None
        };

        let priority = if self.rng.gen_bool(0.5) {
            Some(self.rng.gen_range(0..5))
        } else {
            None
        };

        BeadsAction::Update {
            issue_id,
            status,
            priority,
        }
    }

    fn generate_close(&mut self) -> BeadsAction {
        let issue_id = self.pick_random_issue();
        self.closed_issues.insert(issue_id.clone());

        BeadsAction::Close {
            issue_id,
            reason: "Completed".to_string(),
        }
    }

    fn generate_reopen(&mut self) -> BeadsAction {
        // Try to reopen a closed issue, or pick any issue
        let issue_id = if !self.closed_issues.is_empty() && self.rng.gen_bool(0.7) {
            let idx = self.rng.gen_range(0..self.closed_issues.len());
            let issue = self.closed_issues.iter().nth(idx).unwrap().clone();
            self.closed_issues.remove(&issue);
            issue
        } else {
            self.pick_random_issue()
        };

        BeadsAction::Reopen { issue_id }
    }

    fn generate_add_dependency(&mut self) -> BeadsAction {
        // Need at least 2 issues for a dependency
        if self.existing_issues.len() < 2 {
            return self.generate_create();
        }

        let issue_id =
            self.existing_issues[self.rng.gen_range(0..self.existing_issues.len())].clone();

        // Pick a different issue to depend on
        let mut depends_on =
            self.existing_issues[self.rng.gen_range(0..self.existing_issues.len())].clone();
        while depends_on == issue_id && self.existing_issues.len() > 1 {
            depends_on =
                self.existing_issues[self.rng.gen_range(0..self.existing_issues.len())].clone();
        }

        let dep_type = match self.rng.gen_range(0..3) {
            0 => DependencyType::Blocks,
            1 => DependencyType::Related,
            _ => DependencyType::ParentChild,
        };

        BeadsAction::AddDependency {
            issue_id,
            depends_on,
            dep_type,
        }
    }

    fn generate_export(&mut self) -> BeadsAction {
        BeadsAction::Export {
            output: "issues.jsonl".to_string(),
        }
    }

    fn pick_random_issue(&mut self) -> String {
        if self.existing_issues.is_empty() {
            // Shouldn't happen, but handle it
            format!("{}-1", self.prefix)
        } else {
            let idx = self.rng.gen_range(0..self.existing_issues.len());
            self.existing_issues[idx].clone()
        }
    }
}

/// Executes beads actions against a specific implementation
pub struct ActionExecutor {
    binary_path: String,
    work_dir: String,
    use_no_db: bool,
}

impl ActionExecutor {
    /// Create a new executor for the given binary
    ///
    /// `use_no_db`: If true, prepends --no-db to all commands (for upstream bd)
    pub fn new(binary_path: &str, work_dir: &str, use_no_db: bool) -> Self {
        Self {
            binary_path: binary_path.to_string(),
            work_dir: work_dir.to_string(),
            use_no_db,
        }
    }

    /// Build a command with the binary path, working directory, and --no-db flag if needed
    fn build_command(&self) -> Command {
        let mut cmd = Command::new(&self.binary_path);
        cmd.current_dir(&self.work_dir);

        // Set MB_BEADS_DIR to force using .beads in working directory
        // This prevents minibeads from walking up and finding ancestor .beads directories
        let beads_dir = std::path::PathBuf::from(&self.work_dir).join(".beads");
        cmd.env("MB_BEADS_DIR", beads_dir);

        if self.use_no_db {
            cmd.arg("--no-db");
        }
        cmd
    }

    /// Execute a single action
    ///
    /// For Create actions, verifies that the created issue ID matches expected_id
    pub fn execute(&self, action: &BeadsAction) -> Result<ExecutionResult> {
        // Track actual_issue_id for Create actions
        let mut actual_issue_id: Option<String> = None;

        let output = match action {
            BeadsAction::Init {
                prefix,
                mb_hash_ids,
            } => {
                let mut cmd = self.build_command();
                cmd.arg("init");
                if let Some(p) = prefix {
                    cmd.arg("--prefix").arg(p);
                }
                // Only pass --mb-hash-ids to minibeads, not upstream
                // Upstream doesn't support this flag (it always uses hash IDs)
                let is_upstream = self.binary_path.contains("upstream");
                if let Some(true) = mb_hash_ids {
                    if !is_upstream {
                        cmd.arg("--mb-hash-ids");
                    }
                }
                cmd.output().context("Failed to execute init command")?
            }

            BeadsAction::Create {
                expected_id,
                title,
                priority,
                issue_type,
                description,
            } => {
                let mut cmd = self.build_command();
                cmd.arg("create")
                    .arg(title)
                    .arg("-p")
                    .arg(priority.to_string())
                    .arg("-t")
                    .arg(issue_type.as_str());

                if let Some(desc) = description {
                    cmd.arg("-d").arg(desc);
                }

                let output = cmd.output().context("Failed to execute create command")?;

                // Extract the actual issue ID from output
                if output.status.success() {
                    actual_issue_id = extract_issue_id(&String::from_utf8_lossy(&output.stdout));
                }

                // Verify the created issue ID matches our expectation
                // Skip verification for hash mode (expected_id contains "HASH")
                if output.status.success() && !expected_id.contains("HASH") {
                    if let Some(ref actual) = actual_issue_id {
                        if actual != expected_id {
                            // Parse both IDs to understand the mismatch
                            let expected_parts: Vec<&str> = expected_id.split('-').collect();
                            let actual_parts: Vec<&str> = actual.split('-').collect();

                            let prefix_mismatch = expected_parts.first() != actual_parts.first();
                            let number_mismatch = expected_parts.get(1) != actual_parts.get(1);

                            let mut error_msg = String::from("ISSUE ID MISMATCH!\n");
                            error_msg.push_str(&format!("Expected: {}\n", expected_id));
                            error_msg.push_str(&format!("Actual:   {}\n\n", actual));

                            if prefix_mismatch {
                                error_msg.push_str(&format!(
                                    "PREFIX MISMATCH: Expected '{}', got '{}'\n",
                                    expected_parts.first().unwrap_or(&"?"),
                                    actual_parts.first().unwrap_or(&"?")
                                ));
                                error_msg.push_str("Possible causes:\n");
                                error_msg.push_str("  - Init command failed to set prefix\n");
                                error_msg.push_str(
                                    "  - Found existing .beads directory with different prefix\n",
                                );
                                error_msg.push_str("  - Working in wrong directory\n");
                            }

                            if number_mismatch && !prefix_mismatch {
                                error_msg.push_str(&format!(
                                    "NUMBER MISMATCH: Expected '{}', got '{}'\n",
                                    expected_parts.get(1).unwrap_or(&"?"),
                                    actual_parts.get(1).unwrap_or(&"?")
                                ));
                                error_msg.push_str("Possible causes:\n");
                                error_msg.push_str("  - Existing issues in database\n");
                                error_msg
                                    .push_str("  - Sequential numbering assumption violated\n");
                                error_msg.push_str("  - Test directory not isolated\n");
                            }

                            anyhow::bail!(error_msg);
                        }
                    }
                }

                output
            }

            BeadsAction::List { status, priority } => {
                let mut cmd = self.build_command();
                cmd.arg("list");

                if let Some(s) = status {
                    cmd.arg("--status").arg(s.as_str());
                }
                if let Some(p) = priority {
                    cmd.arg("--priority").arg(p.to_string());
                }

                cmd.output().context("Failed to execute list command")?
            }

            BeadsAction::Show { issue_id } => {
                let mut cmd = self.build_command();
                cmd.arg("show").arg(issue_id);
                cmd.output().context("Failed to execute show command")?
            }

            BeadsAction::Update {
                issue_id,
                status,
                priority,
            } => {
                let mut cmd = self.build_command();
                cmd.arg("update").arg(issue_id);

                if let Some(s) = status {
                    cmd.arg("--status").arg(s.as_str());
                }
                if let Some(p) = priority {
                    cmd.arg("--priority").arg(p.to_string());
                }

                cmd.output().context("Failed to execute update command")?
            }

            BeadsAction::Close { issue_id, reason } => {
                let mut cmd = self.build_command();
                cmd.arg("close").arg(issue_id).arg("--reason").arg(reason);
                cmd.output().context("Failed to execute close command")?
            }

            BeadsAction::Reopen { issue_id } => {
                let mut cmd = self.build_command();
                cmd.arg("reopen").arg(issue_id);
                cmd.output().context("Failed to execute reopen command")?
            }

            BeadsAction::AddDependency {
                issue_id,
                depends_on,
                dep_type,
            } => {
                let mut cmd = self.build_command();
                cmd.arg("dep")
                    .arg("add")
                    .arg(issue_id)
                    .arg(depends_on)
                    .arg("-t")
                    .arg(dep_type.as_str());
                cmd.output().context("Failed to execute dep add command")?
            }

            BeadsAction::Export { output } => {
                let mut cmd = self.build_command();
                cmd.arg("export").arg("--output").arg(output);
                cmd.output().context("Failed to execute export command")?
            }
        };

        Ok(ExecutionResult {
            success: output.status.success(),
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            exit_code: output.status.code(),
            actual_issue_id,
        })
    }

    /// Execute a sequence of actions
    #[allow(dead_code)]
    pub fn execute_sequence(&self, actions: &[BeadsAction]) -> Result<Vec<ExecutionResult>> {
        let mut results = Vec::new();
        for action in actions {
            let result = self.execute(action)?;
            results.push(result);
        }
        Ok(results)
    }
}

/// Extract issue ID from create command output
///
/// Looks for patterns like:
/// - "Created issue: test-1" (sequential)
/// - "Created: test-1" (sequential)
/// - "Created issue: test-4f10" (hash)
/// - "Created: test-4f10" (hash)
fn extract_issue_id(output: &str) -> Option<String> {
    // Try to find issue ID in various formats
    for line in output.lines() {
        // Look for "Created issue: <id>"
        if let Some(pos) = line.find("Created issue:") {
            let id = line[pos + 14..].trim();
            if !id.is_empty() {
                return Some(id.to_string());
            }
        }

        // Look for "Created: <id>"
        if let Some(pos) = line.find("Created:") {
            let id = line[pos + 8..].trim();
            if !id.is_empty() {
                return Some(id.to_string());
            }
        }

        // Look for issue ID pattern (prefix-number or prefix-hexhash)
        let words: Vec<&str> = line.split_whitespace().collect();
        for word in words {
            if word.contains('-') {
                let suffix = word.split('-').next_back().unwrap_or("");

                // Check if it's a sequential number
                if suffix.parse::<usize>().is_ok() {
                    return Some(word.to_string());
                }

                // Check if it's a hex hash (4-8 hex characters)
                if (4..=8).contains(&suffix.len()) && suffix.chars().all(|c| c.is_ascii_hexdigit())
                {
                    return Some(word.to_string());
                }
            }
        }
    }

    None
}

/// Result of executing a beads action
#[derive(Debug, Clone)]
pub struct ExecutionResult {
    pub success: bool,
    pub stdout: String,
    pub stderr: String,
    pub exit_code: Option<i32>,
    /// For Create actions, the actual issue ID that was created
    pub actual_issue_id: Option<String>,
}

/// Reference interpreter for beads actions
///
/// Maintains an in-memory representation of the beads state by interpreting
/// BeadsAction sequences. This provides a "golden state" for verification.
pub struct ReferenceInterpreter {
    pub issues: std::collections::HashMap<String, ReferenceIssue>,
    pub prefix: String,
    pub next_id: usize,
    pub use_hash_ids: bool,
}

/// Simplified issue representation for reference interpreter
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReferenceIssue {
    pub id: String,
    pub title: String,
    pub description: String,
    pub status: Status,
    pub priority: i32,
    pub issue_type: IssueType,
    pub depends_on: std::collections::HashMap<String, DependencyType>,
}

impl ReferenceInterpreter {
    /// Create a new reference interpreter with the given prefix
    pub fn new(prefix: String) -> Self {
        Self {
            issues: std::collections::HashMap::new(),
            prefix,
            next_id: 1,
            use_hash_ids: false,
        }
    }

    /// Create a new reference interpreter with hash IDs enabled
    pub fn new_with_hash_ids(prefix: String) -> Self {
        Self {
            issues: std::collections::HashMap::new(),
            prefix,
            next_id: 1,
            use_hash_ids: true,
        }
    }

    /// Execute an action, updating the internal state
    pub fn execute(&mut self, action: &BeadsAction) -> Result<()> {
        match action {
            BeadsAction::Init {
                prefix,
                mb_hash_ids,
            } => {
                if let Some(p) = prefix {
                    self.prefix = p.clone();
                }
                if let Some(use_hash) = mb_hash_ids {
                    self.use_hash_ids = *use_hash;
                }
                Ok(())
            }

            BeadsAction::Create {
                expected_id,
                title,
                priority,
                issue_type,
                description,
            } => {
                // For hash mode, the expected_id has already been replaced with the actual ID
                // by the test harness, so we just use it directly
                // For numeric mode, verify it matches the expected sequential ID
                if !self.use_hash_ids {
                    let computed_id = format!("{}-{}", self.prefix, self.next_id);
                    if *expected_id != computed_id {
                        anyhow::bail!(
                            "Reference interpreter ID mismatch: expected {}, got {}",
                            computed_id,
                            expected_id
                        );
                    }
                }

                let issue = ReferenceIssue {
                    id: expected_id.clone(),
                    title: title.clone(),
                    description: description.clone().unwrap_or_default(),
                    status: Status::Open,
                    priority: *priority,
                    issue_type: *issue_type,
                    depends_on: std::collections::HashMap::new(),
                };

                self.issues.insert(expected_id.clone(), issue);
                self.next_id += 1;
                Ok(())
            }

            BeadsAction::List { .. } => {
                // List doesn't modify state
                Ok(())
            }

            BeadsAction::Show { .. } => {
                // Show doesn't modify state
                Ok(())
            }

            BeadsAction::Update {
                issue_id,
                status,
                priority,
            } => {
                if let Some(issue) = self.issues.get_mut(issue_id) {
                    if let Some(s) = status {
                        issue.status = *s;
                    }
                    if let Some(p) = priority {
                        issue.priority = *p;
                    }
                }
                // Silently ignore updates to non-existent issues (matches bd behavior)
                Ok(())
            }

            BeadsAction::Close { issue_id, .. } => {
                if let Some(issue) = self.issues.get_mut(issue_id) {
                    issue.status = Status::Closed;
                }
                Ok(())
            }

            BeadsAction::Reopen { issue_id } => {
                if let Some(issue) = self.issues.get_mut(issue_id) {
                    issue.status = Status::Open;
                }
                Ok(())
            }

            BeadsAction::AddDependency {
                issue_id,
                depends_on,
                dep_type,
            } => {
                if let Some(issue) = self.issues.get_mut(issue_id) {
                    issue.depends_on.insert(depends_on.clone(), *dep_type);
                }
                Ok(())
            }

            BeadsAction::Export { .. } => {
                // Export doesn't modify state
                Ok(())
            }
        }
    }

    /// Get the final state as a reference to the issues HashMap
    pub fn get_final_state(&self) -> &std::collections::HashMap<String, ReferenceIssue> {
        &self.issues
    }

    /// Get the current prefix
    pub fn get_prefix(&self) -> &str {
        &self.prefix
    }

    /// Get the next expected issue ID
    pub fn get_next_id(&self) -> usize {
        self.next_id
    }
}