khive-types 0.2.9

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
//! Entity substrate — graph nodes with typed properties and links.

extern crate alloc;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::str::FromStr;

use crate::{EdgeRelation, Header, Id128, Timestamp};

/// 8 closed base kinds for graph-node classification.
///
/// Governed subtype values live in `Entity::entity_type`; `properties` remain
/// metadata and must not carry ontology type strings.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum EntityKind {
    /// Algorithms, techniques, architectures, theories, models, research gaps.
    /// The default / residual bucket.
    #[default]
    Concept,
    /// Papers, preprints, technical reports, blog posts, books.
    /// Has: title, authors, year, venue, DOI/URL.
    Document,
    /// Benchmarks, corpora, evaluation sets.
    /// Has: task type, size, metrics, license.
    Dataset,
    /// Codebases, libraries, tools, frameworks.
    /// Has: language, repo URL, license.
    Project,
    /// Researchers, engineers, authors.
    Person,
    /// Labs, companies, institutions.
    Org,
    /// Built artifacts: binaries, model checkpoints, Docker images, packages.
    Artifact,
    /// Running or deployable services: APIs, hosted endpoints, SaaS products.
    Service,
}

impl EntityKind {
    /// All 8 canonical entity kinds in taxonomy-table order.
    pub const ALL: [Self; 8] = [
        Self::Concept,
        Self::Document,
        Self::Dataset,
        Self::Project,
        Self::Person,
        Self::Org,
        Self::Artifact,
        Self::Service,
    ];

    /// Return the canonical lowercase string for this kind, as stored on the wire.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Concept => "concept",
            Self::Document => "document",
            Self::Dataset => "dataset",
            Self::Project => "project",
            Self::Person => "person",
            Self::Org => "org",
            Self::Artifact => "artifact",
            Self::Service => "service",
        }
    }
}

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

// Canonical entity kind strings for the closed 8-kind taxonomy.
const ENTITY_KIND_VALID: &[&str] = &[
    "concept", "document", "dataset", "project", "person", "org", "artifact", "service",
];

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

    /// Parse a string into an `EntityKind`.
    ///
    /// Accepts the 8 canonical kind names (case-insensitive) plus a set of
    /// convenience aliases to aid human-authored DSL requests (e.g. `"paper"`
    /// resolves to `Document`, `"repo"` to `Project`).
    ///
    /// **Note on subtype aliasing**: when `kind="paper"` is parsed here, only the
    /// base `EntityKind::Document` is returned.  Callers that need to preserve the
    /// `entity_type` subtoken must use the pack registry resolution path, which
    /// returns both the base kind and the subtype string.  `from_str` is
    /// intentionally base-kind-only for use in contexts where the subtype is
    /// carried separately (e.g. `Entity.entity_type`).
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "concept" => Ok(Self::Concept),
            "document" | "doc" | "paper" => Ok(Self::Document),
            "dataset" | "data" | "benchmark" => Ok(Self::Dataset),
            "project" | "repo" | "crate" | "library" | "lib" => Ok(Self::Project),
            "person" | "author" | "researcher" => Ok(Self::Person),
            "org" | "organization" | "organisation" | "lab" | "company" => Ok(Self::Org),
            "artifact" | "art" => Ok(Self::Artifact),
            "service" | "svc" => Ok(Self::Service),
            other => Err(crate::error::UnknownVariant::new(
                "entity_kind",
                other,
                ENTITY_KIND_VALID,
            )),
        }
    }
}

/// A graph node with a type, display name, and key-value properties.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Entity {
    /// Identity and namespace metadata shared by all substrate records.
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub header: Header,
    /// Closed base kind that classifies this entity.
    pub kind: EntityKind,
    /// Pack-governed subtype token (e.g. `"paper"`, `"snapshot"`). Never stored
    /// raw in `properties` — queries compile this to `entities.entity_type = ?`.
    pub entity_type: Option<String>,
    /// Human-readable display name (required; must be non-empty).
    pub name: String,
    /// Optional long-form description of this entity.
    pub description: Option<String>,
    /// Arbitrary structured metadata as key-value pairs.
    pub properties: BTreeMap<String, PropertyValue>,
    /// Categorical labels for filtering and retrieval.
    pub tags: Vec<String>,
    /// Set when the entity is soft-deleted; absent means active.
    pub deleted_at: Option<Timestamp>,
}

/// A directed, typed edge between two entities (or cross-substrate nodes).
///
/// `weight` must be finite and in `[0.0, 1.0]`. When the `serde` feature is
/// enabled, deserialization rejects out-of-range or non-finite weights.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(into = "LinkRaw"))]
pub struct Link {
    /// Unique edge identifier.
    pub id: Id128,
    /// Namespace that owns and isolates this edge.
    pub namespace: String,
    /// Source node identifier.
    pub source: Id128,
    /// Target node identifier.
    pub target: Id128,
    /// Closed relation type that semantically describes this edge.
    pub relation: EdgeRelation,
    /// Arbitrary structured metadata attached to this edge.
    pub properties: BTreeMap<String, PropertyValue>,
    /// Numeric edge weight in the range [0.0, 1.0]; 1.0 means definitional strength.
    pub weight: f64,
    /// Wall-clock time when this edge was created.
    pub created_at: Timestamp,
    /// Wall-clock time of the most recent update.
    pub updated_at: Timestamp,
    /// Set when the edge is soft-deleted; absent means active.
    pub deleted_at: Option<Timestamp>,
}

