tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
//! Short, collision-resistant issue identifiers.
//!
//! An issue id is an **8-character Crockford base32** string (40 random bits),
//! generated with no coordination: two `tix create` runs, in two clones, on two
//! branches, produce different ids with overwhelming probability, so a new issue
//! is globally identifiable without a shared allocator. It is the canonical
//! machine identity; the integer [`crate::model::Issue::number`] stays the
//! human-facing, per-checkout alias and is allowed to collide across branches.
//!
//! The alphabet is Crockford base32 (`0-9`, then `A-Z` minus `I`, `L`, `O`,
//! `U`), the same one relationship ids use. Two properties matter:
//!
//! - **Case-insensitive** — an id is stored uppercase and matched with
//!   [`eq_ignore_ascii_case`], so `1a2b3c4d` selects the same issue as
//!   `1A2B3C4D`.
//! - **Never numeric** — the first character is drawn from the 22 letter
//!   symbols, so an id can never be all digits and can never be mistaken for an
//!   issue number by the selector grammar (a purely numeric selector stays the
//!   fast `number` path; see [`crate::commands::parse_selector`]).

use std::collections::BTreeMap;
use std::fmt;
use std::hash::{BuildHasher, Hasher};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Crockford base32 alphabet: no `I`, `L`, `O`, or `U`.
pub(crate) const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";

/// Index of the first letter symbol in [`CROCKFORD`] (i.e. the end of `0..=9`).
const FIRST_LETTER: u64 = 10;

/// An issue id is exactly this many Crockford base32 characters.
pub const ISSUE_ID_LEN: usize = 8;

/// Encode the low `width * 5` bits of `value` as `width` Crockford base32
/// characters, most significant first.
pub(crate) fn crockford(value: u128, width: usize) -> String {
    let mut out = vec![b'0'; width];
    let mut remaining = value;
    for slot in out.iter_mut().rev() {
        *slot = CROCKFORD[(remaining & 0x1F) as usize];
        remaining >>= 5;
    }
    String::from_utf8(out).expect("Crockford alphabet is ASCII")
}

/// Generate a fresh issue id: [`ISSUE_ID_LEN`] Crockford base32 characters.
///
/// Randomness comes from the OS-seeded hasher state plus a process-local
/// counter and the wall clock, so the crate keeps **zero new dependencies**
/// (the same approach [`crate::relationships::generate_relationship_id`] uses).
/// The first character is a letter by construction, so the result is never a
/// bare integer.
pub fn generate_issue_id() -> String {
    use std::sync::LazyLock;

    static COUNTER: AtomicU64 = AtomicU64::new(0);
    // One OS-seeded random value per process, so ids from the same run are
    // independent of every other run.
    static SEED: LazyLock<u64> = LazyLock::new(|| {
        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
        hasher.write_u64(0);
        hasher.finish()
    });

    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);
    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    // Mix seed, wall clock and counter with a full-avalanche finalizer so every
    // bit of the result depends on every input bit. Sampling the low 40 bits of
    // the *raw* hash lost most of its entropy (the OR-masked variant produced
    // hundreds of duplicates per 10 000 ids); this does not.
    let mut bits =
        splitmix64(*SEED ^ millis.rotate_left(32) ^ counter.wrapping_mul(0x9E37_79B9_7F4A_7C15));

    let mut out = String::with_capacity(ISSUE_ID_LEN);
    // Leading letter: `FIRST_LETTER..32`.
    out.push(CROCKFORD[(FIRST_LETTER + (bits % (32 - FIRST_LETTER))) as usize] as char);
    bits /= 32 - FIRST_LETTER;
    for _ in 1..ISSUE_ID_LEN {
        out.push(CROCKFORD[(bits & 0x1F) as usize] as char);
        bits >>= 5;
    }
    out
}

