1use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::HashMap;
9use uuid::Uuid;
10
11pub use crate::memory::{RetrievalExplanation, RetrievalResult};
13
14pub type MemoryId = String;
16
17pub type ConnectionId = String;
19
20
21
22pub type SessionId = String;
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
27pub enum MemoryType {
28 Knowledge, Event, Task, Conversation, Reflection, Goal, Habit, Emotion, }
37
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40pub enum UserState {
41 Active,
43 Learning,
45 Idle,
47 Busy,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
53pub enum EmotionalState {
54 Neutral,
56 Curious,
58 Excited,
60 Interested,
62 Confused,
64 Satisfied,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
70pub enum AttentionLevel {
71 Low,
73 Medium,
75 High,
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
83pub struct Memory {
84 pub id: MemoryId,
86 pub content: String,
88 pub memory_type: MemoryType,
90 pub embedding: Vec<f32>,
92 pub attributes: MemoryAttributes,
94 pub connections: MemoryConnections,
96 pub metadata: MemoryMetadata,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
104pub struct MemoryAttributes {
105 pub keywords: Vec<String>,
107 pub tags: Vec<String>,
109 pub context: String,
111 pub importance: f32,
113 pub emotion: Option<String>,
115 pub source: Option<String>,
117 pub confidence: f32,
119 pub language: Option<String>,
121 pub custom_attributes: HashMap<String, Value>,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
129pub struct MemoryConnections {
130 pub semantic_links: Vec<MemoryId>,
132 pub temporal_links: Vec<MemoryId>,
134 pub causal_links: Vec<MemoryId>,
136 pub thematic_links: Vec<MemoryId>,
138 pub custom_links: HashMap<String, Vec<MemoryId>>,
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
146pub struct MemoryMetadata {
147 pub created_at: DateTime<Utc>,
149 pub updated_at: DateTime<Utc>,
151 pub access_count: u64,
153 pub last_accessed: DateTime<Utc>,
155 pub version: u32,
157 pub is_deleted: bool,
159 pub deleted_at: Option<DateTime<Utc>>,
161 pub custom_metadata: HashMap<String, Value>,
163}
164
165#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
169pub struct Context {
170 pub session_id: Option<SessionId>,
172 pub current_topic: Option<String>,
174 pub recent_memories: Vec<MemoryId>,
176 pub user_preferences: HashMap<String, Value>,
178 pub environment: HashMap<String, Value>,
180 pub time_window: Option<(DateTime<Utc>, DateTime<Utc>)>,
182 pub priority: Priority,
184}
185
186#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
188pub enum Priority {
189 Low,
190 Normal,
191 High,
192 Critical,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
199pub struct Query {
200 pub text: String,
202 pub query_type: QueryType,
204 pub filters: QueryFilters,
206 pub limit: Option<usize>,
208 pub offset: Option<usize>,
210 pub sort_by: Option<SortBy>,
212 pub weights: QueryWeights,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
218pub enum QueryType {
219 Semantic,
221 Temporal,
223 Causal,
225 Thematic,
227 Mixed,
229 GraphTraversal,
231 PersonalizedPageRank,
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
239pub struct QueryFilters {
240 pub tags: Option<Vec<String>>,
242 pub time_range: Option<(DateTime<Utc>, DateTime<Utc>)>,
244 pub importance_threshold: Option<f32>,
246 pub source_filter: Option<String>,
248 pub language_filter: Option<String>,
250 pub emotion_filter: Option<String>,
252 pub confidence_threshold: Option<f32>,
254 pub custom_filters: HashMap<String, Value>,
256}
257
258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
260pub enum SortBy {
261 Relevance,
263 Time,
265 Importance,
267 AccessCount,
269 Confidence,
271 Custom(String),
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
279pub struct QueryWeights {
280 pub semantic_weight: f32,
282 pub temporal_weight: f32,
284 pub importance_weight: f32,
286 pub frequency_weight: f32,
288 pub personalization_weight: f32,
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
296pub struct Connection {
297 pub id: ConnectionId,
299 pub from_memory: MemoryId,
301 pub to_memory: MemoryId,
303 pub connection_type: ConnectionType,
305 pub strength: f32,
307 pub created_at: DateTime<Utc>,
309 pub updated_at: DateTime<Utc>,
311 pub properties: HashMap<String, Value>,
313 pub bidirectional: bool,
315}
316
317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
319pub enum ConnectionType {
320 Semantic,
322 Temporal,
324 Causal,
326 Thematic,
328 Hierarchical,
330 Reference,
332 Custom(String),
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
340pub enum EvolutionTrigger {
341 NewMemoryAdded(MemoryId),
343 AccessPatternChanged(MemoryId),
345 TimeDecay,
347 UserFeedback(MemoryId, f32),
349 ConnectionStrengthChanged(ConnectionId),
351 BatchUpdate(Vec<MemoryId>),
353 SystemMaintenance,
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
361pub struct Update {
362 pub id: String,
364 pub memory_id: MemoryId,
366 pub update_type: UpdateType,
368 pub timestamp: DateTime<Utc>,
370 pub reason: Option<String>,
372 pub updater_info: Option<String>,
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
378pub enum UpdateType {
379 ImportanceAdjustment(f32),
381 ConnectionAdded(Connection),
383 ConnectionRemoved(ConnectionId),
385 AttributeUpdate(String, Value),
387 ContentUpdate(String),
389 TagUpdate(Vec<String>),
391 MetadataUpdate(HashMap<String, Value>),
393}
394
395#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
399pub struct Interaction {
400 pub id: String,
402 pub user_id: String,
404 pub session_id: Option<SessionId>,
406 pub query: String,
408 pub retrieved_memories: Vec<MemoryId>,
410 pub user_feedback: Option<f32>,
412 pub interaction_type: InteractionType,
414 pub timestamp: DateTime<Utc>,
416 pub response_time_ms: Option<u64>,
418 pub additional_info: HashMap<String, Value>,
420}
421
422#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
424pub enum InteractionType {
425 Query,
427 CreateMemory,
429 UpdateMemory,
431 DeleteMemory,
433 Feedback,
435 Browse,
437}
438
439#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
443pub struct Statistics {
444 pub total_memories: u64,
446 pub total_connections: u64,
448 pub average_importance: f32,
450 pub recently_accessed_count: u64,
452 pub system_start_time: DateTime<Utc>,
454 pub last_update_time: DateTime<Utc>,
456 pub user_stats: HashMap<String, UserStatistics>,
458 pub performance_metrics: PerformanceMetrics,
460}
461
462#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
464pub struct UserStatistics {
465 pub user_id: String,
467 pub memory_count: u64,
469 pub query_count: u64,
471 pub average_feedback: f32,
473 pub last_active: DateTime<Utc>,
475 pub preferred_tags: Vec<String>,
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
481pub struct PerformanceMetrics {
482 pub average_query_time_ms: f64,
484 pub average_creation_time_ms: f64,
486 pub cache_hit_rate: f32,
488 pub memory_usage_bytes: u64,
490 pub disk_usage_bytes: u64,
492 pub queries_per_second: f64,
494}
495
496impl Default for MemoryAttributes {
498 fn default() -> Self {
499 Self {
500 keywords: Vec::new(),
501 tags: Vec::new(),
502 context: String::new(),
503 importance: 0.5,
504 emotion: None,
505 source: None,
506 confidence: 1.0,
507 language: None,
508 custom_attributes: HashMap::new(),
509 }
510 }
511}
512
513impl Default for Context {
514 fn default() -> Self {
515 Self {
516 session_id: None,
517 current_topic: None,
518 recent_memories: Vec::new(),
519 user_preferences: HashMap::new(),
520 environment: HashMap::new(),
521 time_window: None,
522 priority: Priority::Normal,
523 }
524 }
525}
526
527impl Default for QueryWeights {
528 fn default() -> Self {
529 Self {
530 semantic_weight: 0.4,
531 temporal_weight: 0.2,
532 importance_weight: 0.2,
533 frequency_weight: 0.1,
534 personalization_weight: 0.1,
535 }
536 }
537}
538
539impl Default for Priority {
540 fn default() -> Self {
541 Self::Normal
542 }
543}
544
545impl Default for MemoryMetadata {
547 fn default() -> Self {
548 let now = Utc::now();
549 Self {
550 created_at: now,
551 updated_at: now,
552 access_count: 0,
553 last_accessed: now,
554 version: 1,
555 is_deleted: false,
556 deleted_at: None,
557 custom_metadata: HashMap::new(),
558 }
559 }
560}
561
562impl Default for Memory {
563 fn default() -> Self {
564 let _now = Utc::now();
565 Self {
566 id: Uuid::new_v4().to_string(),
567 content: String::new(),
568 memory_type: MemoryType::Knowledge,
569 embedding: Vec::new(),
570 attributes: MemoryAttributes::default(),
571 connections: MemoryConnections::default(),
572 metadata: MemoryMetadata::default(),
573 }
574 }
575}
576
577impl Memory {
578 pub fn new(
580 content: String,
581 memory_type: MemoryType,
582 embedding: Vec<f32>,
583 attributes: MemoryAttributes,
584 ) -> Self {
585 let now = Utc::now();
586 Self {
587 id: Uuid::new_v4().to_string(),
588 content,
589 memory_type,
590 embedding,
591 attributes,
592 connections: MemoryConnections::default(),
593 metadata: MemoryMetadata {
594 created_at: now,
595 updated_at: now,
596 access_count: 0,
597 last_accessed: now,
598 version: 1,
599 is_deleted: false,
600 deleted_at: None,
601 custom_metadata: HashMap::new(),
602 },
603 }
604 }
605
606 pub fn update_access(&mut self) {
608 self.metadata.access_count += 1;
609 self.metadata.last_accessed = Utc::now();
610 }
611
612 pub fn matches_filters(&self, filters: &QueryFilters) -> bool {
614 if let Some(required_tags) = &filters.tags {
616 if !required_tags
617 .iter()
618 .any(|tag| self.attributes.tags.contains(tag))
619 {
620 return false;
621 }
622 }
623
624 if let Some((start, end)) = filters.time_range {
626 if self.metadata.created_at < start || self.metadata.created_at > end {
627 return false;
628 }
629 }
630
631 if let Some(threshold) = filters.importance_threshold {
633 if self.attributes.importance < threshold {
634 return false;
635 }
636 }
637
638 if let Some(threshold) = filters.confidence_threshold {
640 if self.attributes.confidence < threshold {
641 return false;
642 }
643 }
644
645 if let Some(source) = &filters.source_filter {
647 if self.attributes.source.as_ref() != Some(source) {
648 return false;
649 }
650 }
651
652 if let Some(language) = &filters.language_filter {
654 if self.attributes.language.as_ref() != Some(language) {
655 return false;
656 }
657 }
658
659 if let Some(emotion) = &filters.emotion_filter {
661 if self.attributes.emotion.as_ref() != Some(emotion) {
662 return false;
663 }
664 }
665
666 true
667 }
668}
669
670impl Connection {
671 pub fn new(
673 from_memory: MemoryId,
674 to_memory: MemoryId,
675 connection_type: ConnectionType,
676 strength: f32,
677 ) -> Self {
678 let now = Utc::now();
679 Self {
680 id: Uuid::new_v4().to_string(),
681 from_memory,
682 to_memory,
683 connection_type,
684 strength: strength.clamp(0.0, 1.0),
685 created_at: now,
686 updated_at: now,
687 properties: HashMap::new(),
688 bidirectional: false,
689 }
690 }
691
692 pub fn update_strength(&mut self, new_strength: f32) {
694 self.strength = new_strength.clamp(0.0, 1.0);
695 self.updated_at = Utc::now();
696 }
697}
698
699#[cfg(test)]
700mod tests {
701 use super::*;
702
703 #[test]
704 fn test_memory_creation() {
705 let memory = Memory::new(
706 "Test content".to_string(),
707 MemoryType::Knowledge,
708 vec![0.1, 0.2, 0.3],
709 MemoryAttributes::default(),
710 );
711
712 assert_eq!(memory.content, "Test content");
713 assert_eq!(memory.embedding, vec![0.1, 0.2, 0.3]);
714 assert_eq!(memory.metadata.access_count, 0);
715 assert_eq!(memory.metadata.version, 1);
716 }
717
718 #[test]
719 fn test_connection_creation() {
720 let connection = Connection::new(
721 "mem1".to_string(),
722 "mem2".to_string(),
723 ConnectionType::Semantic,
724 0.8,
725 );
726
727 assert_eq!(connection.from_memory, "mem1");
728 assert_eq!(connection.to_memory, "mem2");
729 assert_eq!(connection.strength, 0.8);
730 assert!(!connection.bidirectional);
731 }
732
733 #[test]
734 fn test_memory_filters() {
735 let memory = Memory::new(
736 "Test content".to_string(),
737 MemoryType::Knowledge,
738 vec![0.1, 0.2, 0.3],
739 MemoryAttributes {
740 tags: vec!["test".to_string(), "example".to_string()],
741 importance: 0.7,
742 confidence: 0.9,
743 ..Default::default()
744 },
745 );
746
747 let filters = QueryFilters {
748 tags: Some(vec!["test".to_string()]),
749 importance_threshold: Some(0.5),
750 confidence_threshold: Some(0.8),
751 ..Default::default()
752 };
753
754 assert!(memory.matches_filters(&filters));
755
756 let strict_filters = QueryFilters {
757 importance_threshold: Some(0.9),
758 ..Default::default()
759 };
760
761 assert!(!memory.matches_filters(&strict_filters));
762 }
763
764 #[test]
765 fn test_connection_strength_clamping() {
766 let mut connection = Connection::new(
767 "mem1".to_string(),
768 "mem2".to_string(),
769 ConnectionType::Semantic,
770 1.5, );
772
773 assert_eq!(connection.strength, 1.0); connection.update_strength(-0.5); assert_eq!(connection.strength, 0.0); }
778}