aingle_minimal 0.6.2

Ultra-light AIngle node for IoT devices (<1MB RAM)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial

//! Semantic Graph integration for AIngle Minimal
//!
//! This module provides a semantic graph view of the AIngle data,
//! converting Actions and Entries into semantic triples that can be
//! queried using graph patterns and traversals.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                   Semantic Layer                             │
//! │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
//! │  │  GraphDB    │  │  Indexes    │  │  Query Engine       │  │
//! │  │  (triples)  │  │  SPO/POS/OSP│  │  Pattern Matching   │  │
//! │  └─────────────┘  └─────────────┘  └─────────────────────┘  │
//! └───────────────────────────┬─────────────────────────────────┘
//!                             │ converts
//! ┌───────────────────────────┴─────────────────────────────────┐
//! │                   AIngle Layer                               │
//! │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
//! │  │  Actions    │  │  Entries    │  │  Links              │  │
//! │  └─────────────┘  └─────────────┘  └─────────────────────┘  │
//! └─────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use aingle_minimal::graph::{SemanticGraph, SemanticQuery};
//!
//! // Create graph view of the node's data
//! let graph = SemanticGraph::new();
//!
//! // Query for all records authored by a specific agent
//! let results = graph.query()
//!     .subject_of_type("Action")
//!     .with_predicate("aingle:author")
//!     .with_object_literal("agent123")
//!     .execute()?;
//! ```

use crate::error::{Error, Result};
use crate::types::{Action, Entry, Hash, Link, Record};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// A semantic triple representing a fact
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SemanticTriple {
    /// Subject (the thing being described)
    pub subject: String,
    /// Predicate (the relationship)
    pub predicate: String,
    /// Object (the value or related thing)
    pub object: TripleObject,
    /// Source hash (original AIngle record)
    pub source_hash: Option<Hash>,
}

/// Object of a triple - can be a literal or a reference
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TripleObject {
    /// A literal value
    Literal(String),
    /// An integer value
    Integer(i64),
    /// A reference to another node
    Reference(String),
    /// A hash reference (to AIngle data)
    Hash(Hash),
    /// A boolean value
    Boolean(bool),
}

impl TripleObject {
    pub fn as_string(&self) -> Option<&str> {
        match self {
            Self::Literal(s) => Some(s),
            _ => None,
        }
    }
}

/// In-memory semantic graph index
struct GraphIndex {
    /// SPO index: subject -> predicate -> objects
    spo: HashMap<String, HashMap<String, Vec<TripleObject>>>,
    /// POS index: predicate -> object_key -> subjects
    pos: HashMap<String, HashMap<String, Vec<String>>>,
    /// All triples stored
    triples: Vec<SemanticTriple>,
}

impl GraphIndex {
    fn new() -> Self {
        Self {
            spo: HashMap::new(),
            pos: HashMap::new(),
            triples: Vec::new(),
        }
    }

    fn insert(&mut self, triple: SemanticTriple) {
        // SPO index
        self.spo
            .entry(triple.subject.clone())
            .or_default()
            .entry(triple.predicate.clone())
            .or_default()
            .push(triple.object.clone());

        // POS index
        let obj_key = format!("{:?}", triple.object);
        self.pos
            .entry(triple.predicate.clone())
            .or_default()
            .entry(obj_key)
            .or_default()
            .push(triple.subject.clone());

        // Store full triple
        self.triples.push(triple);
    }

    fn find_by_subject(&self, subject: &str) -> Vec<&SemanticTriple> {
        self.triples
            .iter()
            .filter(|t| t.subject == subject)
            .collect()
    }

    fn find_by_predicate(&self, predicate: &str) -> Vec<&SemanticTriple> {
        self.triples
            .iter()
            .filter(|t| t.predicate == predicate)
            .collect()
    }
}

/// Semantic graph view of AIngle data
pub struct SemanticGraph {
    index: Arc<RwLock<GraphIndex>>,
}

impl SemanticGraph {
    /// Create a new empty semantic graph
    pub fn new() -> Self {
        Self {
            index: Arc::new(RwLock::new(GraphIndex::new())),
        }
    }

