use aidaemon_core::ChannelVisibility;
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use crate::error::{MemoryError, Result};
use crate::records::FactPrivacy;
use crate::sqlite::{ExactChannelIds, FACT_RESTATEMENT_MIN_SIMILARITY, memory_visible};
pub const MAX_FACT_VALUE_CHARS: usize = 4_000;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Provenance {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub excerpt: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Fact {
pub id: String,
pub scope: String,
pub category: String,
pub key: String,
pub value: String,
pub confidence: f32,
pub source: Provenance,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub superseded_at: Option<DateTime<Utc>>,
#[serde(default)]
pub recall_count: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_recalled_at: Option<DateTime<Utc>>,
}
impl Fact {
pub fn is_active(&self) -> bool {
self.superseded_at.is_none()
}
pub fn search_text(&self) -> String {
fact_search_text(&self.category, &self.key, &self.value)
}
}
pub fn fact_search_text(category: &str, key: &str, value: &str) -> String {
format!("{} {}: {}", category, key.replace(['_', '-'], " "), value)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NewFact {
pub scope: String,
pub category: String,
pub key: String,
pub value: String,
pub confidence: f32,
#[serde(default)]
pub source: Provenance,
}
impl NewFact {
pub fn new(
scope: impl Into<String>,
category: impl Into<String>,
key: impl Into<String>,
value: impl Into<String>,
) -> Self {
Self {
scope: scope.into(),
category: category.into(),
key: key.into(),
value: value.into(),
confidence: 1.0,
source: Provenance::default(),
}
}
pub fn confidence(mut self, confidence: f32) -> Self {
self.confidence = confidence;
self
}
pub fn source(mut self, source: Provenance) -> Self {
self.source = source;
self
}
pub fn normalized(mut self) -> Result<Self> {
self.scope = self.scope.trim().to_string();
self.category = normalize_category(&self.category);
self.key = normalize_key(&self.key);
self.value = self.value.trim().to_string();
if self.scope.is_empty() {
return Err(MemoryError::Invalid("scope is empty".into()));
}
if self.category.is_empty() || self.key.is_empty() || self.value.is_empty() {
return Err(MemoryError::Invalid(
"category, key and value must be non-empty".into(),
));
}
if self.value.chars().count() > MAX_FACT_VALUE_CHARS {
return Err(MemoryError::Invalid(format!(
"value longer than {MAX_FACT_VALUE_CHARS} characters"
)));
}
self.confidence = if self.confidence.is_finite() {
self.confidence.clamp(0.0, 1.0)
} else {
0.5
};
self.source.excerpt = self
.source
.excerpt
.map(|e| truncate_chars(e.trim(), 500))
.filter(|e| !e.is_empty());
Ok(self)
}
}
pub fn normalize_category(category: &str) -> String {
category.trim().to_lowercase()
}
pub fn normalize_key(key: &str) -> String {
let mut out = String::with_capacity(key.len());
for c in key.trim().to_lowercase().chars() {
if c.is_whitespace() || c == '-' || c == '.' {
if !out.ends_with('_') {
out.push('_');
}
} else {
out.push(c);
}
}
out.trim_matches('_').to_string()
}
pub fn same_value(a: &str, b: &str) -> bool {
let canon = |s: &str| {
s.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase()
};
canon(a) == canon(b)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum UpsertOutcome {
Inserted { id: String },
Reinforced { id: String },
Superseded {
id: String,
previous_id: String,
previous_value: String,
},
}
impl UpsertOutcome {
pub fn id(&self) -> &str {
match self {
Self::Inserted { id } | Self::Reinforced { id } | Self::Superseded { id, .. } => id,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Episode {
pub id: String,
pub scope: String,
pub session_id: String,
pub summary: String,
#[serde(default)]
pub topics: Vec<String>,
pub importance: f32,
pub created_at: DateTime<Utc>,
#[serde(default)]
pub recall_count: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_recalled_at: Option<DateTime<Utc>>,
}
impl Episode {
pub fn search_text(&self) -> String {
episode_search_text(&self.summary, &self.topics)
}
}
pub fn episode_search_text(summary: &str, topics: &[String]) -> String {
if topics.is_empty() {
summary.to_string()
} else {
format!("{summary} Topics: {}", topics.join(", "))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NewEpisode {
pub scope: String,
pub session_id: String,
pub summary: String,
#[serde(default)]
pub topics: Vec<String>,
pub importance: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct StoredEmbedding {
pub model: String,
pub vector: Vec<f32>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MergeConfig {
pub semantic_threshold: f32,
pub text_threshold: f32,
}
impl Default for MergeConfig {
fn default() -> Self {
Self {
semantic_threshold: FACT_RESTATEMENT_MIN_SIMILARITY,
text_threshold: 0.9,
}
}
}
impl MergeConfig {
pub fn disabled() -> Self {
Self {
semantic_threshold: 2.0,
text_threshold: 2.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecordKind {
Fact,
Episode,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaleEmbedding {
pub kind: RecordKind,
pub id: String,
pub text: String,
pub model: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReembedCursor {
pub kind: RecordKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub after_id: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReembedReport {
pub processed: usize,
pub updated: usize,
pub skipped: usize,
pub next: Option<ReembedCursor>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FactRecord {
pub fact: Fact,
pub embedding: Option<StoredEmbedding>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EpisodeRecord {
pub episode: Episode,
pub embedding: Option<StoredEmbedding>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FactAccess {
pub privacy: FactPrivacy,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_id: Option<String>,
}
impl Default for FactAccess {
fn default() -> Self {
Self::private()
}
}
impl FactAccess {
pub fn private() -> Self {
Self {
privacy: FactPrivacy::Private,
channel_id: None,
}
}
pub fn global() -> Self {
Self {
privacy: FactPrivacy::Global,
channel_id: None,
}
}
pub fn channel(channel_id: impl Into<String>) -> Self {
Self {
privacy: FactPrivacy::Channel,
channel_id: Some(channel_id.into()),
}
}
pub fn from_stored(privacy: &str, channel_id: Option<String>) -> Self {
match (privacy, channel_id) {
("global", _) => Self::global(),
("channel", Some(channel)) => Self::channel(channel),
_ => Self::private(),
}
}
pub fn narrowest(&self, other: &Self) -> Self {
match (self.privacy, other.privacy) {
(FactPrivacy::Private, _) | (_, FactPrivacy::Private) => Self::private(),
(FactPrivacy::Global, _) => other.clone(),
(_, FactPrivacy::Global) => self.clone(),
(FactPrivacy::Channel, FactPrivacy::Channel) => {
if self.channel_id == other.channel_id {
self.clone()
} else {
Self::private()
}
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecallAudience {
pub visibility: ChannelVisibility,
pub channel_id: Option<String>,
pub requester_is_owner: bool,
}
impl RecallAudience {
pub fn new(
visibility: ChannelVisibility,
channel_id: Option<String>,
requester_is_owner: bool,
) -> Self {
Self {
visibility,
channel_id,
requester_is_owner,
}
}
pub fn owner() -> Self {
Self::new(ChannelVisibility::Private, None, true)
}
pub fn from_stored(
visibility: &str,
channel_id: Option<String>,
requester_is_owner: bool,
) -> Self {
let visibility = match visibility {
"private" => ChannelVisibility::Private,
"private_group" => ChannelVisibility::PrivateGroup,
"public" => ChannelVisibility::Public,
"internal" => ChannelVisibility::Internal,
_ => ChannelVisibility::PublicExternal,
};
Self::new(visibility, channel_id, requester_is_owner)
}
pub fn may_see(&self, access: Option<&FactAccess>) -> bool {
let private = FactAccess::private();
let access = access.unwrap_or(&private);
memory_visible(
&ExactChannelIds,
access.privacy,
access.channel_id.as_deref(),
self.channel_id.as_deref(),
self.visibility,
self.requester_is_owner,
)
}
pub fn sees_everything(&self) -> bool {
self.may_see(None)
}
pub fn access_for_writes(&self) -> FactAccess {
match (self.visibility, &self.channel_id) {
(ChannelVisibility::PrivateGroup | ChannelVisibility::Public, Some(channel_id)) => {
FactAccess::channel(channel_id.clone())
}
_ => FactAccess::private(),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Signals {
pub semantic: f32,
pub lexical: f32,
pub graph: f32,
pub freshness: f32,
pub confidence: f32,
pub provenance: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Score {
pub value: f32,
pub signals: Signals,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScoredFact {
pub fact: Fact,
pub score: f32,
pub signals: Signals,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScoredEpisode {
pub episode: Episode,
pub score: f32,
pub signals: Signals,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryStats {
pub active_facts: u64,
pub superseded_facts: u64,
pub episodes: u64,
pub scopes: u64,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DecayReport {
pub facts_decayed: u64,
pub episodes_decayed: u64,
pub superseded_deleted: u64,
pub episodes_deleted: u64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RetentionConfig {
pub fact_recall_decay_after: Option<chrono::Duration>,
pub episode_recall_decay_after: Option<chrono::Duration>,
pub superseded_retention: Option<chrono::Duration>,
pub episode_retention: Option<chrono::Duration>,
}
impl Default for RetentionConfig {
fn default() -> Self {
Self {
fact_recall_decay_after: Some(chrono::Duration::days(14)),
episode_recall_decay_after: Some(chrono::Duration::days(30)),
superseded_retention: Some(chrono::Duration::days(90)),
episode_retention: Some(chrono::Duration::days(365)),
}
}
}
pub(crate) fn ts(t: DateTime<Utc>) -> String {
t.to_rfc3339_opts(SecondsFormat::Micros, true)
}
pub(crate) fn parse_ts(s: &str) -> Option<DateTime<Utc>> {
DateTime::parse_from_rfc3339(s)
.ok()
.map(|t| t.with_timezone(&Utc))
}
pub(crate) fn truncate_chars(s: &str, max: usize) -> String {
match s.char_indices().nth(max) {
Some((at, _)) => s[..at].to_string(),
None => s.to_string(),
}
}
pub(crate) fn new_id() -> String {
uuid::Uuid::new_v4().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_and_categories_are_canonical() {
assert_eq!(normalize_key(" Favorite Color "), "favorite_color");
assert_eq!(normalize_key("dog-name"), "dog_name");
assert_eq!(normalize_category(" Preference "), "preference");
assert!(same_value("Dark Mode", "dark mode"));
assert!(!same_value("dark mode", "light mode"));
}
#[test]
fn stored_access_fails_closed() {
assert_eq!(
FactAccess::from_stored("global", None),
FactAccess::global()
);
assert_eq!(
FactAccess::from_stored("channel", Some("c1".into())),
FactAccess::channel("c1")
);
for unreadable in ["", "GLOBAL", "public", "everyone"] {
assert_eq!(
FactAccess::from_stored(unreadable, None),
FactAccess::private(),
"{unreadable}"
);
}
assert_eq!(
FactAccess::from_stored("channel", None),
FactAccess::private()
);
}
#[test]
fn merged_access_never_widens() {
let (private, global) = (FactAccess::private(), FactAccess::global());
let (one, two) = (FactAccess::channel("c1"), FactAccess::channel("c2"));
assert_eq!(global.narrowest(&global), global);
assert_eq!(global.narrowest(&one), one);
assert_eq!(one.narrowest(&global), one);
assert_eq!(one.narrowest(&one), one);
assert_eq!(one.narrowest(&two), private);
assert_eq!(private.narrowest(&global), private);
assert_eq!(global.narrowest(&private), private);
}
#[test]
fn audience_visibility_matches_the_daemon_rule() {
use ChannelVisibility as V;
let group = RecallAudience::new(V::PrivateGroup, Some("c1".into()), true);
assert!(!group.may_see(Some(&FactAccess::private())));
assert!(group.may_see(Some(&FactAccess::global())));
assert!(group.may_see(Some(&FactAccess::channel("c1"))));
assert!(!group.may_see(Some(&FactAccess::channel("c2"))));
assert!(!group.may_see(None), "an unknown level is private");
let public = RecallAudience::new(V::Public, Some("c1".into()), true);
assert!(!public.may_see(Some(&FactAccess::private())));
assert!(!public.may_see(Some(&FactAccess::global())));
let external = RecallAudience::new(V::PublicExternal, Some("c1".into()), true);
assert!(!external.may_see(Some(&FactAccess::global())));
assert!(!external.may_see(Some(&FactAccess::channel("c1"))));
let guest_dm = RecallAudience::new(V::Private, None, false);
assert!(!guest_dm.may_see(Some(&FactAccess::private())));
assert!(guest_dm.may_see(Some(&FactAccess::global())));
assert!(RecallAudience::owner().sees_everything());
assert!(RecallAudience::new(V::Internal, None, true).sees_everything());
assert!(!group.sees_everything());
}
#[test]
fn unknown_visibility_text_is_the_most_restrictive() {
for unknown in ["", "PUBLIC", "dm", "internal "] {
let audience = RecallAudience::from_stored(unknown, None, true);
assert_eq!(audience.visibility, ChannelVisibility::PublicExternal);
assert!(!audience.may_see(Some(&FactAccess::global())));
}
assert_eq!(
RecallAudience::from_stored("private_group", None, true).visibility,
ChannelVisibility::PrivateGroup
);
}
#[test]
fn writes_stay_in_the_conversation_they_came_from() {
use ChannelVisibility as V;
let in_channel = |v| RecallAudience::new(v, Some("c1".into()), true).access_for_writes();
assert_eq!(in_channel(V::PrivateGroup), FactAccess::channel("c1"));
assert_eq!(in_channel(V::Public), FactAccess::channel("c1"));
assert_eq!(in_channel(V::Private), FactAccess::private());
assert_eq!(in_channel(V::Internal), FactAccess::private());
assert_eq!(in_channel(V::PublicExternal), FactAccess::private());
assert_eq!(
RecallAudience::new(V::Public, None, true).access_for_writes(),
FactAccess::private()
);
}
#[test]
fn invalid_facts_are_rejected() {
assert!(NewFact::new("s", "user", "", "x").normalized().is_err());
assert!(NewFact::new("", "user", "k", "x").normalized().is_err());
let f = NewFact::new("s", "user", "k", "x")
.confidence(7.0)
.normalized()
.unwrap();
assert_eq!(f.confidence, 1.0);
}
}