/// A full-avalanche 64-bit mixer (splitmix64's finalizer).
fn splitmix64(mut z: u64) -> u64 {
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// Whether `s` is syntactically an issue id: [`ISSUE_ID_LEN`] Crockford base32
/// characters whose first symbol is a letter.
///
/// Case-insensitive, matching the storage convention (ids are written
/// uppercase). This is a shape check, not a lookup — an issue whose id this
/// accepts may still not exist.
#[must_use]
pub fn is_issue_id(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.len() != ISSUE_ID_LEN || !bytes[0].is_ascii_alphabetic() {
        return false;
    }
    bytes
        .iter()
        .all(|b| CROCKFORD.contains(&b.to_ascii_uppercase()))
}

/// A reference to one issue in the local graph.
///
/// Canonical ids are the only identity written by current code. A numeric value
/// exists solely as an input and migration alias for data created before issue
/// ids became authoritative.
#[derive(Debug, Clone, Copy)]
pub enum IssueRef {
    /// The collision-resistant canonical issue id, stored uppercase.
    Id {
        /// The fixed-width Crockford identity.
        id: [u8; ISSUE_ID_LEN],
        /// The resolved human alias, when the identity was built from an issue.
        number: Option<u32>,
    },
    /// A human-facing issue number alias.
    Number(u32),
}

impl IssueRef {
    /// Build a canonical id reference, validating the id's shape.
    pub fn id(value: impl Into<String>) -> Option<Self> {
        let value = value.into();
        let value = value.trim();
        if !is_issue_id(value) {
            return None;
        }
        let mut bytes = [0; ISSUE_ID_LEN];
        for (slot, byte) in bytes.iter_mut().zip(value.bytes()) {
            *slot = byte.to_ascii_uppercase();
        }
        Some(Self::Id {
            id: bytes,
            number: None,
        })
    }

    /// A numeric alias.
    pub const fn number(value: u32) -> Self {
        Self::Number(value)
    }

    /// Attach the resolved human alias to a canonical reference.
    #[must_use]
    pub fn with_number(self, value: u32) -> Self {
        match self {
            Self::Id { id, .. } => Self::Id {
                id,
                number: Some(value),
            },
            Self::Number(_) => self,
        }
    }

    /// The canonical id, when this reference already names one.
    #[must_use]
    pub fn as_id(&self) -> Option<&str> {
        match self {
            Self::Id { id, .. } => std::str::from_utf8(id).ok(),
            Self::Number(_) => None,
        }
    }

    /// The numeric alias, when this reference stores one.
    #[must_use]
    pub const fn as_number(&self) -> Option<u32> {
        match self {
            Self::Id { number, .. } => *number,
            Self::Number(number) => Some(*number),
        }
    }

    /// A stable key used for ordering and graph maps.
    #[must_use]
    pub fn key(&self) -> String {
        match self {
            Self::Id { id, .. } => String::from_utf8_lossy(id).into_owned(),
            Self::Number(number) => format!("#{number}"),
        }
    }

    /// Stable ordering key that preserves the established human-facing order.
    ///
    /// Canonical ids remain the edge identity. The numeric alias is used only to
    /// choose an arbitrary orientation for non-directional edges, a decision that
    /// predates canonical ids and must not change with random id values.
    #[must_use]
    pub fn order_key(&self) -> (u32, String) {
        (self.as_number().unwrap_or(u32::MAX), self.key())
    }

    /// Display the human alias when this reference carries one, else its id.
    #[must_use]
    pub fn human(&self) -> String {
        self.as_number()
            .map_or_else(|| self.to_string(), |number| format!("#{number}"))
    }
}

impl fmt::Display for IssueRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Id { id, .. } => f.write_str(&String::from_utf8_lossy(id)),
            Self::Number(number) => write!(f, "#{number}"),
        }
    }
}

impl PartialEq for IssueRef {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Id { id: left, .. }, Self::Id { id: right, .. }) => left == right,
            (Self::Number(left), Self::Number(right)) => left == right,
            _ => false,
        }
    }
}

impl Eq for IssueRef {}