impl Link {
    /// Return `true` if all numeric fields carry finite, domain-valid values.
    ///
    /// - `weight` must be finite and in `[0.0, 1.0]`.
    pub fn is_valid(&self) -> bool {
        self.weight.is_finite() && self.weight >= 0.0 && self.weight <= 1.0
    }
}

#[cfg(feature = "serde")]
#[derive(serde::Serialize, serde::Deserialize)]
struct LinkRaw {
    id: Id128,
    namespace: String,
    source: Id128,
    target: Id128,
    relation: EdgeRelation,
    properties: BTreeMap<String, PropertyValue>,
    weight: f64,
    created_at: Timestamp,
    updated_at: Timestamp,
    deleted_at: Option<Timestamp>,
}

#[cfg(feature = "serde")]
impl From<Link> for LinkRaw {
    fn from(l: Link) -> Self {
        Self {
            id: l.id,
            namespace: l.namespace,
            source: l.source,
            target: l.target,
            relation: l.relation,
            properties: l.properties,
            weight: l.weight,
            created_at: l.created_at,
            updated_at: l.updated_at,
            deleted_at: l.deleted_at,
        }
    }
}

#[cfg(feature = "serde")]
impl TryFrom<LinkRaw> for Link {
    type Error = String;

    fn try_from(raw: LinkRaw) -> Result<Self, Self::Error> {
        if !raw.weight.is_finite() {
            return Err(alloc::format!(
                "Link weight must be finite, got {}",
                raw.weight
            ));
        }
        if !(0.0..=1.0).contains(&raw.weight) {
            return Err(alloc::format!(
                "Link weight must be in [0.0, 1.0], got {}",
                raw.weight
            ));
        }
        Ok(Link {
            id: raw.id,
            namespace: raw.namespace,
            source: raw.source,
            target: raw.target,
            relation: raw.relation,
            properties: raw.properties,
            weight: raw.weight,
            created_at: raw.created_at,
            updated_at: raw.updated_at,
            deleted_at: raw.deleted_at,
        })
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Link {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = LinkRaw::deserialize(deserializer)?;
        Link::try_from(raw).map_err(serde::de::Error::custom)
    }
}

/// Property values stored on entities, links, and notes.
///
/// Recursive: supports arrays and nested objects for free-form JSON properties
/// (e.g. `entity_ids[]`, `alternatives_considered[]`).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum PropertyValue {
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Array(Vec<PropertyValue>),
    Object(BTreeMap<String, PropertyValue>),
    Null,
}