    /// Index an Action as semantic triples
    pub fn index_action(&self, action: &Action) -> Result<()> {
        let mut index = self
            .index
            .write()
            .map_err(|_| Error::storage("lock poisoned"))?;

        let action_hash = action.hash();
        let subject = format!("action:{}", action_hash.to_hex());

        // Type triple
        index.insert(SemanticTriple {
            subject: subject.clone(),
            predicate: "rdf:type".to_string(),
            object: TripleObject::Literal(format!("{:?}", action.action_type)),
            source_hash: Some(action_hash.clone()),
        });

        // Sequence number
        index.insert(SemanticTriple {
            subject: subject.clone(),
            predicate: "aingle:seq".to_string(),
            object: TripleObject::Integer(action.seq as i64),
            source_hash: Some(action_hash.clone()),
        });

        // Previous action (if any)
        if let Some(ref prev) = action.prev_action {
            index.insert(SemanticTriple {
                subject: subject.clone(),
                predicate: "aingle:prevAction".to_string(),
                object: TripleObject::Hash(prev.clone()),
                source_hash: Some(action_hash.clone()),
            });
        }

        // Entry hash (if any)
        if let Some(ref entry_hash) = action.entry_hash {
            index.insert(SemanticTriple {
                subject: subject.clone(),
                predicate: "aingle:entryHash".to_string(),
                object: TripleObject::Hash(entry_hash.clone()),
                source_hash: Some(action_hash.clone()),
            });
        }

        // Author
        index.insert(SemanticTriple {
            subject: subject.clone(),
            predicate: "aingle:author".to_string(),
            object: TripleObject::Literal(action.author.to_hex()),
            source_hash: Some(action_hash.clone()),
        });

        // Timestamp
        index.insert(SemanticTriple {
            subject,
            predicate: "aingle:timestamp".to_string(),
            object: TripleObject::Integer(action.timestamp.0 as i64),
            source_hash: Some(action_hash),
        });

        Ok(())
    }

    /// Index an Entry as semantic triples
    pub fn index_entry(&self, entry: &Entry) -> Result<()> {
        let mut index = self
            .index
            .write()
            .map_err(|_| Error::storage("lock poisoned"))?;

        let entry_hash = entry.hash();
        let subject = format!("entry:{}", entry_hash.to_hex());

        // Type triple
        index.insert(SemanticTriple {
            subject: subject.clone(),
            predicate: "rdf:type".to_string(),
            object: TripleObject::Literal(format!("{:?}", entry.entry_type)),
            source_hash: Some(entry_hash.clone()),
        });

        // Content hash
        index.insert(SemanticTriple {
            subject,
            predicate: "aingle:contentHash".to_string(),
            object: TripleObject::Hash(entry_hash.clone()),
            source_hash: Some(entry_hash),
        });

        Ok(())
    }

    /// Index a Link as semantic triples
    pub fn index_link(&self, link: &Link) -> Result<()> {
        let mut index = self
            .index
            .write()
            .map_err(|_| Error::storage("lock poisoned"))?;

        let base_subject = format!("entry:{}", link.base.to_hex());
        let target = format!("entry:{}", link.target.to_hex());

        // Link as triple
        let predicate = format!("link:{}", link.link_type);
        index.insert(SemanticTriple {
            subject: base_subject,
            predicate,
            object: TripleObject::Reference(target),
            source_hash: None,
        });

        Ok(())
    }

    /// Index a full Record (Action + Entry)
    pub fn index_record(&self, record: &Record) -> Result<()> {
        self.index_action(&record.action)?;
        if let Some(ref entry) = record.entry {
            self.index_entry(entry)?;
        }
        Ok(())
    }