impl std::hash::Hash for IssueRef {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            Self::Id { id, .. } => {
                0u8.hash(state);
                id.hash(state);
            }
            Self::Number(number) => {
                1u8.hash(state);
                number.hash(state);
            }
        }
    }
}

impl PartialOrd for IssueRef {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for IssueRef {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match (self, other) {
            (Self::Id { id: left, .. }, Self::Id { id: right, .. }) => left.cmp(right),
            (Self::Number(left), Self::Number(right)) => left.cmp(right),
            (Self::Id { .. }, Self::Number(_)) => std::cmp::Ordering::Less,
            (Self::Number(_), Self::Id { .. }) => std::cmp::Ordering::Greater,
        }
    }
}

impl From<u32> for IssueRef {
    fn from(value: u32) -> Self {
        Self::Number(value)
    }
}

impl PartialEq<u32> for IssueRef {
    fn eq(&self, other: &u32) -> bool {
        self.as_number() == Some(*other)
    }
}

impl PartialEq<IssueRef> for u32 {
    fn eq(&self, other: &IssueRef) -> bool {
        other.as_number() == Some(*self)
    }
}

impl From<&str> for IssueRef {
    fn from(value: &str) -> Self {
        Self::id(value).unwrap_or_else(|| {
            value.parse::<u32>().map_or_else(
                |_| Self::Id {
                    id: id_bytes_lossy(value),
                    number: None,
                },
                Self::Number,
            )
        })
    }
}

fn id_bytes_lossy(value: &str) -> [u8; ISSUE_ID_LEN] {
    let mut bytes = [b'0'; ISSUE_ID_LEN];
    for (slot, byte) in bytes.iter_mut().zip(value.bytes().take(ISSUE_ID_LEN)) {
        *slot = byte.to_ascii_uppercase();
    }
    bytes
}

impl From<String> for IssueRef {
    fn from(value: String) -> Self {
        Self::from(value.as_str())
    }
}

impl FromStr for IssueRef {
    type Err = std::convert::Infallible;

    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        Ok(Self::from(value))
    }
}

impl Serialize for IssueRef {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        match self {
            Self::Id { id, .. } => serializer.serialize_str(&String::from_utf8_lossy(id)),
            Self::Number(number) => serializer.serialize_u32(*number),
        }
    }
}

impl<'de> Deserialize<'de> for IssueRef {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        struct Visitor;

        impl serde::de::Visitor<'_> for Visitor {
            type Value = IssueRef;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("an 8-character issue id or a numeric issue alias")
            }

            fn visit_u64<E: serde::de::Error>(
                self,
                value: u64,
            ) -> std::result::Result<Self::Value, E> {
                u32::try_from(value)
                    .map(IssueRef::Number)
                    .map_err(|_| E::custom(format!("issue alias {value} exceeds u32")))
            }

            fn visit_str<E: serde::de::Error>(
                self,
                value: &str,
            ) -> std::result::Result<Self::Value, E> {
                let value = value.trim();
                if let Some(reference) = IssueRef::id(value) {
                    return Ok(reference);
                }
                Err(E::custom(format!(
                    "`{value}` is not an 8-character issue id"
                )))
            }
        }

        deserializer.deserialize_any(Visitor)
    }
}

/// The fields identity resolution needs from an issue-like value.
pub trait IdentityNode {
    /// The canonical issue id, when this record has one.
    fn canonical_id(&self) -> Option<&str>;
    /// The human-facing number alias.
    fn issue_number(&self) -> u32;
    /// The store-relative filename.
    fn issue_filename(&self) -> &str;
    /// The current title.
    fn issue_title(&self) -> &str;
}

/// The canonical reference for one identity node.
#[must_use]
pub fn canonical_ref<N: IdentityNode + ?Sized>(node: &N) -> IssueRef {
    node.canonical_id()
        .and_then(IssueRef::id)
        .map(|reference| reference.with_number(node.issue_number()))
        .unwrap_or_else(|| IssueRef::Number(node.issue_number()))
}

