bones-core 0.24.6

Core data structures, CRDT event model, and projection engine for bones
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
//! Validated identifier type for work items.
//!
//! All work items in bones carry a `bn-XXXX` identifier generated by the
//! [`terseid`] library.  `ItemId` is a validated newtype that wraps the
//! raw string and delegates to `terseid` for generation, parsing, and
//! resolution.

use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};
use terseid::{
    IdConfig, IdGenerator, IdResolver, ParsedId, ResolverConfig, child_id as terseid_child_id,
    id_depth as terseid_id_depth, is_child_id as terseid_is_child_id, parse_id,
};

/// The prefix used for all bones work-item identifiers.
pub const BONES_PREFIX: &str = "bn";

// ---------------------------------------------------------------------------
// Core type
// ---------------------------------------------------------------------------

/// A validated work-item identifier (e.g. `bn-a7x`, `bn-a7x.1`).
///
/// The inner string is guaranteed to be a valid terseid ID with the `bn` prefix.
/// Construction goes through [`FromStr`], [`ItemId::new_unchecked`], or the
/// generator helpers.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct ItemId(String);

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors that arise when constructing or resolving an [`ItemId`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ItemIdError {
    /// The raw string does not match the `<prefix>-<hash>[.<child>…]` pattern.
    InvalidFormat(String),
    /// The ID has a valid format but the wrong prefix.
    WrongPrefix { expected: String, found: String },
    /// Partial input matched more than one existing ID.
    Ambiguous {
        partial: String,
        matches: Vec<String>,
    },
    /// Partial input matched zero existing IDs.
    NotFound(String),
}

impl fmt::Display for ItemIdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidFormat(raw) => write!(f, "invalid item ID format: '{raw}'"),
            Self::WrongPrefix { expected, found } => {
                write!(f, "expected prefix '{expected}', found '{found}'")
            }
            Self::Ambiguous { partial, matches } => {
                write!(f, "ambiguous ID '{partial}': matches {matches:?}")
            }
            Self::NotFound(id) => write!(f, "item ID not found: '{id}'"),
        }
    }
}

impl std::error::Error for ItemIdError {}

// ---------------------------------------------------------------------------
// Construction & validation
// ---------------------------------------------------------------------------

impl ItemId {
    /// Create an `ItemId` without validation.
    ///
    /// # Safety (logical)
    ///
    /// The caller **must** ensure `raw` is a valid terseid ID with the correct
    /// prefix.  Prefer [`FromStr`] or the generator helpers in production code.
    #[must_use]
    pub fn new_unchecked(raw: impl Into<String>) -> Self {
        Self(raw.into())
    }

    /// Parse and validate a raw string into an `ItemId`.
    ///
    /// The string is lower-cased and trimmed before validation.
    ///
    /// # Errors
    ///
    /// Returns [`ItemIdError::InvalidFormat`] if the format is wrong, or
    /// [`ItemIdError::WrongPrefix`] if the prefix is not `bn`.
    pub fn parse(raw: &str) -> Result<Self, ItemIdError> {
        let normalized = raw.trim().to_lowercase();

        // Validate via terseid
        let parsed =
            parse_id(&normalized).map_err(|_| ItemIdError::InvalidFormat(raw.to_string()))?;

        if parsed.prefix != BONES_PREFIX {
            return Err(ItemIdError::WrongPrefix {
                expected: BONES_PREFIX.to_string(),
                found: parsed.prefix,
            });
        }

        Ok(Self(parsed.to_id_string()))
    }

    /// Parse any valid terseid ID regardless of prefix.
    ///
    /// Used by the event parser and migration paths where IDs from external
    /// systems (e.g. beads with custom prefixes) must be accepted.
    ///
    /// # Errors
    ///
    /// Returns [`ItemIdError::InvalidFormat`] if the string is not a valid
    /// terseid ID.
    pub fn parse_any_prefix(raw: &str) -> Result<Self, ItemIdError> {
        let normalized = raw.trim().to_lowercase();
        let parsed =
            parse_id(&normalized).map_err(|_| ItemIdError::InvalidFormat(raw.to_string()))?;
        Ok(Self(parsed.to_id_string()))
    }