    /// Start building a query
    pub fn query(&self) -> SemanticQuery<'_> {
        SemanticQuery::new(self)
    }

    /// Find all triples for a subject
    pub fn get_subject(&self, subject: &str) -> Result<Vec<SemanticTriple>> {
        let index = self
            .index
            .read()
            .map_err(|_| Error::storage("lock poisoned"))?;
        Ok(index
            .find_by_subject(subject)
            .into_iter()
            .cloned()
            .collect())
    }

    /// Find all triples with a predicate
    pub fn get_predicate(&self, predicate: &str) -> Result<Vec<SemanticTriple>> {
        let index = self
            .index
            .read()
            .map_err(|_| Error::storage("lock poisoned"))?;
        Ok(index
            .find_by_predicate(predicate)
            .into_iter()
            .cloned()
            .collect())
    }

    /// Traverse the graph following links
    pub fn traverse(
        &self,
        start: &str,
        predicates: &[&str],
        max_depth: usize,
    ) -> Result<Vec<String>> {
        let index = self
            .index
            .read()
            .map_err(|_| Error::storage("lock poisoned"))?;

        let mut visited = std::collections::HashSet::new();
        let mut result = Vec::new();
        let mut frontier = vec![(start.to_string(), 0)];

        while let Some((current, depth)) = frontier.pop() {
            if depth > max_depth || visited.contains(&current) {
                continue;
            }
            visited.insert(current.clone());

            // Find outgoing edges
            for triple in index.find_by_subject(&current) {
                // Check if predicate matches
                if predicates.is_empty() || predicates.contains(&triple.predicate.as_str()) {
                    match &triple.object {
                        TripleObject::Reference(target) => {
                            result.push(target.clone());
                            frontier.push((target.clone(), depth + 1));
                        }
                        TripleObject::Hash(hash) => {
                            let target = format!("hash:{}", hash.to_hex());
                            result.push(target.clone());
                            frontier.push((target, depth + 1));
                        }
                        _ => {}
                    }
                }
            }
        }

        Ok(result)
    }

    /// Get graph statistics
    pub fn stats(&self) -> Result<GraphStats> {
        let index = self
            .index
            .read()
            .map_err(|_| Error::storage("lock poisoned"))?;

        Ok(GraphStats {
            triple_count: index.triples.len(),
            subject_count: index.spo.len(),
            predicate_count: index.pos.len(),
        })
    }
}

impl Default for SemanticGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// Query builder for semantic graph
pub struct SemanticQuery<'a> {
    graph: &'a SemanticGraph,
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<TripleObject>,
    limit: Option<usize>,
}

impl<'a> SemanticQuery<'a> {
    fn new(graph: &'a SemanticGraph) -> Self {
        Self {
            graph,
            subject: None,
            predicate: None,
            object: None,
            limit: None,
        }
    }

    /// Filter by subject
    pub fn subject(mut self, subject: &str) -> Self {
        self.subject = Some(subject.to_string());
        self
    }

    /// Filter by subject type (e.g., "Action", "Entry")
    pub fn subject_of_type(self, type_name: &str) -> Self {
        self.subject(&format!("{}:", type_name.to_lowercase()))
    }

    /// Filter by predicate
    pub fn with_predicate(mut self, predicate: &str) -> Self {
        self.predicate = Some(predicate.to_string());
        self
    }

    /// Filter by literal object value
    pub fn with_object_literal(mut self, value: &str) -> Self {
        self.object = Some(TripleObject::Literal(value.to_string()));
        self
    }

    /// Filter by reference object value
    pub fn with_object_reference(mut self, reference: &str) -> Self {
        self.object = Some(TripleObject::Reference(reference.to_string()));
        self
    }

    /// Limit results
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Execute the query
    pub fn execute(self) -> Result<Vec<SemanticTriple>> {
        let index = self
            .graph
            .index
            .read()
            .map_err(|_| Error::storage("lock poisoned"))?;

        let mut results: Vec<_> = index
            .triples
            .iter()
            .filter(|t| {
                // Subject filter
                if let Some(ref s) = self.subject {
                    if !t.subject.starts_with(s) {
                        return false;
                    }
                }
                // Predicate filter
                if let Some(ref p) = self.predicate {
                    if &t.predicate != p {
                        return false;
                    }
                }
                // Object filter
                if let Some(ref o) = self.object {
                    if &t.object != o {
                        return false;
                    }
                }
                true
            })
            .cloned()
            .collect();

        // Apply limit
        if let Some(limit) = self.limit {
            results.truncate(limit);
        }

        Ok(results)
    }
}