/// Why a selector or stored alias did not resolve to one canonical reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AliasError {
    /// No issue carries the alias.
    Missing(String),
    /// More than one issue carries the alias.
    Ambiguous {
        /// The alias as supplied.
        alias: String,
        /// Every canonical reference the alias matches.
        candidates: Vec<IssueRef>,
    },
    /// Two records claim one canonical id.
    DuplicateId {
        /// The duplicated canonical id.
        id: String,
        /// Every issue number claiming it.
        numbers: Vec<u32>,
    },
}

/// One file participating in a duplicated canonical identity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DuplicateIdentityRecord {
    /// The duplicated canonical id.
    pub id: String,
    /// The human-facing number claimed by the file.
    pub number: u32,
    /// The store-relative filename claiming the id.
    pub filename: String,
}

/// One project-wide index from every accepted alias to a canonical issue reference.
///
/// The index is built once per read operation. Numbers, filenames, and titles are
/// aliases; ids are identity. Duplicate ids are recorded and make the index
/// unusable for graph work rather than allowing one file to shadow another.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AliasIndex {
    /// How many input records the one index-building pass examined.
    scanned_nodes: usize,
    by_id: BTreeMap<String, IssueRef>,
    by_number: BTreeMap<u32, Vec<IssueRef>>,
    by_filename: BTreeMap<String, Vec<IssueRef>>,
    by_title: BTreeMap<String, Vec<IssueRef>>,
    duplicate_ids: BTreeMap<String, Vec<u32>>,
    duplicate_id_files: BTreeMap<String, Vec<String>>,
    duplicate_records: Vec<DuplicateIdentityRecord>,
    canonical: BTreeMap<IssueRef, IssueRef>,
}

impl AliasIndex {
    /// How many canonical issues the index holds.
    #[must_use]
    pub fn len(&self) -> usize {
        self.canonical.len()
    }