    /// Return the raw ID string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Parse the inner string into a terseid [`ParsedId`].
    ///
    /// This never fails because `ItemId` guarantees validity at construction.
    ///
    /// # Panics
    ///
    /// Panics if the internal invariant is broken (the stored string is not a
    /// valid terseid ID).  This should never happen through the public API.
    #[must_use]
    pub fn parsed(&self) -> ParsedId {
        parse_id(&self.0).expect("ItemId invariant broken")
    }

    /// Return `true` if this is a root ID (no child path segments).
    #[must_use]
    pub fn is_root(&self) -> bool {
        !terseid_is_child_id(&self.0)
    }

    /// Return `true` if this is a child ID (has child path segments).
    #[must_use]
    pub fn is_child(&self) -> bool {
        terseid_is_child_id(&self.0)
    }

    /// Depth of the child path (0 for root IDs).
    #[must_use]
    pub fn depth(&self) -> usize {
        terseid_id_depth(&self.0)
    }

    /// Create a child ID by appending a child number.
    ///
    /// ```
    /// # use bones_core::model::item_id::ItemId;
    /// let parent = ItemId::parse("bn-a7x").unwrap();
    /// let child = parent.child(1);
    /// assert_eq!(child.as_str(), "bn-a7x.1");
    /// ```
    #[must_use]
    pub fn child(&self, number: u32) -> Self {
        Self(terseid_child_id(&self.0, number))
    }

    /// Return the parent `ItemId`, or `None` if this is a root.
    #[must_use]
    pub fn parent(&self) -> Option<Self> {
        self.parsed().parent().map(Self)
    }

    /// Return `true` if `self` is a descendant of `ancestor`.
    #[must_use]
    pub fn is_child_of(&self, ancestor: &Self) -> bool {
        self.parsed().is_child_of(ancestor.as_str())
    }
}

// ---------------------------------------------------------------------------
// Trait implementations
// ---------------------------------------------------------------------------

impl FromStr for ItemId {
    type Err = ItemIdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl fmt::Display for ItemId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for ItemId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl From<ItemId> for String {
    fn from(id: ItemId) -> Self {
        id.0
    }
}

impl TryFrom<String> for ItemId {
    type Error = ItemIdError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(&value)
    }
}

// ---------------------------------------------------------------------------
// Generator helper
// ---------------------------------------------------------------------------

/// Create a configured [`IdGenerator`] with the `bn` prefix and sensible
/// defaults for a bones repository.
#[must_use]
pub fn bones_id_generator() -> IdGenerator {
    IdGenerator::new(IdConfig::new(BONES_PREFIX))
}

/// Generate a new `ItemId` from a seed and current item count.
///
/// `seed` — typically `format!("{title}\0{nonce}")`.
/// `item_count` — current number of existing items (drives adaptive length).
/// `exists` — returns `true` if a candidate ID is already taken.
pub fn generate_item_id(seed: &str, item_count: usize, exists: impl Fn(&str) -> bool) -> ItemId {
    let generator = bones_id_generator();
    let id = generator.generate(
        |nonce| format!("{seed}\0{nonce}").into_bytes(),
        item_count,
        &exists,
    );
    ItemId(id)
}

// ---------------------------------------------------------------------------
// Resolver helper
// ---------------------------------------------------------------------------