/// Graph statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GraphStats {
    /// Total number of triples
    pub triple_count: usize,
    /// Number of unique subjects
    pub subject_count: usize,
    /// Number of unique predicates
    pub predicate_count: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ActionType, AgentPubKey, Signature, Timestamp};

    fn random_hash() -> Hash {
        use rand::Rng;
        let mut bytes = [0u8; 32];
        rand::rng().fill(&mut bytes);
        Hash(bytes)
    }

    fn random_agent() -> AgentPubKey {
        use rand::Rng;
        let mut bytes = [0u8; 32];
        rand::rng().fill(&mut bytes);
        AgentPubKey(bytes)
    }

    fn random_signature() -> Signature {
        use rand::Rng;
        let mut bytes = [0u8; 64];
        rand::rng().fill(&mut bytes);
        Signature(bytes)
    }

    fn test_action() -> Action {
        Action {
            action_type: ActionType::Create,
            author: random_agent(),
            timestamp: Timestamp(1234567890),
            seq: 1,
            prev_action: None,
            entry_hash: Some(random_hash()),
            signature: random_signature(),
        }
    }

    #[test]
    fn test_index_action() {
        let graph = SemanticGraph::new();
        let action = test_action();

        graph.index_action(&action).unwrap();

        let stats = graph.stats().unwrap();
        assert_eq!(stats.triple_count, 5); // type, seq, entry_hash, author, timestamp (no prev_action)
    }

    #[test]
    fn test_query_by_predicate() {
        let graph = SemanticGraph::new();
        let action = test_action();
        graph.index_action(&action).unwrap();

        let results = graph
            .query()
            .with_predicate("aingle:seq")
            .execute()
            .unwrap();

        assert_eq!(results.len(), 1);
        assert!(matches!(results[0].object, TripleObject::Integer(1)));
    }

    #[test]
    fn test_traverse() {
        let graph = SemanticGraph::new();

        // Create linked entries
        let link = Link {
            base: random_hash(),
            target: random_hash(),
            link_type: 0,
            tag: Vec::new(),
            timestamp: Timestamp::now(),
        };
        graph.index_link(&link).unwrap();

        let base_subject = format!("entry:{}", link.base.to_hex());
        let reachable = graph.traverse(&base_subject, &["link:0"], 3).unwrap();

        assert_eq!(reachable.len(), 1);
    }

    #[test]
    fn test_get_subject() {
        let graph = SemanticGraph::new();
        let action = test_action();
        let action_hash = action.hash();
        graph.index_action(&action).unwrap();

        let subject = format!("action:{}", action_hash.to_hex());
        let triples = graph.get_subject(&subject).unwrap();

        assert!(!triples.is_empty());
        assert!(triples.iter().all(|t| t.subject == subject));
    }

    #[test]
    fn test_semantic_graph_default() {
        let graph: SemanticGraph = Default::default();
        let stats = graph.stats().unwrap();
        assert_eq!(stats.triple_count, 0);
        assert_eq!(stats.subject_count, 0);
        assert_eq!(stats.predicate_count, 0);
    }

    #[test]
    fn test_index_entry() {
        use crate::types::EntryType;

        let graph = SemanticGraph::new();
        let entry = Entry {
            entry_type: EntryType::App,
            content: vec![1, 2, 3],
        };

        graph.index_entry(&entry).unwrap();

        let stats = graph.stats().unwrap();
        assert_eq!(stats.triple_count, 2); // type + contentHash
    }

    #[test]
    fn test_index_link() {
        let graph = SemanticGraph::new();
        let link = Link {
            base: random_hash(),
            target: random_hash(),
            link_type: 1,
            tag: vec![1, 2, 3],
            timestamp: Timestamp::now(),
        };

        graph.index_link(&link).unwrap();

        let stats = graph.stats().unwrap();
        assert_eq!(stats.triple_count, 1);
    }

    #[test]
    fn test_index_record() {
        use crate::types::EntryType;

        let graph = SemanticGraph::new();
        let record = Record {
            action: test_action(),
            entry: Some(Entry {
                entry_type: EntryType::App,
                content: vec![1, 2, 3],
            }),
        };

        graph.index_record(&record).unwrap();

        let stats = graph.stats().unwrap();
        assert!(stats.triple_count >= 5); // action triples + entry triples
    }

    #[test]
    fn test_index_record_without_entry() {
        let graph = SemanticGraph::new();
        let record = Record {
            action: test_action(),
            entry: None,
        };

        graph.index_record(&record).unwrap();

        let stats = graph.stats().unwrap();
        assert!(stats.triple_count >= 5); // action triples only
    }

    #[test]
    fn test_query_by_subject() {
        let graph = SemanticGraph::new();
        let action = test_action();
        graph.index_action(&action).unwrap();

        let results = graph.query().subject_of_type("Action").execute().unwrap();

        assert!(!results.is_empty());
    }

    #[test]
    fn test_query_with_limit() {
        let graph = SemanticGraph::new();

        // Add multiple actions
        for _ in 0..5 {
            let mut action = test_action();
            action.timestamp = Timestamp(rand::random());
            graph.index_action(&action).unwrap();
        }

        let results = graph
            .query()
            .with_predicate("aingle:seq")
            .limit(2)
            .execute()
            .unwrap();

        assert!(results.len() <= 2);
    }

    #[test]
    fn test_query_with_object_literal() {
        let graph = SemanticGraph::new();
        let action = test_action();
        let author_hex = action.author.to_hex();
        graph.index_action(&action).unwrap();

        let results = graph
            .query()
            .with_predicate("aingle:author")
            .with_object_literal(&author_hex)
            .execute()
            .unwrap();

        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_query_with_object_reference() {
        let graph = SemanticGraph::new();

        let base = random_hash();
        let target = random_hash();
        let link = Link {
            base,
            target: target.clone(),
            link_type: 0,
            tag: Vec::new(),
            timestamp: Timestamp::now(),
        };
        graph.index_link(&link).unwrap();

        let target_ref = format!("entry:{}", target.to_hex());
        let results = graph
            .query()
            .with_object_reference(&target_ref)
            .execute()
            .unwrap();

        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_get_predicate() {
        let graph = SemanticGraph::new();
        let action = test_action();
        graph.index_action(&action).unwrap();

        let triples = graph.get_predicate("rdf:type").unwrap();
        assert_eq!(triples.len(), 1);

        let triples = graph.get_predicate("aingle:author").unwrap();
        assert_eq!(triples.len(), 1);
    }

    #[test]
    fn test_get_predicate_empty() {
        let graph = SemanticGraph::new();
        let triples = graph.get_predicate("nonexistent").unwrap();
        assert!(triples.is_empty());
    }

    #[test]
    fn test_traverse_empty_predicates() {
        let graph = SemanticGraph::new();

        let link = Link {
            base: random_hash(),
            target: random_hash(),
            link_type: 0,
            tag: Vec::new(),
            timestamp: Timestamp::now(),
        };
        graph.index_link(&link).unwrap();

        let base_subject = format!("entry:{}", link.base.to_hex());
        // Empty predicates means follow all
        let reachable = graph.traverse(&base_subject, &[], 3).unwrap();
        assert_eq!(reachable.len(), 1);
    }

    #[test]
    fn test_traverse_max_depth() {
        let graph = SemanticGraph::new();

        // Chain of links
        let hash1 = random_hash();
        let hash2 = random_hash();
        let hash3 = random_hash();

        let link1 = Link {
            base: hash1.clone(),
            target: hash2.clone(),
            link_type: 0,
            tag: Vec::new(),
            timestamp: Timestamp::now(),
        };
        let link2 = Link {
            base: hash2.clone(),
            target: hash3.clone(),
            link_type: 0,
            tag: Vec::new(),
            timestamp: Timestamp::now(),
        };

        graph.index_link(&link1).unwrap();
        graph.index_link(&link2).unwrap();

        let base_subject = format!("entry:{}", hash1.to_hex());

        // Depth 1 should find only first target
        let reachable = graph.traverse(&base_subject, &["link:0"], 1).unwrap();
        assert!(!reachable.is_empty());
    }

    #[test]
    fn test_triple_object_as_string() {
        let literal = TripleObject::Literal("hello".to_string());
        assert_eq!(literal.as_string(), Some("hello"));

        let integer = TripleObject::Integer(42);
        assert_eq!(integer.as_string(), None);

        let reference = TripleObject::Reference("ref".to_string());
        assert_eq!(reference.as_string(), None);

        let boolean = TripleObject::Boolean(true);
        assert_eq!(boolean.as_string(), None);

        let hash = TripleObject::Hash(random_hash());
        assert_eq!(hash.as_string(), None);
    }

    #[test]
    fn test_semantic_triple_serialization() {
        let triple = SemanticTriple {
            subject: "test:subject".to_string(),
            predicate: "test:predicate".to_string(),
            object: TripleObject::Literal("value".to_string()),
            source_hash: None,
        };

        let json = serde_json::to_string(&triple).unwrap();
        let deserialized: SemanticTriple = serde_json::from_str(&json).unwrap();

        assert_eq!(triple.subject, deserialized.subject);
        assert_eq!(triple.predicate, deserialized.predicate);
        assert_eq!(triple.object, deserialized.object);
    }

    #[test]
    fn test_triple_object_variants() {
        let obj1 = TripleObject::Integer(100);
        let obj2 = TripleObject::Boolean(false);
        let obj3 = TripleObject::Hash(random_hash());
        let obj4 = TripleObject::Reference("ref".to_string());

        // Test Debug
        let _ = format!("{:?}", obj1);
        let _ = format!("{:?}", obj2);
        let _ = format!("{:?}", obj3);
        let _ = format!("{:?}", obj4);

        // Test Clone
        let cloned = obj1.clone();
        assert_eq!(cloned, obj1);
    }

    #[test]
    fn test_graph_stats_serialization() {
        let stats = GraphStats {
            triple_count: 100,
            subject_count: 50,
            predicate_count: 10,
        };

        let json = serde_json::to_string(&stats).unwrap();
        let deserialized: GraphStats = serde_json::from_str(&json).unwrap();

        assert_eq!(stats.triple_count, deserialized.triple_count);
        assert_eq!(stats.subject_count, deserialized.subject_count);
        assert_eq!(stats.predicate_count, deserialized.predicate_count);
    }

    #[test]
    fn test_graph_stats_default() {
        let stats: GraphStats = Default::default();
        assert_eq!(stats.triple_count, 0);
        assert_eq!(stats.subject_count, 0);
        assert_eq!(stats.predicate_count, 0);
    }

    #[test]
    fn test_index_action_with_prev_action() {
        let graph = SemanticGraph::new();
        let mut action = test_action();
        action.prev_action = Some(random_hash());

        graph.index_action(&action).unwrap();

        let stats = graph.stats().unwrap();
        assert_eq!(stats.triple_count, 6); // 5 base + prev_action
    }

    #[test]
    fn test_index_action_without_entry_hash() {
        let graph = SemanticGraph::new();
        let mut action = test_action();
        action.entry_hash = None;

        graph.index_action(&action).unwrap();

        let stats = graph.stats().unwrap();
        assert_eq!(stats.triple_count, 4); // 5 - entry_hash
    }

    #[test]
    fn test_query_no_results() {
        let graph = SemanticGraph::new();
        let action = test_action();
        graph.index_action(&action).unwrap();

        let results = graph
            .query()
            .with_predicate("nonexistent:predicate")
            .execute()
            .unwrap();

        assert!(results.is_empty());
    }

    #[test]
    fn test_multiple_actions() {
        let graph = SemanticGraph::new();

        for i in 0..10 {
            let mut action = test_action();
            action.seq = i;
            graph.index_action(&action).unwrap();
        }

        let stats = graph.stats().unwrap();
        assert_eq!(stats.triple_count, 50); // 5 triples per action * 10

        let results = graph.query().with_predicate("rdf:type").execute().unwrap();

        assert_eq!(results.len(), 10);
    }
}