Skip to main content

drevo_core/
model.rs

1//! Data model types for drevo.
2//!
3//! Defines the core domain types: [`Node`], [`Edge`], and their
4//! corresponding creation ([`NewNode`], [`NewEdge`]) and update
5//! ([`NodePatch`], [`EdgePatch`]) structs.
6
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, HashMap};
9
10/// JSON-compatible properties map that works with both bincode and serde_json.
11///
12/// Bincode v2 does not support `serde_json::Value` directly (no `deserialize_any`).
13/// This wrapper serializes properties as a JSON byte string for bincode,
14/// while remaining transparent for JSON serialization.
15#[derive(Debug, Clone, Default, PartialEq)]
16pub struct Properties(pub HashMap<String, serde_json::Value>);
17
18impl From<HashMap<String, serde_json::Value>> for Properties {
19    fn from(map: HashMap<String, serde_json::Value>) -> Self {
20        Self(map)
21    }
22}
23
24impl std::ops::Deref for Properties {
25    type Target = HashMap<String, serde_json::Value>;
26    fn deref(&self) -> &Self::Target {
27        &self.0
28    }
29}
30
31impl std::ops::DerefMut for Properties {
32    fn deref_mut(&mut self) -> &mut Self::Target {
33        &mut self.0
34    }
35}
36
37impl Serialize for Properties {
38    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
39        // Collect into BTreeMap so the output is deterministic across HashMap
40        // iteration orders — required by drevo-rust §"Serialization"
41        // ("bincode v2 — compact, fast, deterministic"). Inner `serde_json::Value`
42        // objects already use `serde_json::Map` (BTreeMap-backed by default), so
43        // only the outer HashMap iteration needed normalising.
44        let sorted: BTreeMap<&String, &serde_json::Value> = self.0.iter().collect();
45        if serializer.is_human_readable() {
46            sorted.serialize(serializer)
47        } else {
48            let json = serde_json::to_vec(&sorted).map_err(serde::ser::Error::custom)?;
49            json.serialize(serializer)
50        }
51    }
52}
53
54impl<'de> Deserialize<'de> for Properties {
55    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
56        if deserializer.is_human_readable() {
57            let map = HashMap::<String, serde_json::Value>::deserialize(deserializer)?;
58            Ok(Self(map))
59        } else {
60            let json = Vec::<u8>::deserialize(deserializer)?;
61            let map = serde_json::from_slice(&json).map_err(serde::de::Error::custom)?;
62            Ok(Self(map))
63        }
64    }
65}
66
67/// A node in the graph.
68///
69/// Nodes represent domain entities (notes, tags, people, tasks, etc.).
70/// The `kind` field classifies the node, and `properties` stores
71/// arbitrary JSON-compatible metadata without schema migration.
72#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
73pub struct Node {
74    /// Auto-incremented unique identifier.
75    pub id: u64,
76    /// UUID v7 — sortable, globally unique.
77    pub uuid: [u8; 16],
78    /// Classification (e.g. "note", "tag", "person", "concept").
79    pub kind: String,
80    /// Human-readable title.
81    pub title: String,
82    /// Raw Markdown body.
83    pub body: String,
84    /// Rendered HTML (cached).
85    pub body_html: String,
86    /// Creation timestamp (Unix milliseconds).
87    pub created_at: i64,
88    /// Last update timestamp (Unix milliseconds).
89    pub updated_at: i64,
90    /// Arbitrary JSON-compatible metadata.
91    pub properties: Properties,
92}
93
94/// Input for creating a new node.
95///
96/// Fields that the system generates (id, uuid, timestamps) are omitted.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct NewNode {
99    /// Classification (e.g. "note", "tag").
100    pub kind: String,
101    /// Human-readable title.
102    pub title: String,
103    /// Raw Markdown body.
104    pub body: String,
105    /// Rendered HTML (cached). Defaults to empty string if not provided.
106    pub body_html: String,
107    /// Arbitrary JSON-compatible metadata.
108    pub properties: Properties,
109}
110
111/// Partial update for an existing node.
112///
113/// Only `Some` fields are applied; `None` fields are left unchanged.
114#[derive(Debug, Clone, Default, Serialize, Deserialize)]
115pub struct NodePatch {
116    /// New value for [`Node::kind`]; the kind index is rewritten when set.
117    pub kind: Option<String>,
118    /// New value for [`Node::title`]; the title index and FTS are rewritten
119    /// when set.
120    pub title: Option<String>,
121    /// New value for [`Node::body`]; the FTS index is rewritten when set.
122    pub body: Option<String>,
123    /// New value for [`Node::body_html`]; the cached rendered HTML.
124    pub body_html: Option<String>,
125    /// New value for [`Node::properties`]; replaces the entire map.
126    pub properties: Option<Properties>,
127}
128
129/// A directed edge connecting two nodes.
130///
131/// Edges represent relationships (links_to, tagged_with, depends_on, etc.).
132/// The `weight` field supports ranking and weighted traversal.
133#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
134pub struct Edge {
135    /// Auto-incremented unique identifier.
136    pub id: u64,
137    /// UUID v7 — sortable, globally unique.
138    pub uuid: [u8; 16],
139    /// Source node id.
140    pub from_id: u64,
141    /// Target node id.
142    pub to_id: u64,
143    /// Classification (e.g. "links_to", "tagged_with").
144    pub kind: String,
145    /// Weight for ranking/traversal (default 1.0).
146    pub weight: f32,
147    /// Creation timestamp (Unix milliseconds).
148    pub created_at: i64,
149    /// Arbitrary JSON-compatible metadata.
150    pub properties: Properties,
151}
152
153/// Input for creating a new edge.
154///
155/// Fields that the system generates (id, uuid, created_at) are omitted.
156#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct NewEdge {
158    /// Source node id.
159    pub from_id: u64,
160    /// Target node id.
161    pub to_id: u64,
162    /// Classification (e.g. "links_to", "tagged_with").
163    pub kind: String,
164    /// Weight for ranking/traversal (default 1.0).
165    pub weight: f32,
166    /// Arbitrary JSON-compatible metadata.
167    pub properties: Properties,
168}
169
170/// Partial update for an existing edge.
171///
172/// Only `Some` fields are applied; `None` fields are left unchanged.
173#[derive(Debug, Clone, Default, Serialize, Deserialize)]
174pub struct EdgePatch {
175    /// New classification for the edge (e.g. `"links_to"`).
176    pub kind: Option<String>,
177    /// New ranking weight for the edge (default `1.0`).
178    pub weight: Option<f32>,
179    /// Replaces the entire properties map.
180    pub properties: Option<Properties>,
181}
182
183/// Graph traversal direction.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum Direction {
186    /// Follow edges where `from_id` matches the given node.
187    Outgoing,
188    /// Follow edges where `to_id` matches the given node.
189    Incoming,
190    /// Follow edges in both directions.
191    Both,
192}
193
194/// A search result with a relevance score.
195///
196/// Returned by full-text search over nodes, ranked by Okapi BM25 score (see
197/// [`FtsRanking`]).
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct ScoredNode {
200    /// The matching node.
201    pub node: Node,
202    /// Relevance score (higher = more relevant).
203    pub score: f32,
204}
205
206/// A relationship search result with a relevance score.
207///
208/// Returned by full-text search over relationships, ranked by Okapi BM25 over
209/// their string properties.
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211pub struct ScoredEdge {
212    /// The matching edge.
213    pub edge: Edge,
214    /// Relevance score (higher = more relevant).
215    pub score: f32,
216}
217
218/// Relevance-ranking strategy for full-text search.
219///
220/// Search ranks with [`FtsRanking::default`] (Okapi BM25). The
221/// [`FtsRanking::TfIdf`] scorer is a deterministic, length-insensitive
222/// baseline for callers that need one (e.g. golden-ranking regression
223/// tests).
224#[derive(Debug, Clone, Copy, PartialEq)]
225pub enum FtsRanking {
226    /// Okapi BM25: term-frequency saturation (`k1`) plus document-length
227    /// normalization (`b`). Scores
228    /// `Σ idf(qᵢ) · tf·(k1+1) / (tf + k1·(1 − b + b·|d|/avgdl))`.
229    Bm25 {
230        /// Term-frequency saturation parameter (conventional default `1.2`).
231        /// Higher values let repeated terms keep accruing score; lower
232        /// values saturate sooner.
233        k1: f32,
234        /// Document-length normalization parameter in `[0, 1]`
235        /// (conventional default `0.75`). `0` disables length
236        /// normalization; `1` applies it fully.
237        b: f32,
238    },
239    /// Legacy TF-IDF: binary trigram presence normalized by the node's
240    /// trigram cardinality, weighted by smoothed IDF `ln(1 + N/df)`.
241    /// Kept for deterministic-baseline comparisons.
242    TfIdf,
243}
244
245impl FtsRanking {
246    /// BM25 with the conventional `k1 = 1.2`, `b = 0.75` defaults used by
247    /// Lucene, Elasticsearch, and Tantivy.
248    pub const fn bm25_default() -> Self {
249        FtsRanking::Bm25 { k1: 1.2, b: 0.75 }
250    }
251}
252
253impl Default for FtsRanking {
254    fn default() -> Self {
255        FtsRanking::bm25_default()
256    }
257}
258
259/// A subgraph extracted by bounded traversal from a root node.
260///
261/// Contains all nodes and edges within a given radius (depth) of
262/// the root. Useful for providing bounded context to AI agents
263/// (e.g. via MCP) or exporting a local neighborhood of the graph.
264#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
265pub struct SubGraph {
266    /// All nodes within the traversal radius, including the root node.
267    pub nodes: Vec<Node>,
268    /// All edges that connect nodes within the subgraph.
269    pub edges: Vec<Edge>,
270}
271
272/// Generate a new UUID v7 as a 16-byte array.
273#[cfg(not(target_arch = "wasm32"))]
274pub fn new_uuid_v7() -> [u8; 16] {
275    *uuid::Uuid::now_v7().as_bytes()
276}
277
278/// Generate a new UUID v7 as a 16-byte array (wasm32).
279///
280/// `Uuid::now_v7()` reads the wall clock through `std::time::SystemTime`,
281/// which is unimplemented on `wasm32-unknown-unknown` and aborts with
282/// `unreachable`. Derive the v7 timestamp from [`now_ms`] (the JS clock)
283/// instead; the random bits still come from `getrandom` (the `wasm_js`
284/// backend enabled by the `wasm` feature).
285#[cfg(target_arch = "wasm32")]
286pub fn new_uuid_v7() -> [u8; 16] {
287    let ms = now_ms();
288    let secs = (ms / 1000) as u64;
289    let nanos = ((ms % 1000) * 1_000_000) as u32;
290    let ts = uuid::Timestamp::from_unix(uuid::NoContext, secs, nanos);
291    *uuid::Uuid::new_v7(ts).as_bytes()
292}
293
294/// Return the current time as Unix milliseconds.
295///
296/// Total function — never panics. If the host clock is set before the Unix
297/// epoch (`SystemTime::now() < UNIX_EPOCH`), the timestamp is returned as a
298/// negative value reflecting the offset before the epoch, satisfying
299/// `drevo-rust` §"Error Handling" + `drevo-architecture` anti-pattern #5
300/// ("no `unwrap()` / `expect()` in library code").
301#[cfg(not(target_arch = "wasm32"))]
302pub fn now_ms() -> i64 {
303    match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
304        Ok(dur) => dur.as_millis() as i64,
305        Err(err) => -(err.duration().as_millis() as i64),
306    }
307}
308
309/// Return the current time as Unix milliseconds (wasm32).
310///
311/// `std::time::SystemTime::now()` is unimplemented on
312/// `wasm32-unknown-unknown` and aborts with `unreachable`, so read the wall
313/// clock from the JS host via `Date.now()`. `js-sys` is always available on
314/// wasm32 (see the target-specific dependency in `Cargo.toml`).
315#[cfg(target_arch = "wasm32")]
316pub fn now_ms() -> i64 {
317    js_sys::Date::now() as i64
318}
319
320impl Node {
321    /// Apply a [`NodePatch`] to this node, updating only the fields that are `Some`.
322    /// Automatically updates `updated_at` timestamp.
323    pub fn apply_patch(&mut self, patch: NodePatch) {
324        if let Some(kind) = patch.kind {
325            self.kind = kind;
326        }
327        if let Some(title) = patch.title {
328            self.title = title;
329        }
330        if let Some(body) = patch.body {
331            self.body = body;
332        }
333        if let Some(body_html) = patch.body_html {
334            self.body_html = body_html;
335        }
336        if let Some(properties) = patch.properties {
337            self.properties = properties;
338        }
339        self.updated_at = now_ms();
340    }
341}
342
343impl Edge {
344    /// Apply an [`EdgePatch`] to this edge, updating only the fields that are `Some`.
345    pub fn apply_patch(&mut self, patch: EdgePatch) {
346        if let Some(kind) = patch.kind {
347            self.kind = kind;
348        }
349        if let Some(weight) = patch.weight {
350            self.weight = weight;
351        }
352        if let Some(properties) = patch.properties {
353            self.properties = properties;
354        }
355    }
356}
357
358impl NewNode {
359    /// Create a [`Node`] from this input, assigning the given id and generating uuid/timestamps.
360    pub fn into_node(self, id: u64) -> Node {
361        let now = now_ms();
362        Node {
363            id,
364            uuid: new_uuid_v7(),
365            kind: self.kind,
366            title: self.title,
367            body: self.body,
368            body_html: self.body_html,
369            created_at: now,
370            updated_at: now,
371            properties: self.properties,
372        }
373    }
374}
375
376impl NewEdge {
377    /// Create an [`Edge`] from this input, assigning the given id and generating uuid/timestamp.
378    pub fn into_edge(self, id: u64) -> Edge {
379        Edge {
380            id,
381            uuid: new_uuid_v7(),
382            from_id: self.from_id,
383            to_id: self.to_id,
384            kind: self.kind,
385            weight: self.weight,
386            created_at: now_ms(),
387            properties: self.properties,
388        }
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use serde_json::json;
396
397    fn sample_new_node() -> NewNode {
398        let mut props = HashMap::new();
399        props.insert("priority".to_string(), json!(1));
400        NewNode {
401            kind: "note".to_string(),
402            title: "Test Node".to_string(),
403            body: "# Hello\nWorld".to_string(),
404            body_html: "<h1>Hello</h1><p>World</p>".to_string(),
405            properties: Properties::from(props),
406        }
407    }
408
409    fn sample_new_edge() -> NewEdge {
410        let mut props = HashMap::new();
411        props.insert("label".to_string(), json!("related"));
412        NewEdge {
413            from_id: 1,
414            to_id: 2,
415            kind: "links_to".to_string(),
416            weight: 1.0,
417            properties: Properties::from(props),
418        }
419    }
420
421    // --- UUID v7 ---
422
423    #[test]
424    fn uuid_v7_is_valid() {
425        let bytes = new_uuid_v7();
426        let uuid = uuid::Uuid::from_bytes(bytes);
427        assert_eq!(uuid.get_version(), Some(uuid::Version::SortRand));
428    }
429
430    #[test]
431    fn uuid_v7_is_unique() {
432        let a = new_uuid_v7();
433        let b = new_uuid_v7();
434        assert_ne!(a, b);
435    }
436
437    #[test]
438    fn uuid_v7_is_sortable_by_time() {
439        let a = new_uuid_v7();
440        // Small delay to ensure different timestamp
441        std::thread::sleep(std::time::Duration::from_millis(2));
442        let b = new_uuid_v7();
443        assert!(a < b, "UUID v7 should be time-sortable");
444    }
445
446    // --- now_ms ---
447
448    #[test]
449    fn now_ms_returns_reasonable_timestamp() {
450        let ts = now_ms();
451        // Should be after 2024-01-01 (1704067200000)
452        assert!(ts > 1_704_067_200_000);
453        // Should be before 2100-01-01
454        assert!(ts < 4_102_444_800_000);
455    }
456
457    // --- NewNode::into_node ---
458
459    #[test]
460    fn new_node_into_node_sets_id() {
461        let node = sample_new_node().into_node(42);
462        assert_eq!(node.id, 42);
463    }
464
465    #[test]
466    fn new_node_into_node_generates_uuid() {
467        let node = sample_new_node().into_node(1);
468        let uuid = uuid::Uuid::from_bytes(node.uuid);
469        assert_eq!(uuid.get_version(), Some(uuid::Version::SortRand));
470    }
471
472    #[test]
473    fn new_node_into_node_copies_fields() {
474        let input = sample_new_node();
475        let node = input.clone().into_node(1);
476        assert_eq!(node.kind, input.kind);
477        assert_eq!(node.title, input.title);
478        assert_eq!(node.body, input.body);
479        assert_eq!(node.body_html, input.body_html);
480        assert_eq!(node.properties, input.properties);
481    }
482
483    #[test]
484    fn new_node_into_node_sets_timestamps() {
485        let before = now_ms();
486        let node = sample_new_node().into_node(1);
487        let after = now_ms();
488        assert!(node.created_at >= before && node.created_at <= after);
489        assert_eq!(node.created_at, node.updated_at);
490    }
491
492    // --- NewEdge::into_edge ---
493
494    #[test]
495    fn new_edge_into_edge_sets_id() {
496        let edge = sample_new_edge().into_edge(99);
497        assert_eq!(edge.id, 99);
498    }
499
500    #[test]
501    fn new_edge_into_edge_copies_fields() {
502        let input = sample_new_edge();
503        let edge = input.clone().into_edge(1);
504        assert_eq!(edge.from_id, input.from_id);
505        assert_eq!(edge.to_id, input.to_id);
506        assert_eq!(edge.kind, input.kind);
507        assert_eq!(edge.weight, input.weight);
508        assert_eq!(edge.properties, input.properties);
509    }
510
511    #[test]
512    fn new_edge_into_edge_generates_uuid() {
513        let edge = sample_new_edge().into_edge(1);
514        let uuid = uuid::Uuid::from_bytes(edge.uuid);
515        assert_eq!(uuid.get_version(), Some(uuid::Version::SortRand));
516    }
517
518    #[test]
519    fn new_edge_into_edge_sets_timestamp() {
520        let before = now_ms();
521        let edge = sample_new_edge().into_edge(1);
522        let after = now_ms();
523        assert!(edge.created_at >= before && edge.created_at <= after);
524    }
525
526    // --- Node::apply_patch ---
527
528    #[test]
529    fn apply_patch_updates_only_some_fields() {
530        let mut node = sample_new_node().into_node(1);
531        let original_kind = node.kind.clone();
532        let original_body = node.body.clone();
533
534        node.apply_patch(NodePatch {
535            title: Some("Updated Title".to_string()),
536            ..Default::default()
537        });
538
539        assert_eq!(node.title, "Updated Title");
540        assert_eq!(node.kind, original_kind);
541        assert_eq!(node.body, original_body);
542    }
543
544    #[test]
545    fn apply_patch_updates_all_fields() {
546        let mut node = sample_new_node().into_node(1);
547        let mut new_props = HashMap::new();
548        new_props.insert("status".to_string(), json!("done"));
549        let new_props = Properties::from(new_props);
550
551        node.apply_patch(NodePatch {
552            kind: Some("task".to_string()),
553            title: Some("New Title".to_string()),
554            body: Some("New body".to_string()),
555            body_html: Some("<p>New body</p>".to_string()),
556            properties: Some(new_props.clone()),
557        });
558
559        assert_eq!(node.kind, "task");
560        assert_eq!(node.title, "New Title");
561        assert_eq!(node.body, "New body");
562        assert_eq!(node.body_html, "<p>New body</p>");
563        assert_eq!(node.properties, new_props);
564    }
565
566    #[test]
567    fn apply_patch_updates_timestamp() {
568        let mut node = sample_new_node().into_node(1);
569        let old_updated = node.updated_at;
570        std::thread::sleep(std::time::Duration::from_millis(2));
571
572        node.apply_patch(NodePatch {
573            title: Some("Changed".to_string()),
574            ..Default::default()
575        });
576
577        assert!(node.updated_at > old_updated);
578    }
579
580    #[test]
581    fn apply_empty_patch_only_updates_timestamp() {
582        let mut node = sample_new_node().into_node(1);
583        let original = node.clone();
584        std::thread::sleep(std::time::Duration::from_millis(2));
585
586        node.apply_patch(NodePatch::default());
587
588        assert_eq!(node.kind, original.kind);
589        assert_eq!(node.title, original.title);
590        assert!(node.updated_at > original.updated_at);
591    }
592
593    // --- Edge::apply_patch ---
594
595    #[test]
596    fn edge_apply_patch_updates_some_fields() {
597        let mut edge = sample_new_edge().into_edge(1);
598        let original_kind = edge.kind.clone();
599
600        edge.apply_patch(EdgePatch {
601            weight: Some(2.5),
602            ..Default::default()
603        });
604
605        assert_eq!(edge.weight, 2.5);
606        assert_eq!(edge.kind, original_kind);
607    }
608
609    #[test]
610    fn edge_apply_patch_updates_all_fields() {
611        let mut edge = sample_new_edge().into_edge(1);
612        let mut new_props = HashMap::new();
613        new_props.insert("color".to_string(), json!("red"));
614        let new_props = Properties::from(new_props);
615
616        edge.apply_patch(EdgePatch {
617            kind: Some("blocks".to_string()),
618            weight: Some(0.5),
619            properties: Some(new_props.clone()),
620        });
621
622        assert_eq!(edge.kind, "blocks");
623        assert_eq!(edge.weight, 0.5);
624        assert_eq!(edge.properties, new_props);
625    }
626
627    // --- Serialization ---
628
629    #[test]
630    fn node_serializes_to_bincode_roundtrip() {
631        let node = sample_new_node().into_node(1);
632        let config = bincode::config::standard();
633        let bytes = bincode::serde::encode_to_vec(&node, config).unwrap();
634        let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
635        assert_eq!(decoded, node);
636    }
637
638    #[test]
639    fn edge_serializes_to_bincode_roundtrip() {
640        let edge = sample_new_edge().into_edge(1);
641        let config = bincode::config::standard();
642        let bytes = bincode::serde::encode_to_vec(&edge, config).unwrap();
643        let (decoded, _): (Edge, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
644        assert_eq!(decoded, edge);
645    }
646
647    #[test]
648    fn node_serializes_to_json_roundtrip() {
649        let node = sample_new_node().into_node(1);
650        let json = serde_json::to_string(&node).unwrap();
651        let decoded: Node = serde_json::from_str(&json).unwrap();
652        assert_eq!(decoded, node);
653    }
654
655    #[test]
656    fn edge_serializes_to_json_roundtrip() {
657        let edge = sample_new_edge().into_edge(1);
658        let json = serde_json::to_string(&edge).unwrap();
659        let decoded: Edge = serde_json::from_str(&json).unwrap();
660        assert_eq!(decoded, edge);
661    }
662
663    #[test]
664    fn node_with_empty_properties_serializes() {
665        let node = NewNode {
666            kind: "note".to_string(),
667            title: "Empty".to_string(),
668            body: String::new(),
669            body_html: String::new(),
670            properties: Properties::default(),
671        }
672        .into_node(1);
673
674        let config = bincode::config::standard();
675        let bytes = bincode::serde::encode_to_vec(&node, config).unwrap();
676        let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
677        assert_eq!(decoded, node);
678    }
679
680    #[test]
681    fn node_with_complex_properties_serializes() {
682        let mut props = HashMap::new();
683        props.insert("tags".to_string(), json!(["rust", "graph", "db"]));
684        props.insert("nested".to_string(), json!({"a": {"b": 42}}));
685        props.insert("flag".to_string(), json!(true));
686        props.insert("score".to_string(), json!(2.71));
687        props.insert("empty".to_string(), json!(null));
688
689        let node = NewNode {
690            kind: "note".to_string(),
691            title: "Complex".to_string(),
692            body: String::new(),
693            body_html: String::new(),
694            properties: Properties::from(props),
695        }
696        .into_node(1);
697
698        let config = bincode::config::standard();
699        let bytes = bincode::serde::encode_to_vec(&node, config).unwrap();
700        let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
701        assert_eq!(decoded, node);
702    }
703
704    // --- Direction ---
705
706    #[test]
707    fn direction_variants_are_distinct() {
708        assert_ne!(Direction::Outgoing, Direction::Incoming);
709        assert_ne!(Direction::Outgoing, Direction::Both);
710        assert_ne!(Direction::Incoming, Direction::Both);
711    }
712
713    #[test]
714    fn direction_clone_eq() {
715        let d = Direction::Outgoing;
716        let d2 = d;
717        assert_eq!(d, d2);
718    }
719
720    // --- Deterministic bincode (drevo-rust §"Serialization") ---
721
722    fn build_properties(pairs: &[(&str, serde_json::Value)]) -> Properties {
723        let mut props = HashMap::new();
724        for (k, v) in pairs {
725            props.insert((*k).to_string(), v.clone());
726        }
727        Properties::from(props)
728    }
729
730    #[test]
731    fn properties_bincode_is_deterministic_across_insertion_order() {
732        // Two HashMaps with identical content but different insertion order
733        // must serialize to identical bincode bytes — the storage layer relies
734        // on `bincode v2 — compact, fast, deterministic` (drevo-rust §"Serialization").
735        let a = build_properties(&[
736            ("alpha", json!(1)),
737            ("beta", json!("two")),
738            ("gamma", json!([3, 4, 5])),
739            ("delta", json!({"nested": true})),
740        ]);
741        let b = build_properties(&[
742            ("delta", json!({"nested": true})),
743            ("gamma", json!([3, 4, 5])),
744            ("alpha", json!(1)),
745            ("beta", json!("two")),
746        ]);
747
748        let config = bincode::config::standard();
749        let bytes_a = bincode::serde::encode_to_vec(&a, config).unwrap();
750        let bytes_b = bincode::serde::encode_to_vec(&b, config).unwrap();
751
752        assert_eq!(
753            bytes_a, bytes_b,
754            "Properties bincode must be byte-identical for equivalent contents \
755             irrespective of HashMap insertion order"
756        );
757    }
758
759    #[test]
760    fn node_bincode_is_deterministic_across_property_insertion_order() {
761        // Same Node logical content, two different property insertion orders →
762        // the entire Node must bincode-encode to identical bytes.
763        let make = |order_a: bool| {
764            let pairs: &[(&str, serde_json::Value)] = if order_a {
765                &[("k1", json!(1)), ("k2", json!(2)), ("k3", json!(3))]
766            } else {
767                &[("k3", json!(3)), ("k1", json!(1)), ("k2", json!(2))]
768            };
769            Node {
770                id: 7,
771                uuid: [0u8; 16],
772                kind: "note".to_string(),
773                title: "T".to_string(),
774                body: "B".to_string(),
775                body_html: String::new(),
776                created_at: 1,
777                updated_at: 1,
778                properties: build_properties(pairs),
779            }
780        };
781
782        let config = bincode::config::standard();
783        let bytes_a = bincode::serde::encode_to_vec(make(true), config).unwrap();
784        let bytes_b = bincode::serde::encode_to_vec(make(false), config).unwrap();
785        assert_eq!(bytes_a, bytes_b);
786    }
787
788    // --- now_ms total — must not panic (drevo-rust §"Error Handling" + drevo-architecture anti-pattern #5) ---
789
790    #[test]
791    fn now_ms_is_total_and_does_not_panic() {
792        for _ in 0..32 {
793            let _ = now_ms();
794        }
795    }
796
797    // --- Unicode edge cases (drevo-tdd §"Edge cases mandatory: Unicode (CJK, emoji, Cyrillic)") ---
798
799    fn roundtrip_node_bincode(node: &Node) {
800        let config = bincode::config::standard();
801        let bytes = bincode::serde::encode_to_vec(node, config).unwrap();
802        let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
803        assert_eq!(decoded, *node);
804    }
805
806    fn roundtrip_node_json(node: &Node) {
807        let s = serde_json::to_string(node).unwrap();
808        let decoded: Node = serde_json::from_str(&s).unwrap();
809        assert_eq!(decoded, *node);
810    }
811
812    #[test]
813    fn node_with_cjk_content_serializes_roundtrip() {
814        let node = NewNode {
815            kind: "note".to_string(),
816            // Chinese / Japanese / Korean characters
817            title: "知识图谱・グラフノート・지식그래프".to_string(),
818            body: "# 标题\n本文。これは本文です。본문 내용입니다。".to_string(),
819            body_html: "<h1>标题</h1>".to_string(),
820            properties: Properties::default(),
821        }
822        .into_node(1);
823        roundtrip_node_bincode(&node);
824        roundtrip_node_json(&node);
825    }
826
827    #[test]
828    fn node_with_emoji_content_serializes_roundtrip() {
829        let node = NewNode {
830            kind: "note".to_string(),
831            title: "🚀 launch 🌍".to_string(),
832            body: "🔥 multi-codepoint: 👨‍👩‍👧‍👦 family ZWJ sequence".to_string(),
833            body_html: String::new(),
834            properties: Properties::default(),
835        }
836        .into_node(1);
837        roundtrip_node_bincode(&node);
838        roundtrip_node_json(&node);
839    }
840
841    #[test]
842    fn node_with_cyrillic_content_serializes_roundtrip() {
843        let node = NewNode {
844            kind: "заметка".to_string(),
845            title: "Привет, мир!".to_string(),
846            body: "Граф-база данных — производительная и надёжная.".to_string(),
847            body_html: String::new(),
848            properties: Properties::default(),
849        }
850        .into_node(1);
851        roundtrip_node_bincode(&node);
852        roundtrip_node_json(&node);
853    }
854
855    #[test]
856    fn properties_with_unicode_keys_and_values_roundtrip() {
857        let props = build_properties(&[
858            ("标签", json!("中文")),
859            ("emoji_🔑", json!("🌈")),
860            ("кириллица", json!({"вложенный": true})),
861        ]);
862        let config = bincode::config::standard();
863        let bytes = bincode::serde::encode_to_vec(&props, config).unwrap();
864        let (decoded, _): (Properties, _) =
865            bincode::serde::decode_from_slice(&bytes, config).unwrap();
866        assert_eq!(decoded, props);
867
868        // JSON roundtrip too
869        let json = serde_json::to_string(&props).unwrap();
870        let from_json: Properties = serde_json::from_str(&json).unwrap();
871        assert_eq!(from_json, props);
872    }
873
874    #[test]
875    fn edge_with_cyrillic_kind_serializes_roundtrip() {
876        let edge = NewEdge {
877            from_id: 1,
878            to_id: 2,
879            kind: "связано_с".to_string(),
880            weight: 1.0,
881            properties: Properties::default(),
882        }
883        .into_edge(1);
884        let config = bincode::config::standard();
885        let bytes = bincode::serde::encode_to_vec(&edge, config).unwrap();
886        let (decoded, _): (Edge, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
887        assert_eq!(decoded, edge);
888    }
889}