/// Resolve partial CLI input into a full `ItemId`.
///
/// Resolution order (delegated to [`terseid::IdResolver`]):
/// 1. Exact match (case-insensitive)
/// 2. Prefix normalisation — bare hash `a7x` becomes `bn-a7x`
/// 3. Substring match on the hash portion
///
/// `exists` — returns `true` if a full ID exists.
/// `substring_match` — returns all full IDs whose hash contains the input.
///
/// # Errors
///
/// * [`ItemIdError::Ambiguous`] — substring matched more than one ID.
/// * [`ItemIdError::NotFound`] — no match at all.
pub fn resolve_item_id(
    input: &str,
    exists: impl Fn(&str) -> bool,
    substring_match: impl Fn(&str) -> Vec<String>,
) -> Result<ItemId, ItemIdError> {
    let cfg = ResolverConfig::new(BONES_PREFIX);
    let id_resolver = IdResolver::new(cfg);

    let result = id_resolver
        .resolve(input, &exists, &substring_match)
        .map_err(|e| match e {
            terseid::TerseIdError::AmbiguousId { partial, matches } => {
                ItemIdError::Ambiguous { partial, matches }
            }
            terseid::TerseIdError::NotFound { id } => ItemIdError::NotFound(id),
            other => ItemIdError::InvalidFormat(other.to_string()),
        })?;

    // The resolved ID came from the known-good set, so it is valid.
    Ok(ItemId(result.id))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // === Construction & validation ==========================================

    #[test]
    fn parse_valid_root_id() {
        let id = ItemId::parse("bn-a7x").unwrap();
        assert_eq!(id.as_str(), "bn-a7x");
        assert!(id.is_root());
        assert!(!id.is_child());
        assert_eq!(id.depth(), 0);
    }

    #[test]
    fn parse_valid_child_id() {
        let id = ItemId::parse("bn-a7x.1").unwrap();
        assert_eq!(id.as_str(), "bn-a7x.1");
        assert!(!id.is_root());
        assert!(id.is_child());
        assert_eq!(id.depth(), 1);
    }

    #[test]
    fn parse_valid_grandchild_id() {
        let id = ItemId::parse("bn-a7x.1.3").unwrap();
        assert_eq!(id.depth(), 2);
    }

    #[test]
    fn parse_normalises_case() {
        let id = ItemId::parse("BN-A7X").unwrap();
        assert_eq!(id.as_str(), "bn-a7x");
    }

    #[test]
    fn parse_trims_whitespace() {
        let id = ItemId::parse("  bn-a7x  ").unwrap();
        assert_eq!(id.as_str(), "bn-a7x");
    }

    #[test]
    fn parse_rejects_wrong_prefix() {
        let err = ItemId::parse("tk-a7x").unwrap_err();
        assert!(matches!(err, ItemIdError::WrongPrefix { .. }));
    }

    #[test]
    fn parse_rejects_invalid_format() {
        assert!(ItemId::parse("notanid").is_err());
        assert!(ItemId::parse("bn-").is_err());
        assert!(ItemId::parse("").is_err());
    }

    #[test]
    fn parse_accepts_all_letter_hash() {
        // All-letter 4+ char hashes are valid (backward compat with old terseid)
        assert!(ItemId::parse("bn-abcd").is_ok());
        assert!(ItemId::parse("bn-unwi").is_ok());
    }

    #[test]
    fn parse_accepts_longer_hash_with_digit() {
        let id = ItemId::parse("bn-a7x3q9").unwrap();
        assert_eq!(id.as_str(), "bn-a7x3q9");
    }

    // === FromStr / Display round-trip =======================================

    #[test]
    fn display_fromstr_roundtrip() {
        let id: ItemId = "bn-a7x".parse().unwrap();
        let rendered = id.to_string();
        let reparsed: ItemId = rendered.parse().unwrap();
        assert_eq!(id, reparsed);
    }

    #[test]
    fn display_fromstr_roundtrip_child() {
        let id: ItemId = "bn-a7x.1.3".parse().unwrap();
        let rendered = id.to_string();
        let reparsed: ItemId = rendered.parse().unwrap();
        assert_eq!(id, reparsed);
    }

    // === Serde round-trip ===================================================

    #[test]
    fn serde_json_roundtrip() {
        let id = ItemId::parse("bn-a7x.1").unwrap();
        let json = serde_json::to_string(&id).unwrap();
        assert_eq!(json, "\"bn-a7x.1\"");
        let deser: ItemId = serde_json::from_str(&json).unwrap();
        assert_eq!(id, deser);
    }

    #[test]
    fn serde_rejects_invalid() {
        let result = serde_json::from_str::<ItemId>("\"notvalid\"");
        assert!(result.is_err());
    }

    // === Child / parent =====================================================

    #[test]
    fn child_creates_valid_id() {
        let parent = ItemId::parse("bn-a7x").unwrap();
        let child = parent.child(1);
        assert_eq!(child.as_str(), "bn-a7x.1");
        assert!(child.is_child());
    }

    #[test]
    fn grandchild_creation() {
        let root = ItemId::parse("bn-a7x").unwrap();
        let child = root.child(1);
        let grandchild = child.child(3);
        assert_eq!(grandchild.as_str(), "bn-a7x.1.3");
        assert_eq!(grandchild.depth(), 2);
    }

    #[test]
    fn parent_of_root_is_none() {
        let root = ItemId::parse("bn-a7x").unwrap();
        assert!(root.parent().is_none());
    }

    #[test]
    fn parent_of_child() {
        let child = ItemId::parse("bn-a7x.1").unwrap();
        let parent = child.parent().unwrap();
        assert_eq!(parent.as_str(), "bn-a7x");
    }

    #[test]
    fn parent_of_grandchild() {
        let gc = ItemId::parse("bn-a7x.1.3").unwrap();
        let parent = gc.parent().unwrap();
        assert_eq!(parent.as_str(), "bn-a7x.1");
    }

    #[test]
    fn is_child_of_works() {
        let root = ItemId::parse("bn-a7x").unwrap();
        let child = ItemId::parse("bn-a7x.1").unwrap();
        let gc = ItemId::parse("bn-a7x.1.3").unwrap();

        assert!(child.is_child_of(&root));
        assert!(gc.is_child_of(&root));
        assert!(gc.is_child_of(&child));
        assert!(!root.is_child_of(&child));
        assert!(!child.is_child_of(&gc));
    }

    // === Generation =========================================================

    #[test]
    fn generate_produces_valid_id() {
        let id = generate_item_id("my test item", 0, |_| false);
        assert!(id.as_str().starts_with("bn-"));
        assert!(id.is_root());
        // Should parse back successfully
        let reparsed = ItemId::parse(id.as_str()).unwrap();
        assert_eq!(id, reparsed);
    }

    #[test]
    fn generate_deterministic_with_same_seed() {
        let id1 = generate_item_id("seed-abc", 0, |_| false);
        let id2 = generate_item_id("seed-abc", 0, |_| false);
        assert_eq!(id1, id2);
    }

    #[test]
    fn generate_different_seeds_different_ids() {
        let id1 = generate_item_id("seed-one", 0, |_| false);
        let id2 = generate_item_id("seed-two", 0, |_| false);
        assert_ne!(id1, id2);
    }

    #[test]
    fn generate_avoids_collisions() {
        let mut taken: HashSet<String> = HashSet::new();

        for i in 0..20 {
            let id = generate_item_id(&format!("item-{i}"), taken.len(), |candidate| {
                taken.contains(candidate)
            });
            assert!(
                taken.insert(id.as_str().to_string()),
                "collision on iteration {i}: {}",
                id
            );
        }

        assert_eq!(taken.len(), 20);
    }

    #[test]
    fn generate_adaptive_length_grows() {
        // With 0 items, should use short hash (min_hash_length = 3)
        let generator = bones_id_generator();
        let short = generator.optimal_length(0);
        assert_eq!(short, 3);

        // With many items, should use longer hash
        let long = generator.optimal_length(100_000);
        assert!(long > short, "expected adaptive growth: {long} > {short}");
    }

    // === Resolution =========================================================

    #[test]
    fn resolve_exact() {
        let known = vec!["bn-a7x".to_string(), "bn-b8y".to_string()];
        let id = resolve_item_id(
            "bn-a7x",
            |candidate| known.contains(&candidate.to_string()),
            |_sub| vec![],
        )
        .unwrap();
        assert_eq!(id.as_str(), "bn-a7x");
    }

    #[test]
    fn resolve_bare_hash() {
        let known = vec!["bn-a7x".to_string()];
        let id = resolve_item_id(
            "a7x",
            |candidate| known.contains(&candidate.to_string()),
            |_sub| vec![],
        )
        .unwrap();
        assert_eq!(id.as_str(), "bn-a7x");
    }

    #[test]
    fn resolve_substring() {
        let known = vec!["bn-a7x".to_string(), "bn-b8y".to_string()];
        let id = resolve_item_id(
            "a7",
            |candidate| known.contains(&candidate.to_string()),
            |sub| {
                known
                    .iter()
                    .filter(|id| id.split('-').last().is_some_and(|hash| hash.contains(sub)))
                    .cloned()
                    .collect()
            },
        )
        .unwrap();
        assert_eq!(id.as_str(), "bn-a7x");
    }

    #[test]
    fn resolve_ambiguous() {
        let known = vec!["bn-a7x".to_string(), "bn-a7y".to_string()];
        let err = resolve_item_id(
            "a7",
            |candidate| known.contains(&candidate.to_string()),
            |sub| {
                known
                    .iter()
                    .filter(|id| id.split('-').last().is_some_and(|hash| hash.contains(sub)))
                    .cloned()
                    .collect()
            },
        )
        .unwrap_err();
        assert!(matches!(err, ItemIdError::Ambiguous { .. }));
    }

    #[test]
    fn resolve_not_found() {
        let err = resolve_item_id("zzz", |_| false, |_| vec![]).unwrap_err();
        assert!(matches!(err, ItemIdError::NotFound(_)));
    }

    // === Ordering & Hash ====================================================

    #[test]
    fn ordering_is_lexicographic() {
        let a = ItemId::parse("bn-a7x").unwrap();
        let b = ItemId::parse("bn-b8y").unwrap();
        assert!(a < b);
    }

    #[test]
    fn hash_set_deduplication() {
        let id1 = ItemId::parse("bn-a7x").unwrap();
        let id2 = ItemId::parse("bn-a7x").unwrap();
        let mut set = HashSet::new();
        set.insert(id1);
        set.insert(id2);
        assert_eq!(set.len(), 1);
    }

    // === AsRef / Into =======================================================

    #[test]
    fn as_ref_str() {
        let id = ItemId::parse("bn-a7x").unwrap();
        let s: &str = id.as_ref();
        assert_eq!(s, "bn-a7x");
    }

    #[test]
    fn into_string() {
        let id = ItemId::parse("bn-a7x").unwrap();
        let s: String = id.into();
        assert_eq!(s, "bn-a7x");
    }

    // === new_unchecked ======================================================

    #[test]
    fn new_unchecked_trusts_caller() {
        let id = ItemId::new_unchecked("bn-a7x");
        assert_eq!(id.as_str(), "bn-a7x");
    }

    // === Error display ======================================================

    #[test]
    fn error_display() {
        let e = ItemIdError::InvalidFormat("bad".into());
        assert!(e.to_string().contains("bad"));

        let e = ItemIdError::WrongPrefix {
            expected: "bn".into(),
            found: "tk".into(),
        };
        assert!(e.to_string().contains("bn"));
        assert!(e.to_string().contains("tk"));

        let e = ItemIdError::Ambiguous {
            partial: "a7".into(),
            matches: vec!["bn-a7x".into(), "bn-a7y".into()],
        };
        assert!(e.to_string().contains("a7"));

        let e = ItemIdError::NotFound("zzz".into());
        assert!(e.to_string().contains("zzz"));
    }
}