    /// Whether the index contains no issue records.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.canonical.is_empty()
    }

    /// How many issue records the single index-building pass examined.
    #[must_use]
    pub fn scanned_nodes(&self) -> usize {
        self.scanned_nodes
    }

    /// Build the complete alias index over one issue snapshot.
    pub fn build<N: IdentityNode>(nodes: &[N]) -> Self {
        let mut index = Self::default();
        let mut id_records: BTreeMap<String, Vec<(u32, String)>> = BTreeMap::new();
        for node in nodes {
            index.scanned_nodes += 1;
            let canonical = canonical_ref(node);
            index.canonical.insert(canonical, canonical);
            index
                .by_number
                .entry(node.issue_number())
                .or_default()
                .push(canonical);
            index
                .by_filename
                .entry(node.issue_filename().to_string())
                .or_default()
                .push(canonical);
            index
                .by_title
                .entry(node.issue_title().to_string())
                .or_default()
                .push(canonical);
            if let Some(id) = node.canonical_id().and_then(IssueRef::id) {
                let key = id.key();
                index.by_id.insert(key.clone(), canonical);
                id_records
                    .entry(key)
                    .or_default()
                    .push((node.issue_number(), node.issue_filename().to_string()));
            }
        }
        for (id, records) in id_records
            .into_iter()
            .filter(|(_, records)| records.len() > 1)
        {
            let mut numbers: Vec<u32> = records.iter().map(|(number, _)| *number).collect();
            numbers.sort_unstable();
            numbers.dedup();
            let mut files: Vec<String> = records
                .iter()
                .map(|(_, filename)| filename.clone())
                .collect();
            files.sort();
            files.dedup();
            index.duplicate_ids.insert(id.clone(), numbers);
            index.duplicate_id_files.insert(id.clone(), files);
            index
                .duplicate_records
                .extend(
                    records
                        .into_iter()
                        .map(|(number, filename)| DuplicateIdentityRecord {
                            id: id.clone(),
                            number,
                            filename,
                        }),
                );
        }
        index.duplicate_records.sort_by(|left, right| {
            (&left.id, left.number, &left.filename).cmp(&(&right.id, right.number, &right.filename))
        });
        for values in index
            .by_number
            .values_mut()
            .chain(index.by_filename.values_mut())
            .chain(index.by_title.values_mut())
        {
            values.sort();
            values.dedup();
        }
        index
    }

    /// Every duplicated canonical id, in stable order.
    #[must_use]
    pub fn duplicate_ids(&self) -> &BTreeMap<String, Vec<u32>> {
        &self.duplicate_ids
    }

    /// Every filename claiming each duplicated canonical id, in stable order.
    #[must_use]
    pub fn duplicate_id_files(&self) -> &BTreeMap<String, Vec<String>> {
        &self.duplicate_id_files
    }

    /// One record per file claiming a duplicated canonical id.
    #[must_use]
    pub fn duplicate_records(&self) -> &[DuplicateIdentityRecord] {
        &self.duplicate_records
    }

    /// Resolve a stored graph reference or selector alias to one canonical reference.
    pub fn resolve(&self, reference: &IssueRef) -> std::result::Result<IssueRef, AliasError> {
        match reference {
            IssueRef::Id { .. } => {
                let key = reference.key();
                if let Some(numbers) = self.duplicate_ids.get(&key) {
                    return Err(AliasError::DuplicateId {
                        id: key,
                        numbers: numbers.clone(),
                    });
                }
                self.by_id
                    .get(&key)
                    .copied()
                    .ok_or(AliasError::Missing(key))
            }
            IssueRef::Number(number) => self.resolve_number(*number),
        }
    }

    /// Resolve a numeric alias, refusing ambiguity.
    pub fn resolve_number(&self, number: u32) -> std::result::Result<IssueRef, AliasError> {
        Self::resolve_many(
            &self.by_number.get(&number).cloned().unwrap_or_default(),
            number.to_string(),
        )
    }

    /// Resolve an exact filename alias, refusing ambiguity.
    pub fn resolve_filename(&self, filename: &str) -> std::result::Result<IssueRef, AliasError> {
        Self::resolve_many(
            &self.by_filename.get(filename).cloned().unwrap_or_default(),
            filename.to_string(),
        )
    }

    /// Resolve an exact title alias, refusing ambiguity.
    pub fn resolve_title(&self, title: &str) -> std::result::Result<IssueRef, AliasError> {
        Self::resolve_many(
            &self.by_title.get(title).cloned().unwrap_or_default(),
            title.to_string(),
        )
    }

    fn resolve_many(
        candidates: &[IssueRef],
        alias: String,
    ) -> std::result::Result<IssueRef, AliasError> {
        match candidates {
            [] => Err(AliasError::Missing(alias)),
            [one] => Ok(*one),
            many => Err(AliasError::Ambiguous {
                alias,
                candidates: many.to_vec(),
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn crockford_encodes_fixed_width_and_excludes_ambiguous_letters() {
        assert_eq!(crockford(0, 8), "00000000");
        assert_eq!(crockford(31, 8), "0000000Z");
        assert_eq!(crockford(32u128, 2), "10");
        // Crockford omits I, L, O and U.
        for b in b"ILOU" {
            assert!(!CROCKFORD.contains(b), "{b} must not be in the alphabet");
        }
    }

    #[test]
    fn generated_ids_are_eight_crockford_chars_and_never_numeric() {
        for _ in 0..1_000 {
            let id = generate_issue_id();
            assert_eq!(id.len(), ISSUE_ID_LEN, "{id}");
            assert!(
                id.parse::<u32>().is_err(),
                "id {id} must not parse as an issue number"
            );
            assert!(is_issue_id(&id), "{id} must be a valid id");
        }
    }

    #[test]
    fn generated_ids_are_distinct_within_a_process() {
        let ids: HashSet<String> = (0..10_000).map(|_| generate_issue_id()).collect();
        assert_eq!(ids.len(), 10_000);
    }

    #[test]
    fn is_issue_id_is_case_insensitive_and_rejects_bad_shapes() {
        let id = generate_issue_id();
        assert!(is_issue_id(&id));
        assert!(is_issue_id(&id.to_ascii_lowercase()));
        assert!(!is_issue_id("12345678"), "all digits is not an id");
        assert!(!is_issue_id("1234567"), "too short");
        assert!(!is_issue_id("123456789"), "too long");
        assert!(!is_issue_id("ABCDEFGI"), "I is not in the alphabet");
        assert!(!is_issue_id(""), "empty");
    }

    #[test]
    fn canonical_graph_references_serialize_ids_and_read_numeric_migration_aliases() {
        let id = IssueRef::id("a1b2c3d4").unwrap();
        assert_eq!(serde_yaml::to_string(&id).unwrap().trim(), "A1B2C3D4");
        let from_id: IssueRef = serde_yaml::from_str("A1B2C3D4").unwrap();
        assert_eq!(from_id, id);
        let alias: IssueRef = serde_yaml::from_str("7").unwrap();
        assert_eq!(alias, IssueRef::Number(7));
        assert!(serde_yaml::from_str::<IssueRef>("'7'").is_err());
    }

    struct Node {
        id: Option<&'static str>,
        number: u32,
        filename: &'static str,
        title: &'static str,
    }

    impl IdentityNode for Node {
        fn canonical_id(&self) -> Option<&str> {
            self.id
        }
        fn issue_number(&self) -> u32 {
            self.number
        }
        fn issue_filename(&self) -> &str {
            self.filename
        }
        fn issue_title(&self) -> &str {
            self.title
        }
    }

    #[test]
    fn alias_index_resolves_unique_aliases_and_refuses_missing_ambiguous_and_duplicate_ids() {
        let nodes = [
            Node {
                id: Some("A1B2C3D4"),
                number: 1,
                filename: "one.md",
                title: "One",
            },
            Node {
                id: Some("B1B2C3D4"),
                number: 2,
                filename: "two.md",
                title: "Two",
            },
        ];
        let index = AliasIndex::build(&nodes);
        assert_eq!(
            index.resolve_number(1).unwrap(),
            IssueRef::id("A1B2C3D4").unwrap()
        );
        assert!(matches!(
            index.resolve_number(9),
            Err(AliasError::Missing(_))
        ));

        let ambiguous = [
            nodes[0].id.map(|_| "A1B2C3D4"),
            nodes[1].id.map(|_| "B1B2C3D4"),
        ]
        .into_iter()
        .enumerate()
        .map(|(i, id)| Node {
            id,
            number: 7,
            filename: if i == 0 { "a.md" } else { "b.md" },
            title: if i == 0 { "A" } else { "B" },
        })
        .collect::<Vec<_>>();
        let index = AliasIndex::build(&ambiguous);
        assert!(matches!(
            index.resolve_number(7),
            Err(AliasError::Ambiguous { .. })
        ));

        let duplicates = [
            Node {
                id: Some("A1B2C3D4"),
                number: 1,
                filename: "a.md",
                title: "A",
            },
            Node {
                id: Some("A1B2C3D4"),
                number: 2,
                filename: "b.md",
                title: "B",
            },
        ];
        let index = AliasIndex::build(&duplicates);
        assert_eq!(index.duplicate_ids().get("A1B2C3D4"), Some(&vec![1, 2]));
        assert_eq!(
            index.duplicate_id_files().get("A1B2C3D4"),
            Some(&vec!["a.md".to_string(), "b.md".to_string()])
        );
        assert_eq!(
            index
                .duplicate_records()
                .iter()
                .map(|record| (record.number, record.filename.as_str()))
                .collect::<Vec<_>>(),
            vec![(1, "a.md"), (2, "b.md")]
        );
        assert!(matches!(
            index.resolve(&IssueRef::id("A1B2C3D4").unwrap()),
            Err(AliasError::DuplicateId { .. })
        ));
    }
}