khive-types 0.10.0

Core type primitives: Id128, Timestamp, Namespace, and the 3 substrate data types (Note, Entity, Event).
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
//! Edge relation types for the closed ontology used throughout khive.

extern crate alloc;
use alloc::string::String;
use core::fmt;
use core::str::FromStr;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// The 10 semantic categories that group the 20 canonical edge relations.
///
/// Exposed via [`EdgeRelation::category`] for query planners and UI rendering.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum EdgeCategory {
    /// Composition, reference and location: `contains`, `part_of`, `instance_of`, `links_to`,
    /// `located_in`
    Structure,
    /// Intellectual lineage: `extends`, `variant_of`, `introduced_by`, `supersedes`
    Derivation,
    /// Data/artifact origin: `derived_from`
    Provenance,
    /// Time ordering: `precedes`
    Temporal,
    /// Build/runtime needs: `depends_on`, `enables`
    Dependency,
    /// Code ↔ concept: `implements`
    Implementation,
    /// Peer relationships: `competes_with`, `composed_with`
    Lateral,
    /// Cross-substrate annotation: `annotates`
    Annotation,
    /// Evidence for/against a claim: `supports`, `refutes`
    Epistemic,
    /// Current whole or partial ownership: `owns`
    Ownership,
}

/// Closed set of 20 canonical edge relations.
///
/// No `Default` — every edge requires an explicit relation.
/// Wire format: snake_case strings (e.g. `"part_of"`, `"introduced_by"`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum EdgeRelation {
    // Structure
    Contains,
    PartOf,
    InstanceOf,
    LinksTo,
    LocatedIn,
    // Derivation
    Extends,
    VariantOf,
    IntroducedBy,
    Supersedes,
    // Provenance
    DerivedFrom,
    // Temporal
    Precedes,
    // Dependency
    DependsOn,
    Enables,
    // Implementation
    Implements,
    // Lateral
    CompetesWith,
    ComposedWith,
    // Annotation
    Annotates,
    // Epistemic
    Supports,
    Refutes,
    // Ownership
    Owns,
}

impl EdgeRelation {
    /// All 20 canonical relations in ontology-table order.
    pub const ALL: [Self; 20] = [
        Self::Contains,
        Self::PartOf,
        Self::InstanceOf,
        Self::LinksTo,
        Self::LocatedIn,
        Self::Extends,
        Self::VariantOf,
        Self::IntroducedBy,
        Self::Supersedes,
        Self::DerivedFrom,
        Self::Precedes,
        Self::DependsOn,
        Self::Enables,
        Self::Implements,
        Self::CompetesWith,
        Self::ComposedWith,
        Self::Annotates,
        Self::Supports,
        Self::Refutes,
        Self::Owns,
    ];

    /// Valid snake_case names for all 20 canonical relations.
    pub const VALID_NAMES: &'static [&'static str] = &[
        "contains",
        "part_of",
        "instance_of",
        "links_to",
        "located_in",
        "extends",
        "variant_of",
        "introduced_by",
        "supersedes",
        "derived_from",
        "precedes",
        "depends_on",
        "enables",
        "implements",
        "competes_with",
        "composed_with",
        "annotates",
        "supports",
        "refutes",
        "owns",
    ];

    /// `true` for symmetric relations: edge direction has no semantic meaning.
    pub const fn is_symmetric(&self) -> bool {
        matches!(self, Self::CompetesWith | Self::ComposedWith)
    }

    /// Order the endpoints of an edge so a symmetric relation has one stored form.
    ///
    /// For symmetric relations (`competes_with`, `composed_with`) the smaller
    /// endpoint comes first, so A→B and B→A collapse into a single canonical row.
    /// Every other relation, and a symmetric pair that is already ordered or has
    /// equal endpoints, is returned as given.
    ///
    /// Generic over `T: Ord` because this crate does not depend on a UUID type;
    /// for UUIDs the order is the byte order of the id.
    pub fn canonical_endpoints<T: Ord>(&self, source: T, target: T) -> (T, T) {
        if self.is_symmetric() && target < source {
            (target, source)
        } else {
            (source, target)
        }
    }

    /// The category this relation belongs to.
    pub const fn category(&self) -> EdgeCategory {
        match self {
            Self::Contains | Self::PartOf | Self::InstanceOf | Self::LinksTo | Self::LocatedIn => {
                EdgeCategory::Structure
            }
            Self::Extends | Self::VariantOf | Self::IntroducedBy | Self::Supersedes => {
                EdgeCategory::Derivation
            }
            Self::DerivedFrom => EdgeCategory::Provenance,
            Self::Precedes => EdgeCategory::Temporal,
            Self::DependsOn | Self::Enables => EdgeCategory::Dependency,
            Self::Implements => EdgeCategory::Implementation,
            Self::CompetesWith | Self::ComposedWith => EdgeCategory::Lateral,
            Self::Annotates => EdgeCategory::Annotation,
            Self::Supports | Self::Refutes => EdgeCategory::Epistemic,
            Self::Owns => EdgeCategory::Ownership,
        }
    }

    /// Canonical snake_case name as stored in the database.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Contains => "contains",
            Self::PartOf => "part_of",
            Self::InstanceOf => "instance_of",
            Self::LinksTo => "links_to",
            Self::LocatedIn => "located_in",
            Self::Extends => "extends",
            Self::VariantOf => "variant_of",
            Self::IntroducedBy => "introduced_by",
            Self::Supersedes => "supersedes",
            Self::DerivedFrom => "derived_from",
            Self::Precedes => "precedes",
            Self::DependsOn => "depends_on",
            Self::Enables => "enables",
            Self::Implements => "implements",
            Self::CompetesWith => "competes_with",
            Self::ComposedWith => "composed_with",
            Self::Annotates => "annotates",
            Self::Supports => "supports",
            Self::Refutes => "refutes",
            Self::Owns => "owns",
        }
    }
}

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

