1use aidaemon_core::ChannelVisibility;
4use chrono::{DateTime, SecondsFormat, Utc};
5use serde::{Deserialize, Serialize};
6
7use crate::error::{MemoryError, Result};
8use crate::records::FactPrivacy;
9use crate::sqlite::{ExactChannelIds, FACT_RESTATEMENT_MIN_SIMILARITY, memory_visible};
10
11pub const MAX_FACT_VALUE_CHARS: usize = 4_000;
13
14#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
17pub struct Provenance {
18 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub run_id: Option<String>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
23 pub session_id: Option<String>,
24 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub excerpt: Option<String>,
28}
29
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct Fact {
36 pub id: String,
37 pub scope: String,
40 pub category: String,
41 pub key: String,
42 pub value: String,
43 pub confidence: f32,
45 pub source: Provenance,
46 pub created_at: DateTime<Utc>,
47 pub updated_at: DateTime<Utc>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub superseded_at: Option<DateTime<Utc>>,
50 #[serde(default)]
51 pub recall_count: u32,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub last_recalled_at: Option<DateTime<Utc>>,
54}
55
56impl Fact {
57 pub fn is_active(&self) -> bool {
58 self.superseded_at.is_none()
59 }
60
61 pub fn search_text(&self) -> String {
64 fact_search_text(&self.category, &self.key, &self.value)
65 }
66}
67
68pub fn fact_search_text(category: &str, key: &str, value: &str) -> String {
71 format!("{} {}: {}", category, key.replace(['_', '-'], " "), value)
72}
73
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77pub struct NewFact {
78 pub scope: String,
79 pub category: String,
80 pub key: String,
81 pub value: String,
82 pub confidence: f32,
83 #[serde(default)]
84 pub source: Provenance,
85}
86
87impl NewFact {
88 pub fn new(
89 scope: impl Into<String>,
90 category: impl Into<String>,
91 key: impl Into<String>,
92 value: impl Into<String>,
93 ) -> Self {
94 Self {
95 scope: scope.into(),
96 category: category.into(),
97 key: key.into(),
98 value: value.into(),
99 confidence: 1.0,
100 source: Provenance::default(),
101 }
102 }
103
104 pub fn confidence(mut self, confidence: f32) -> Self {
105 self.confidence = confidence;
106 self
107 }
108
109 pub fn source(mut self, source: Provenance) -> Self {
110 self.source = source;
111 self
112 }
113
114 pub fn normalized(mut self) -> Result<Self> {
117 self.scope = self.scope.trim().to_string();
118 self.category = normalize_category(&self.category);
119 self.key = normalize_key(&self.key);
120 self.value = self.value.trim().to_string();
121 if self.scope.is_empty() {
122 return Err(MemoryError::Invalid("scope is empty".into()));
123 }
124 if self.category.is_empty() || self.key.is_empty() || self.value.is_empty() {
125 return Err(MemoryError::Invalid(
126 "category, key and value must be non-empty".into(),
127 ));
128 }
129 if self.value.chars().count() > MAX_FACT_VALUE_CHARS {
130 return Err(MemoryError::Invalid(format!(
131 "value longer than {MAX_FACT_VALUE_CHARS} characters"
132 )));
133 }
134 self.confidence = if self.confidence.is_finite() {
135 self.confidence.clamp(0.0, 1.0)
136 } else {
137 0.5
138 };
139 self.source.excerpt = self
140 .source
141 .excerpt
142 .map(|e| truncate_chars(e.trim(), 500))
143 .filter(|e| !e.is_empty());
144 Ok(self)
145 }
146}
147
148pub fn normalize_category(category: &str) -> String {
150 category.trim().to_lowercase()
151}
152
153pub fn normalize_key(key: &str) -> String {
155 let mut out = String::with_capacity(key.len());
156 for c in key.trim().to_lowercase().chars() {
157 if c.is_whitespace() || c == '-' || c == '.' {
158 if !out.ends_with('_') {
159 out.push('_');
160 }
161 } else {
162 out.push(c);
163 }
164 }
165 out.trim_matches('_').to_string()
166}
167
168pub fn same_value(a: &str, b: &str) -> bool {
171 let canon = |s: &str| {
172 s.split_whitespace()
173 .collect::<Vec<_>>()
174 .join(" ")
175 .to_lowercase()
176 };
177 canon(a) == canon(b)
178}
179
180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
182#[serde(rename_all = "snake_case", tag = "kind")]
183pub enum UpsertOutcome {
184 Inserted { id: String },
186 Reinforced { id: String },
189 Superseded {
192 id: String,
193 previous_id: String,
194 previous_value: String,
195 },
196}
197
198impl UpsertOutcome {
199 pub fn id(&self) -> &str {
201 match self {
202 Self::Inserted { id } | Self::Reinforced { id } | Self::Superseded { id, .. } => id,
203 }
204 }
205}
206
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
209pub struct Episode {
210 pub id: String,
211 pub scope: String,
212 pub session_id: String,
213 pub summary: String,
214 #[serde(default)]
215 pub topics: Vec<String>,
216 pub importance: f32,
218 pub created_at: DateTime<Utc>,
219 #[serde(default)]
220 pub recall_count: u32,
221 #[serde(default, skip_serializing_if = "Option::is_none")]
222 pub last_recalled_at: Option<DateTime<Utc>>,
223}
224
225impl Episode {
226 pub fn search_text(&self) -> String {
228 episode_search_text(&self.summary, &self.topics)
229 }
230}
231
232pub fn episode_search_text(summary: &str, topics: &[String]) -> String {
233 if topics.is_empty() {
234 summary.to_string()
235 } else {
236 format!("{summary} Topics: {}", topics.join(", "))
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242pub struct NewEpisode {
243 pub scope: String,
244 pub session_id: String,
245 pub summary: String,
246 #[serde(default)]
247 pub topics: Vec<String>,
248 pub importance: f32,
249}
250
251#[derive(Debug, Clone, PartialEq)]
254pub struct StoredEmbedding {
255 pub model: String,
256 pub vector: Vec<f32>,
257}
258
259#[derive(Debug, Clone, Copy, PartialEq)]
262pub struct MergeConfig {
263 pub semantic_threshold: f32,
266 pub text_threshold: f32,
268}
269
270impl Default for MergeConfig {
271 fn default() -> Self {
272 Self {
273 semantic_threshold: FACT_RESTATEMENT_MIN_SIMILARITY,
274 text_threshold: 0.9,
275 }
276 }
277}
278
279impl MergeConfig {
280 pub fn disabled() -> Self {
282 Self {
283 semantic_threshold: 2.0,
284 text_threshold: 2.0,
285 }
286 }
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(rename_all = "snake_case")]
292pub enum RecordKind {
293 Fact,
294 Episode,
295}
296
297#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct StaleEmbedding {
300 pub kind: RecordKind,
301 pub id: String,
302 pub text: String,
304 pub model: Option<String>,
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310pub struct ReembedCursor {
311 pub kind: RecordKind,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub after_id: Option<String>,
314}
315
316#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
318pub struct ReembedReport {
319 pub processed: usize,
321 pub updated: usize,
322 pub skipped: usize,
325 pub next: Option<ReembedCursor>,
327}
328
329#[derive(Debug, Clone, PartialEq)]
331pub struct FactRecord {
332 pub fact: Fact,
333 pub embedding: Option<StoredEmbedding>,
334}
335
336#[derive(Debug, Clone, PartialEq)]
338pub struct EpisodeRecord {
339 pub episode: Episode,
340 pub embedding: Option<StoredEmbedding>,
341}
342
343#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347pub struct FactAccess {
348 pub privacy: FactPrivacy,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
351 pub channel_id: Option<String>,
352}
353
354impl Default for FactAccess {
355 fn default() -> Self {
356 Self::private()
357 }
358}
359
360impl FactAccess {
361 pub fn private() -> Self {
363 Self {
364 privacy: FactPrivacy::Private,
365 channel_id: None,
366 }
367 }
368
369 pub fn global() -> Self {
371 Self {
372 privacy: FactPrivacy::Global,
373 channel_id: None,
374 }
375 }
376
377 pub fn channel(channel_id: impl Into<String>) -> Self {
379 Self {
380 privacy: FactPrivacy::Channel,
381 channel_id: Some(channel_id.into()),
382 }
383 }
384
385 pub fn from_stored(privacy: &str, channel_id: Option<String>) -> Self {
388 match (privacy, channel_id) {
389 ("global", _) => Self::global(),
390 ("channel", Some(channel)) => Self::channel(channel),
391 _ => Self::private(),
392 }
393 }
394
395 pub fn narrowest(&self, other: &Self) -> Self {
398 match (self.privacy, other.privacy) {
399 (FactPrivacy::Private, _) | (_, FactPrivacy::Private) => Self::private(),
400 (FactPrivacy::Global, _) => other.clone(),
401 (_, FactPrivacy::Global) => self.clone(),
402 (FactPrivacy::Channel, FactPrivacy::Channel) => {
403 if self.channel_id == other.channel_id {
404 self.clone()
405 } else {
406 Self::private()
407 }
408 }
409 }
410 }
411}
412
413#[derive(Debug, Clone, PartialEq, Eq)]
416pub struct RecallAudience {
417 pub visibility: ChannelVisibility,
418 pub channel_id: Option<String>,
419 pub requester_is_owner: bool,
420}
421
422impl RecallAudience {
423 pub fn new(
424 visibility: ChannelVisibility,
425 channel_id: Option<String>,
426 requester_is_owner: bool,
427 ) -> Self {
428 Self {
429 visibility,
430 channel_id,
431 requester_is_owner,
432 }
433 }
434
435 pub fn owner() -> Self {
437 Self::new(ChannelVisibility::Private, None, true)
438 }
439
440 pub fn from_stored(
444 visibility: &str,
445 channel_id: Option<String>,
446 requester_is_owner: bool,
447 ) -> Self {
448 let visibility = match visibility {
449 "private" => ChannelVisibility::Private,
450 "private_group" => ChannelVisibility::PrivateGroup,
451 "public" => ChannelVisibility::Public,
452 "internal" => ChannelVisibility::Internal,
453 _ => ChannelVisibility::PublicExternal,
454 };
455 Self::new(visibility, channel_id, requester_is_owner)
456 }
457
458 pub fn may_see(&self, access: Option<&FactAccess>) -> bool {
461 let private = FactAccess::private();
462 let access = access.unwrap_or(&private);
463 memory_visible(
464 &ExactChannelIds,
465 access.privacy,
466 access.channel_id.as_deref(),
467 self.channel_id.as_deref(),
468 self.visibility,
469 self.requester_is_owner,
470 )
471 }
472
473 pub fn sees_everything(&self) -> bool {
475 self.may_see(None)
476 }
477
478 pub fn access_for_writes(&self) -> FactAccess {
483 match (self.visibility, &self.channel_id) {
484 (ChannelVisibility::PrivateGroup | ChannelVisibility::Public, Some(channel_id)) => {
485 FactAccess::channel(channel_id.clone())
486 }
487 _ => FactAccess::private(),
488 }
489 }
490}
491
492#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
495pub struct Signals {
496 pub semantic: f32,
497 pub lexical: f32,
498 pub graph: f32,
499 pub freshness: f32,
500 pub confidence: f32,
501 pub provenance: f32,
502}
503
504#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
506pub struct Score {
507 pub value: f32,
508 pub signals: Signals,
509}
510
511#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
513pub struct ScoredFact {
514 pub fact: Fact,
515 pub score: f32,
516 pub signals: Signals,
517}
518
519#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
521pub struct ScoredEpisode {
522 pub episode: Episode,
523 pub score: f32,
524 pub signals: Signals,
525}
526
527#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
529pub struct MemoryStats {
530 pub active_facts: u64,
531 pub superseded_facts: u64,
532 pub episodes: u64,
533 pub scopes: u64,
534}
535
536#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
538pub struct DecayReport {
539 pub facts_decayed: u64,
541 pub episodes_decayed: u64,
542 pub superseded_deleted: u64,
544 pub episodes_deleted: u64,
546}
547
548#[derive(Debug, Clone, Copy, PartialEq)]
551pub struct RetentionConfig {
552 pub fact_recall_decay_after: Option<chrono::Duration>,
555 pub episode_recall_decay_after: Option<chrono::Duration>,
558 pub superseded_retention: Option<chrono::Duration>,
560 pub episode_retention: Option<chrono::Duration>,
563}
564
565impl Default for RetentionConfig {
566 fn default() -> Self {
567 Self {
568 fact_recall_decay_after: Some(chrono::Duration::days(14)),
569 episode_recall_decay_after: Some(chrono::Duration::days(30)),
570 superseded_retention: Some(chrono::Duration::days(90)),
571 episode_retention: Some(chrono::Duration::days(365)),
572 }
573 }
574}
575
576pub(crate) fn ts(t: DateTime<Utc>) -> String {
578 t.to_rfc3339_opts(SecondsFormat::Micros, true)
579}
580
581pub(crate) fn parse_ts(s: &str) -> Option<DateTime<Utc>> {
582 DateTime::parse_from_rfc3339(s)
583 .ok()
584 .map(|t| t.with_timezone(&Utc))
585}
586
587pub(crate) fn truncate_chars(s: &str, max: usize) -> String {
589 match s.char_indices().nth(max) {
590 Some((at, _)) => s[..at].to_string(),
591 None => s.to_string(),
592 }
593}
594
595pub(crate) fn new_id() -> String {
596 uuid::Uuid::new_v4().to_string()
597}
598
599#[cfg(test)]
600mod tests {
601 use super::*;
602
603 #[test]
604 fn keys_and_categories_are_canonical() {
605 assert_eq!(normalize_key(" Favorite Color "), "favorite_color");
606 assert_eq!(normalize_key("dog-name"), "dog_name");
607 assert_eq!(normalize_category(" Preference "), "preference");
608 assert!(same_value("Dark Mode", "dark mode"));
609 assert!(!same_value("dark mode", "light mode"));
610 }
611
612 #[test]
613 fn stored_access_fails_closed() {
614 assert_eq!(
615 FactAccess::from_stored("global", None),
616 FactAccess::global()
617 );
618 assert_eq!(
619 FactAccess::from_stored("channel", Some("c1".into())),
620 FactAccess::channel("c1")
621 );
622 for unreadable in ["", "GLOBAL", "public", "everyone"] {
623 assert_eq!(
624 FactAccess::from_stored(unreadable, None),
625 FactAccess::private(),
626 "{unreadable}"
627 );
628 }
629 assert_eq!(
631 FactAccess::from_stored("channel", None),
632 FactAccess::private()
633 );
634 }
635
636 #[test]
637 fn merged_access_never_widens() {
638 let (private, global) = (FactAccess::private(), FactAccess::global());
639 let (one, two) = (FactAccess::channel("c1"), FactAccess::channel("c2"));
640 assert_eq!(global.narrowest(&global), global);
641 assert_eq!(global.narrowest(&one), one);
642 assert_eq!(one.narrowest(&global), one);
643 assert_eq!(one.narrowest(&one), one);
644 assert_eq!(one.narrowest(&two), private);
645 assert_eq!(private.narrowest(&global), private);
646 assert_eq!(global.narrowest(&private), private);
647 }
648
649 #[test]
650 fn audience_visibility_matches_the_daemon_rule() {
651 use ChannelVisibility as V;
652 let group = RecallAudience::new(V::PrivateGroup, Some("c1".into()), true);
653 assert!(!group.may_see(Some(&FactAccess::private())));
654 assert!(group.may_see(Some(&FactAccess::global())));
655 assert!(group.may_see(Some(&FactAccess::channel("c1"))));
656 assert!(!group.may_see(Some(&FactAccess::channel("c2"))));
657 assert!(!group.may_see(None), "an unknown level is private");
658
659 let public = RecallAudience::new(V::Public, Some("c1".into()), true);
660 assert!(!public.may_see(Some(&FactAccess::private())));
661 assert!(!public.may_see(Some(&FactAccess::global())));
662
663 let external = RecallAudience::new(V::PublicExternal, Some("c1".into()), true);
664 assert!(!external.may_see(Some(&FactAccess::global())));
665 assert!(!external.may_see(Some(&FactAccess::channel("c1"))));
666
667 let guest_dm = RecallAudience::new(V::Private, None, false);
668 assert!(!guest_dm.may_see(Some(&FactAccess::private())));
669 assert!(guest_dm.may_see(Some(&FactAccess::global())));
670
671 assert!(RecallAudience::owner().sees_everything());
672 assert!(RecallAudience::new(V::Internal, None, true).sees_everything());
673 assert!(!group.sees_everything());
674 }
675
676 #[test]
677 fn unknown_visibility_text_is_the_most_restrictive() {
678 for unknown in ["", "PUBLIC", "dm", "internal "] {
679 let audience = RecallAudience::from_stored(unknown, None, true);
680 assert_eq!(audience.visibility, ChannelVisibility::PublicExternal);
681 assert!(!audience.may_see(Some(&FactAccess::global())));
682 }
683 assert_eq!(
684 RecallAudience::from_stored("private_group", None, true).visibility,
685 ChannelVisibility::PrivateGroup
686 );
687 }
688
689 #[test]
690 fn writes_stay_in_the_conversation_they_came_from() {
691 use ChannelVisibility as V;
692 let in_channel = |v| RecallAudience::new(v, Some("c1".into()), true).access_for_writes();
693 assert_eq!(in_channel(V::PrivateGroup), FactAccess::channel("c1"));
694 assert_eq!(in_channel(V::Public), FactAccess::channel("c1"));
695 assert_eq!(in_channel(V::Private), FactAccess::private());
696 assert_eq!(in_channel(V::Internal), FactAccess::private());
697 assert_eq!(in_channel(V::PublicExternal), FactAccess::private());
698 assert_eq!(
699 RecallAudience::new(V::Public, None, true).access_for_writes(),
700 FactAccess::private()
701 );
702 }
703
704 #[test]
705 fn invalid_facts_are_rejected() {
706 assert!(NewFact::new("s", "user", "", "x").normalized().is_err());
707 assert!(NewFact::new("", "user", "k", "x").normalized().is_err());
708 let f = NewFact::new("s", "user", "k", "x")
709 .confidence(7.0)
710 .normalized()
711 .unwrap();
712 assert_eq!(f.confidence, 1.0);
713 }
714}