impl fmt::Display for PropertyValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::String(s) => f.write_str(s),
            Self::Integer(n) => write!(f, "{n}"),
            Self::Float(n) => write!(f, "{n}"),
            Self::Boolean(b) => write!(f, "{b}"),
            Self::Array(arr) => write!(f, "[{} items]", arr.len()),
            Self::Object(obj) => write!(f, "{{{} keys}}", obj.len()),
            Self::Null => f.write_str("null"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Namespace, Timestamp};
    #[cfg(feature = "serde")]
    use alloc::string::ToString;

    #[test]
    fn entity_with_properties() {
        let mut props = BTreeMap::new();
        props.insert("role".into(), PropertyValue::String("engineer".into()));
        props.insert("age".into(), PropertyValue::Integer(30));

        let entity = Entity {
            header: Header::new(
                Id128::from_u128(1),
                Namespace::local(),
                Timestamp::from_secs(1700000000),
            ),
            kind: EntityKind::Person,
            entity_type: Some("researcher".into()),
            name: "Ocean".into(),
            description: None,
            properties: props,
            tags: alloc::vec![],
            deleted_at: None,
        };
        assert_eq!(entity.kind, EntityKind::Person);
        assert_eq!(entity.kind.name(), "person");
        assert_eq!(entity.entity_type.as_deref(), Some("researcher"));
        assert_eq!(entity.properties.len(), 2);
    }

    #[test]
    fn entity_kind_default_is_concept() {
        assert_eq!(EntityKind::default(), EntityKind::Concept);
    }

    #[test]
    fn entity_kind_display_roundtrip() {
        for kind in EntityKind::ALL {
            let s = alloc::format!("{kind}");
            let parsed = EntityKind::from_str(&s).unwrap();
            assert_eq!(parsed, kind);
        }
    }

    #[test]
    fn entity_kind_from_str_aliases() {
        assert_eq!(EntityKind::from_str("doc").unwrap(), EntityKind::Document);
        assert_eq!(EntityKind::from_str("paper").unwrap(), EntityKind::Document);
        assert_eq!(
            EntityKind::from_str("benchmark").unwrap(),
            EntityKind::Dataset
        );
        assert_eq!(EntityKind::from_str("repo").unwrap(), EntityKind::Project);
        assert_eq!(EntityKind::from_str("author").unwrap(), EntityKind::Person);
        assert_eq!(EntityKind::from_str("lab").unwrap(), EntityKind::Org);
        assert_eq!(EntityKind::from_str("art").unwrap(), EntityKind::Artifact);
        assert_eq!(EntityKind::from_str("svc").unwrap(), EntityKind::Service);
    }

    #[test]
    fn entity_kind_artifact_and_service_roundtrip() {
        assert_eq!(EntityKind::Artifact.name(), "artifact");
        assert_eq!(EntityKind::Service.name(), "service");
        assert_eq!(
            EntityKind::from_str("artifact").unwrap(),
            EntityKind::Artifact
        );
        assert_eq!(
            EntityKind::from_str("service").unwrap(),
            EntityKind::Service
        );
    }

    #[test]
    fn entity_kind_all_has_eight_variants() {
        assert_eq!(EntityKind::ALL.len(), 8);
        assert!(EntityKind::ALL.contains(&EntityKind::Artifact));
        assert!(EntityKind::ALL.contains(&EntityKind::Service));
    }

    #[test]
    fn entity_kind_unknown_valid_list_includes_new_kinds() {
        let err = EntityKind::from_str("gadget").unwrap_err();
        assert!(err.valid.contains(&"artifact"));
        assert!(err.valid.contains(&"service"));
    }

    #[test]
    fn entity_kind_from_str_case_insensitive() {
        assert_eq!(
            EntityKind::from_str("CONCEPT").unwrap(),
            EntityKind::Concept
        );
        assert_eq!(EntityKind::from_str("Person").unwrap(), EntityKind::Person);
    }

    #[test]
    fn entity_kind_from_str_unknown_errors() {
        let err = EntityKind::from_str("gadget").unwrap_err();
        assert_eq!(err.domain, "entity_kind");
        assert_eq!(err.value, "gadget");
        assert!(err.valid.contains(&"concept"));
    }

    #[test]
    fn link_construction() {
        let ts = Timestamp::from_secs(1700000000);
        let link = Link {
            id: Id128::from_u128(100),
            namespace: "default".into(),
            source: Id128::from_u128(1),
            target: Id128::from_u128(2),
            relation: EdgeRelation::Extends,
            properties: BTreeMap::new(),
            weight: 1.0,
            created_at: ts,
            updated_at: ts,
            deleted_at: None,
        };
        assert_eq!(link.relation, EdgeRelation::Extends);
        assert!(link.is_valid());
    }

    #[test]
    fn link_is_valid_rejects_out_of_range() {
        let ts = Timestamp::from_secs(1700000000);
        let link = Link {
            id: Id128::from_u128(100),
            namespace: "default".into(),
            source: Id128::from_u128(1),
            target: Id128::from_u128(2),
            relation: EdgeRelation::Extends,
            properties: BTreeMap::new(),
            weight: 2.0,
            created_at: ts,
            updated_at: ts,
            deleted_at: None,
        };
        assert!(!link.is_valid());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn link_serde_rejects_weight_above_one() {
        let json = serde_json::json!({
            "id": "00000000-0000-0000-0000-000000000064",
            "namespace": "default",
            "source": "00000000-0000-0000-0000-000000000001",
            "target": "00000000-0000-0000-0000-000000000002",
            "relation": "extends",
            "properties": {},
            "weight": 2.0,
            "created_at": 1700000000000000_u64,
            "updated_at": 1700000000000000_u64,
            "deleted_at": null
        });
        let result: Result<Link, _> = serde_json::from_value(json);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("[0.0, 1.0]"),
            "error should mention range: {err}"
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn link_serde_rejects_negative_weight() {
        let json = serde_json::json!({
            "id": "00000000-0000-0000-0000-000000000064",
            "namespace": "default",
            "source": "00000000-0000-0000-0000-000000000001",
            "target": "00000000-0000-0000-0000-000000000002",
            "relation": "extends",
            "properties": {},
            "weight": -0.1,
            "created_at": 1700000000000000_u64,
            "updated_at": 1700000000000000_u64,
            "deleted_at": null
        });
        let result: Result<Link, _> = serde_json::from_value(json);
        assert!(result.is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn link_serde_accepts_valid_weight() {
        let json = serde_json::json!({
            "id": "00000000-0000-0000-0000-000000000064",
            "namespace": "default",
            "source": "00000000-0000-0000-0000-000000000001",
            "target": "00000000-0000-0000-0000-000000000002",
            "relation": "extends",
            "properties": {},
            "weight": 0.75,
            "created_at": 1700000000000000_u64,
            "updated_at": 1700000000000000_u64,
            "deleted_at": null
        });
        let link: Link = serde_json::from_value(json).expect("valid weight should deserialize");
        assert_eq!(link.weight, 0.75);
    }
}