impl FromStr for EdgeRelation {
    type Err = crate::error::UnknownVariant;

    /// Parse a string into an `EdgeRelation`.
    ///
    /// Accepts the 20 canonical relation names (case-insensitive, with hyphens
    /// normalised to underscores) and also squashed forms that omit the separator
    /// (e.g. `"partof"`, `"derivedfrom"`).  The squashed forms exist for ergonomic
    /// DSL entry; they are **not** stored on the wire, which always uses the
    /// canonical snake_case form produced by [`EdgeRelation::as_str`].
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut normalised = String::with_capacity(s.len());
        for c in s.chars() {
            match c {
                '-' | '_' => normalised.push('_'),
                c if c.is_ascii_alphanumeric() => normalised.push(c.to_ascii_lowercase()),
                _ => {
                    return Err(crate::error::UnknownVariant::new(
                        "edge_relation",
                        s,
                        Self::VALID_NAMES,
                    ));
                }
            }
        }

        match normalised.as_str() {
            "contains" => Ok(Self::Contains),
            "part_of" | "partof" => Ok(Self::PartOf),
            "instance_of" | "instanceof" => Ok(Self::InstanceOf),
            "links_to" | "linksto" => Ok(Self::LinksTo),
            "located_in" | "locatedin" => Ok(Self::LocatedIn),
            "extends" => Ok(Self::Extends),
            "variant_of" | "variantof" => Ok(Self::VariantOf),
            "introduced_by" | "introducedby" => Ok(Self::IntroducedBy),
            "supersedes" => Ok(Self::Supersedes),
            "derived_from" | "derivedfrom" => Ok(Self::DerivedFrom),
            "precedes" => Ok(Self::Precedes),
            "depends_on" | "dependson" => Ok(Self::DependsOn),
            "enables" => Ok(Self::Enables),
            "implements" => Ok(Self::Implements),
            "competes_with" | "competeswith" => Ok(Self::CompetesWith),
            "composed_with" | "composedwith" => Ok(Self::ComposedWith),
            "annotates" => Ok(Self::Annotates),
            "supports" => Ok(Self::Supports),
            "refutes" => Ok(Self::Refutes),
            "owns" => Ok(Self::Owns),
            _ => Err(crate::error::UnknownVariant::new(
                "edge_relation",
                s,
                Self::VALID_NAMES,
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;

    #[test]
    fn all_has_twenty_variants() {
        assert_eq!(EdgeRelation::ALL.len(), 20);
    }

    #[test]
    fn all_ten_categories_covered() {
        let mut cats = alloc::vec::Vec::new();
        for r in EdgeRelation::ALL {
            let c = r.category();
            if !cats.contains(&c) {
                cats.push(c);
            }
        }
        assert_eq!(cats.len(), 10, "all 10 categories must be represented");
    }

    #[test]
    fn owns_is_directional_ownership() {
        assert_eq!("owns".parse::<EdgeRelation>().unwrap(), EdgeRelation::Owns);
        assert_eq!("OWNS".parse::<EdgeRelation>().unwrap(), EdgeRelation::Owns);
        assert_eq!(EdgeRelation::Owns.to_string(), "owns");
        assert_eq!(EdgeRelation::Owns.category(), EdgeCategory::Ownership);
        assert!(!EdgeRelation::Owns.is_symmetric());
        assert_eq!(EdgeRelation::Owns.canonical_endpoints(9, 2), (9, 2));
    }

    #[test]
    fn display_roundtrip_for_all() {
        for relation in EdgeRelation::ALL {
            let s = relation.to_string();
            let parsed: EdgeRelation = s.parse().expect("display output should re-parse");
            assert_eq!(parsed, relation);
        }
    }

    #[test]
    fn from_str_case_insensitive() {
        assert_eq!(
            "Extends".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Extends
        );
        assert_eq!(
            "extends".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Extends
        );
        assert_eq!(
            "EXTENDS".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Extends
        );
    }

    #[test]
    fn from_str_hyphen_tolerant() {
        assert_eq!(
            "part_of".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::PartOf
        );
        assert_eq!(
            "part-of".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::PartOf
        );
        assert_eq!(
            "partof".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::PartOf
        );

        assert_eq!(
            "introduced_by".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::IntroducedBy
        );
        assert_eq!(
            "introduced-by".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::IntroducedBy
        );
    }

    #[test]
    fn from_str_unknown_returns_error_with_list() {
        let err = "related_to".parse::<EdgeRelation>().unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("related_to"),
            "error should mention the bad input"
        );
        assert!(
            msg.contains("contains"),
            "error should list valid relations"
        );
        assert!(
            msg.contains("derived_from"),
            "error should list derived_from"
        );
        assert!(msg.contains("precedes"), "error should list precedes");
        assert!(msg.contains("annotates"), "error should list annotates");
    }

    #[test]
    fn edge_relation_bang_rejected() {
        for bad in ["supports!", "part/of", "depends.on", "competes with"] {
            let err = bad
                .parse::<EdgeRelation>()
                .expect_err("malformed punctuation/whitespace must be rejected");
            assert_eq!(err.domain, "edge_relation");
            assert_eq!(err.value, bad);
        }
    }

    #[test]
    fn category_returns_correct_group() {
        assert_eq!(EdgeRelation::Contains.category(), EdgeCategory::Structure);
        assert_eq!(EdgeRelation::PartOf.category(), EdgeCategory::Structure);
        assert_eq!(EdgeRelation::InstanceOf.category(), EdgeCategory::Structure);
        assert_eq!(EdgeRelation::LinksTo.category(), EdgeCategory::Structure);
        assert_eq!(EdgeRelation::LocatedIn.category(), EdgeCategory::Structure);

        assert_eq!(EdgeRelation::Extends.category(), EdgeCategory::Derivation);
        assert_eq!(EdgeRelation::VariantOf.category(), EdgeCategory::Derivation);
        assert_eq!(
            EdgeRelation::IntroducedBy.category(),
            EdgeCategory::Derivation
        );
        assert_eq!(
            EdgeRelation::Supersedes.category(),
            EdgeCategory::Derivation
        );

        assert_eq!(EdgeRelation::DependsOn.category(), EdgeCategory::Dependency);
        assert_eq!(EdgeRelation::Enables.category(), EdgeCategory::Dependency);

        assert_eq!(
            EdgeRelation::Implements.category(),
            EdgeCategory::Implementation
        );

        assert_eq!(
            EdgeRelation::DerivedFrom.category(),
            EdgeCategory::Provenance
        );
        assert_eq!(EdgeRelation::Precedes.category(), EdgeCategory::Temporal);

        assert_eq!(EdgeRelation::CompetesWith.category(), EdgeCategory::Lateral);
        assert_eq!(EdgeRelation::ComposedWith.category(), EdgeCategory::Lateral);

        assert_eq!(EdgeRelation::Annotates.category(), EdgeCategory::Annotation);
    }

    #[test]
    fn from_str_new_relations() {
        assert_eq!(
            "derived_from".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::DerivedFrom
        );
        assert_eq!(
            "derived-from".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::DerivedFrom
        );
        assert_eq!(
            "derivedfrom".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::DerivedFrom
        );
        assert_eq!(
            "precedes".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Precedes
        );
    }

    #[test]
    fn from_str_links_to() {
        assert_eq!(
            "links_to".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::LinksTo
        );
        assert_eq!(
            "links-to".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::LinksTo
        );
        assert_eq!(
            "linksto".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::LinksTo
        );
        assert_eq!(EdgeRelation::LinksTo.to_string(), "links_to");
        assert_eq!(EdgeRelation::LinksTo.category(), EdgeCategory::Structure);
    }

    #[test]
    fn from_str_located_in() {
        assert_eq!(
            "located_in".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::LocatedIn
        );
        assert_eq!(
            "located-in".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::LocatedIn
        );
        assert_eq!(
            "locatedin".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::LocatedIn
        );
        assert_eq!(EdgeRelation::LocatedIn.to_string(), "located_in");
        assert_eq!(EdgeRelation::LocatedIn.category(), EdgeCategory::Structure);
    }

    #[test]
    fn is_symmetric_only_for_lateral_peer_relations() {
        assert!(EdgeRelation::CompetesWith.is_symmetric());
        assert!(EdgeRelation::ComposedWith.is_symmetric());
        assert!(!EdgeRelation::DependsOn.is_symmetric());
        assert!(!EdgeRelation::DerivedFrom.is_symmetric());
        assert!(!EdgeRelation::Precedes.is_symmetric());
        assert!(!EdgeRelation::Extends.is_symmetric());
        assert!(!EdgeRelation::LinksTo.is_symmetric());
        assert!(!EdgeRelation::LocatedIn.is_symmetric());
    }

    /// The symmetric relations, named here rather than derived from `is_symmetric`
    /// so the tests below do not take their expectation from the code under test.
    const SYMMETRIC: [EdgeRelation; 2] = [EdgeRelation::CompetesWith, EdgeRelation::ComposedWith];

    /// Endpoint pairs with source less than, greater than and equal to target.
    const PAIRS: [(u8, u8); 3] = [(1, 2), (2, 1), (7, 7)];

    #[test]
    fn canonical_endpoints_sorts_symmetric_relations() {
        for relation in SYMMETRIC {
            assert!(relation.is_symmetric(), "{relation}");
            for (source, target) in PAIRS {
                assert_eq!(
                    relation.canonical_endpoints(source, target),
                    (source.min(target), source.max(target)),
                    "{relation}: {source} to {target}"
                );
            }
        }
    }

    #[test]
    fn canonical_endpoints_leaves_other_relations_as_given() {
        let others: alloc::vec::Vec<EdgeRelation> = EdgeRelation::ALL
            .into_iter()
            .filter(|relation| !SYMMETRIC.contains(relation))
            .collect();
        assert_eq!(others.len(), EdgeRelation::ALL.len() - SYMMETRIC.len());
        for relation in others {
            assert!(!relation.is_symmetric(), "{relation}");
            for (source, target) in PAIRS {
                assert_eq!(
                    relation.canonical_endpoints(source, target),
                    (source, target),
                    "{relation}: {source} to {target}"
                );
            }
        }
    }

    #[test]
    fn from_str_epistemic_relations() {
        assert_eq!(
            "supports".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Supports
        );
        assert_eq!(
            "refutes".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Refutes
        );
        assert_eq!(
            "Supports".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Supports
        );
        assert_eq!(
            "REFUTES".parse::<EdgeRelation>().unwrap(),
            EdgeRelation::Refutes
        );
        assert_eq!(EdgeRelation::Supports.category(), EdgeCategory::Epistemic);
        assert_eq!(EdgeRelation::Refutes.category(), EdgeCategory::Epistemic);
        assert!(!EdgeRelation::Supports.is_symmetric());
        assert!(!EdgeRelation::Refutes.is_symmetric());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_snake_case_roundtrip() {
        let rel = EdgeRelation::IntroducedBy;
        let json = serde_json::to_string(&rel).unwrap();
        assert_eq!(json, "\"introduced_by\"");
        let parsed: EdgeRelation = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, rel);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_new_relations_roundtrip() {
        for rel in [EdgeRelation::DerivedFrom, EdgeRelation::Precedes] {
            let json = serde_json::to_string(&rel).unwrap();
            let parsed: EdgeRelation = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, rel);
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_epistemic_relations_roundtrip() {
        let sup_json = serde_json::to_string(&EdgeRelation::Supports).unwrap();
        assert_eq!(sup_json, "\"supports\"");
        let sup_parsed: EdgeRelation = serde_json::from_str(&sup_json).unwrap();
        assert_eq!(sup_parsed, EdgeRelation::Supports);

        let ref_json = serde_json::to_string(&EdgeRelation::Refutes).unwrap();
        assert_eq!(ref_json, "\"refutes\"");
        let ref_parsed: EdgeRelation = serde_json::from_str(&ref_json).unwrap();
        assert_eq!(ref_parsed, EdgeRelation::Refutes);
    }
}