Skip to main content

use_ai_memory/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7pub mod prelude {
8    pub use crate::{
9        AiMemoryConfidence, AiMemoryConflictKind, AiMemoryError, AiMemoryId, AiMemoryKind,
10        AiMemoryOperationKind, AiMemoryRetentionKind, AiMemoryScope, AiMemorySensitivity,
11        AiMemorySourceKind, AiMemoryStatus,
12    };
13}
14
15#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
16pub struct AiMemoryId(String);
17
18impl AiMemoryId {
19    pub fn new(value: impl AsRef<str>) -> Result<Self, AiMemoryError> {
20        non_empty_text(value).map(Self)
21    }
22
23    pub fn as_str(&self) -> &str {
24        &self.0
25    }
26
27    pub fn value(&self) -> &str {
28        self.as_str()
29    }
30
31    pub fn into_string(self) -> String {
32        self.0
33    }
34}
35
36impl AsRef<str> for AiMemoryId {
37    fn as_ref(&self) -> &str {
38        self.as_str()
39    }
40}
41
42impl fmt::Display for AiMemoryId {
43    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
44        formatter.write_str(self.as_str())
45    }
46}
47
48impl FromStr for AiMemoryId {
49    type Err = AiMemoryError;
50
51    fn from_str(value: &str) -> Result<Self, Self::Err> {
52        Self::new(value)
53    }
54}
55
56impl TryFrom<&str> for AiMemoryId {
57    type Error = AiMemoryError;
58
59    fn try_from(value: &str) -> Result<Self, Self::Error> {
60        Self::new(value)
61    }
62}
63
64#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
65pub struct AiMemoryConfidence(f64);
66
67impl AiMemoryConfidence {
68    pub fn new(value: f64) -> Result<Self, AiMemoryError> {
69        if !value.is_finite() {
70            return Err(AiMemoryError::NonFinite);
71        }
72        if !(0.0..=1.0).contains(&value) {
73            return Err(AiMemoryError::OutOfRange);
74        }
75        Ok(Self(value))
76    }
77
78    pub const fn value(self) -> f64 {
79        self.0
80    }
81}
82
83macro_rules! memory_enum {
84    ($name:ident { $($variant:ident => $label:literal),+ $(,)? }) => {
85        #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
86        pub enum $name {
87            $($variant),+
88        }
89
90        impl $name {
91            pub const ALL: &'static [Self] = &[$(Self::$variant),+];
92
93            pub const fn as_str(self) -> &'static str {
94                match self {
95                    $(Self::$variant => $label),+
96                }
97            }
98        }
99
100        impl fmt::Display for $name {
101            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
102                formatter.write_str(self.as_str())
103            }
104        }
105
106        impl FromStr for $name {
107            type Err = AiMemoryError;
108
109            fn from_str(value: &str) -> Result<Self, Self::Err> {
110                match normalized_label(value)?.as_str() {
111                    $($label => Ok(Self::$variant),)+
112                    _ => Err(AiMemoryError::UnknownLabel),
113                }
114            }
115        }
116    };
117}
118
119memory_enum!(AiMemoryKind {
120    Preference => "preference",
121    Fact => "fact",
122    Instruction => "instruction",
123    Summary => "summary",
124    Skill => "skill",
125    Relationship => "relationship",
126    Project => "project",
127    Workflow => "workflow",
128    Correction => "correction",
129    Custom => "custom",
130});
131
132memory_enum!(AiMemoryScope {
133    Session => "session",
134    User => "user",
135    Project => "project",
136    Organization => "organization",
137    Global => "global",
138    Tool => "tool",
139    Agent => "agent",
140});
141
142memory_enum!(AiMemoryStatus {
143    Active => "active",
144    Superseded => "superseded",
145    Deleted => "deleted",
146    Archived => "archived",
147    PendingReview => "pending-review",
148});
149
150memory_enum!(AiMemorySourceKind {
151    UserProvided => "user-provided",
152    Inferred => "inferred",
153    Imported => "imported",
154    ToolGenerated => "tool-generated",
155    SystemGenerated => "system-generated",
156    Unknown => "unknown",
157});
158
159memory_enum!(AiMemoryRetentionKind {
160    Ephemeral => "ephemeral",
161    Session => "session",
162    LongTerm => "long-term",
163    UntilRevoked => "until-revoked",
164    PolicyControlled => "policy-controlled",
165});
166
167memory_enum!(AiMemorySensitivity {
168    Public => "public",
169    Internal => "internal",
170    Private => "private",
171    Sensitive => "sensitive",
172    Restricted => "restricted",
173    Unknown => "unknown",
174});
175
176memory_enum!(AiMemoryOperationKind {
177    Create => "create",
178    Read => "read",
179    Update => "update",
180    Delete => "delete",
181    Merge => "merge",
182    Suppress => "suppress",
183    Forget => "forget",
184});
185
186memory_enum!(AiMemoryConflictKind {
187    Duplicate => "duplicate",
188    Contradiction => "contradiction",
189    Stale => "stale",
190    ScopeMismatch => "scope-mismatch",
191    SensitivityMismatch => "sensitivity-mismatch",
192    Unknown => "unknown",
193});
194
195#[derive(Clone, Copy, Debug, Eq, PartialEq)]
196pub enum AiMemoryError {
197    Empty,
198    NonFinite,
199    OutOfRange,
200    UnknownLabel,
201}
202
203impl fmt::Display for AiMemoryError {
204    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
205        match self {
206            Self::Empty => formatter.write_str("AI memory metadata text cannot be empty"),
207            Self::NonFinite => formatter.write_str("AI memory confidence must be finite"),
208            Self::OutOfRange => formatter.write_str("AI memory confidence must be in 0.0..=1.0"),
209            Self::UnknownLabel => formatter.write_str("unknown AI memory metadata label"),
210        }
211    }
212}
213
214impl Error for AiMemoryError {}
215
216fn non_empty_text(value: impl AsRef<str>) -> Result<String, AiMemoryError> {
217    let trimmed = value.as_ref().trim();
218    if trimmed.is_empty() {
219        Err(AiMemoryError::Empty)
220    } else {
221        Ok(trimmed.to_string())
222    }
223}
224
225fn normalized_label(value: &str) -> Result<String, AiMemoryError> {
226    let trimmed = value.trim();
227    if trimmed.is_empty() {
228        Err(AiMemoryError::Empty)
229    } else {
230        Ok(trimmed.to_ascii_lowercase().replace(['_', ' '], "-"))
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::{
237        AiMemoryConfidence, AiMemoryConflictKind, AiMemoryError, AiMemoryId, AiMemoryKind,
238        AiMemoryOperationKind, AiMemoryRetentionKind, AiMemoryScope, AiMemorySensitivity,
239        AiMemorySourceKind, AiMemoryStatus,
240    };
241    use core::{fmt, str::FromStr};
242
243    fn assert_enum_family<T>(variants: &[T]) -> Result<(), AiMemoryError>
244    where
245        T: Copy + Eq + fmt::Debug + fmt::Display + FromStr<Err = AiMemoryError>,
246    {
247        for variant in variants {
248            let label = variant.to_string();
249            assert_eq!(label.parse::<T>()?, *variant);
250            assert_eq!(label.replace('-', "_").parse::<T>()?, *variant);
251            assert_eq!(label.replace('-', " ").parse::<T>()?, *variant);
252        }
253        Ok(())
254    }
255
256    #[test]
257    fn validates_memory_ids() -> Result<(), AiMemoryError> {
258        let id = AiMemoryId::new(" memory-001 ")?;
259
260        assert_eq!(id.as_str(), "memory-001");
261        assert_eq!(id.value(), "memory-001");
262        assert_eq!(id.as_ref(), "memory-001");
263        assert_eq!(id.to_string(), "memory-001");
264        assert_eq!(AiMemoryId::try_from("memory-001")?, id);
265        assert_eq!(id.into_string(), "memory-001".to_string());
266        assert_eq!(AiMemoryId::new("  "), Err(AiMemoryError::Empty));
267        Ok(())
268    }
269
270    #[test]
271    fn validates_memory_confidence() -> Result<(), AiMemoryError> {
272        assert_eq!(AiMemoryConfidence::new(0.0)?.value(), 0.0);
273        assert_eq!(AiMemoryConfidence::new(1.0)?.value(), 1.0);
274        assert_eq!(
275            AiMemoryConfidence::new(-0.1),
276            Err(AiMemoryError::OutOfRange)
277        );
278        assert_eq!(AiMemoryConfidence::new(1.1), Err(AiMemoryError::OutOfRange));
279        assert_eq!(
280            AiMemoryConfidence::new(f64::NAN),
281            Err(AiMemoryError::NonFinite)
282        );
283        Ok(())
284    }
285
286    #[test]
287    fn displays_and_parses_memory_enums() -> Result<(), AiMemoryError> {
288        assert_enum_family(AiMemoryKind::ALL)?;
289        assert_enum_family(AiMemoryScope::ALL)?;
290        assert_enum_family(AiMemoryStatus::ALL)?;
291        assert_enum_family(AiMemorySourceKind::ALL)?;
292        assert_enum_family(AiMemoryRetentionKind::ALL)?;
293        assert_enum_family(AiMemorySensitivity::ALL)?;
294        assert_enum_family(AiMemoryOperationKind::ALL)?;
295        assert_enum_family(AiMemoryConflictKind::ALL)?;
296        assert_eq!(
297            "policy controlled".parse::<AiMemoryRetentionKind>()?,
298            AiMemoryRetentionKind::PolicyControlled
299        );
300        Ok(())
301    }
302}