Skip to main content

aidaemon_memory/
records.rs

1//! The records of the daemon-shaped memory contract ([`crate::stores`]):
2//! facts with privacy and channel provenance, extraction results, episodes,
3//! people, and exact conversation history.
4
5use std::collections::HashMap;
6
7use aidaemon_core::{ChannelVisibility, UserRole};
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11/// Privacy level for facts stored in memory.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13pub enum FactPrivacy {
14    /// Accessible everywhere (user's name, timezone, general preferences).
15    Global,
16    /// Accessible only in originating channel + DMs.
17    Channel,
18    /// DM-only, never shared in channels, never hinted.
19    Private,
20}
21
22impl std::fmt::Display for FactPrivacy {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        match self {
25            FactPrivacy::Global => write!(f, "global"),
26            FactPrivacy::Channel => write!(f, "channel"),
27            FactPrivacy::Private => write!(f, "private"),
28        }
29    }
30}
31
32/// Categories a background extractor (per-turn extraction, consolidation,
33/// task learning) may write flat facts into. Facts the owner stores
34/// explicitly keep any category; people go through structured personal
35/// memory, not this list.
36///
37/// `behavior` and `relationship` are deliberately absent: an extractor reads
38/// one session, so it cannot observe recurrence, and asked for "recurring
39/// workflows" or "communication patterns" it filed every single request as
40/// a habit. A stated way of working is a `preference`.
41pub const AUTOMATED_FACT_CATEGORIES: &[&str] = &["user", "preference", "project", "technical"];
42
43/// Whether a background extractor may write a flat fact in `category`.
44pub fn automated_fact_category_allowed(category: &str) -> bool {
45    let category = category.trim();
46    AUTOMATED_FACT_CATEGORIES
47        .iter()
48        .any(|allowed| allowed.eq_ignore_ascii_case(category))
49}
50
51impl FactPrivacy {
52    pub fn from_str_lossy(s: &str) -> Self {
53        match s {
54            "global" => Self::Global,
55            "channel" => Self::Channel,
56            "private" => Self::Private,
57            _ => Self::Global,
58        }
59    }
60
61    /// Whether moving a fact from `self` to `to` lets more chats see it.
62    pub fn widens_to(self, to: Self) -> bool {
63        fn reach(privacy: FactPrivacy) -> u8 {
64            match privacy {
65                FactPrivacy::Private => 0,
66                FactPrivacy::Channel => 1,
67                FactPrivacy::Global => 2,
68            }
69        }
70        reach(to) > reach(self)
71    }
72}
73
74/// A fact stored in Layer 2 memory.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct Fact {
77    pub id: i64,
78    pub category: String,
79    pub key: String,
80    pub value: String,
81    pub source: String,
82    pub created_at: DateTime<Utc>,
83    pub updated_at: DateTime<Utc>,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub superseded_at: Option<DateTime<Utc>>,
86    #[serde(default)]
87    pub recall_count: i32,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub last_recalled_at: Option<DateTime<Utc>>,
90    /// Channel where this fact originated (e.g., "slack:C12345"). None for legacy/global facts.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub channel_id: Option<String>,
93    /// Privacy level controlling where this fact can be recalled.
94    #[serde(default = "default_fact_privacy")]
95    pub privacy: FactPrivacy,
96    /// When the fact was originally stated or inferred in the event stream.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub first_seen_at: Option<DateTime<Utc>>,
99    /// The exact snippet of conversation that generated this fact.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub source_excerpt: Option<String>,
102}
103
104fn default_fact_privacy() -> FactPrivacy {
105    FactPrivacy::Global
106}
107
108/// An entity proposed by the memory extraction model. `local_id` is scoped to
109/// one extraction result and is used by relationships to avoid name ambiguity.
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct ExtractedMemoryEntity {
112    pub local_id: String,
113    pub name: String,
114    pub entity_type: String,
115    #[serde(default)]
116    pub aliases: Vec<String>,
117    #[serde(default = "default_extraction_confidence")]
118    pub confidence: f32,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ExtractedMemoryRelationship {
123    pub source_id: String,
124    pub target_id: String,
125    pub relation: String,
126    #[serde(default = "default_extraction_confidence")]
127    pub confidence: f32,
128}
129
130/// Optional semantic graph attached to a fact extraction. Fact persistence is
131/// independent: invalid graph output is ignored rather than poisoning memory.
132#[derive(Debug, Clone, Default, Serialize, Deserialize)]
133pub struct ExtractedMemoryGraph {
134    #[serde(default)]
135    pub entities: Vec<ExtractedMemoryEntity>,
136    #[serde(default)]
137    pub relationships: Vec<ExtractedMemoryRelationship>,
138}
139
140fn default_extraction_confidence() -> f32 {
141    0.5
142}
143
144/// A canonical entity proposed by the personal-memory extractor.
145///
146/// `local_id` only links records inside one write. `is_reference` distinguishes
147/// a mention of an already-known alias from a declaration of a new entity.
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct PersonalEntityCandidate {
150    pub local_id: String,
151    pub entity_type: String,
152    pub canonical_name: String,
153    #[serde(default)]
154    pub is_reference: bool,
155    #[serde(default)]
156    pub canonical_name_confirmed: bool,
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct PersonalAliasCandidate {
161    pub entity_local_id: String,
162    pub value: String,
163    pub alias_type: String,
164}
165
166#[derive(Debug, Clone, Serialize, Deserialize)]
167pub struct PersonalFactCandidate {
168    pub subject_local_id: String,
169    pub predicate: String,
170    pub value: String,
171    #[serde(default)]
172    pub display_value: Option<String>,
173    #[serde(default)]
174    pub valid_from: Option<String>,
175    #[serde(default)]
176    pub valid_to: Option<String>,
177    /// The writer asks to forget this predicate rather than state a value.
178    /// Only a direct owner statement retracts; `value` is ignored.
179    #[serde(default)]
180    pub retract: bool,
181}
182
183#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct PersonalRelationshipCandidate {
185    pub source_local_id: String,
186    pub relationship_type: String,
187    pub target_local_id: String,
188    #[serde(default)]
189    pub valid_from: Option<String>,
190    #[serde(default)]
191    pub valid_to: Option<String>,
192}
193
194/// One atomic, entity-aware personal-memory write plan.
195#[derive(Debug, Clone, Default, Serialize, Deserialize)]
196pub struct PersonalMemoryWrite {
197    #[serde(default)]
198    pub entities: Vec<PersonalEntityCandidate>,
199    #[serde(default)]
200    pub aliases: Vec<PersonalAliasCandidate>,
201    #[serde(default)]
202    pub facts: Vec<PersonalFactCandidate>,
203    #[serde(default)]
204    pub relationships: Vec<PersonalRelationshipCandidate>,
205    /// True only when the owner directly supplied the information.
206    #[serde(default)]
207    pub direct_user_statement: bool,
208    /// True when the owner explicitly corrected a previously stored value.
209    #[serde(default)]
210    pub correction: bool,
211}
212
213#[derive(Debug, Clone, Default, Serialize, Deserialize)]
214pub struct PersonalMemoryWriteResult {
215    pub created_entities: usize,
216    pub updated_entities: usize,
217    pub created_aliases: usize,
218    pub confirmed_aliases: usize,
219    pub created_facts: usize,
220    pub confirmed_facts: usize,
221    pub superseded_facts: usize,
222    pub disputed_facts: usize,
223    pub created_relationships: usize,
224    pub confirmed_relationships: usize,
225    #[serde(default)]
226    pub unresolved: Vec<String>,
227}
228
229impl PersonalMemoryWriteResult {
230    pub fn concise_summary(&self) -> String {
231        let mut parts = Vec::new();
232        for (count, label) in [
233            (self.created_entities, "entities created"),
234            (self.updated_entities, "entities updated"),
235            (self.created_aliases, "aliases created"),
236            (self.confirmed_aliases, "aliases confirmed"),
237            (self.created_facts, "facts created"),
238            (self.confirmed_facts, "facts confirmed"),
239            (self.superseded_facts, "facts superseded"),
240            (self.disputed_facts, "facts disputed"),
241            (self.created_relationships, "relationships created"),
242            (self.confirmed_relationships, "relationships confirmed"),
243        ] {
244            if count > 0 {
245                parts.push(format!("{count} {label}"));
246            }
247        }
248        if !self.unresolved.is_empty() {
249            parts.push(format!("{} unresolved", self.unresolved.len()));
250        }
251        if parts.is_empty() {
252            "No changes (already current).".to_string()
253        } else {
254            parts.join(", ")
255        }
256    }
257}
258
259#[derive(Debug, Clone, Default, Serialize, Deserialize)]
260pub struct MemoryHealthReport {
261    pub spans: i64,
262    pub active_claims: i64,
263    pub entities: i64,
264    pub active_edges: i64,
265    pub active_embeddings: i64,
266    pub stale_embeddings: i64,
267    pub facts_missing_claims: i64,
268    pub episodes_missing_spans: i64,
269    pub orphan_edges: i64,
270    pub embedding_dimension_mismatches: i64,
271}
272
273/// An episode representing a session summary (episodic memory).
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct Episode {
276    pub id: i64,
277    pub session_id: String,
278    pub summary: String,
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub topics: Option<Vec<String>>,
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub emotional_tone: Option<String>,
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub outcome: Option<String>,
285    pub importance: f32,
286    pub recall_count: i32,
287    #[serde(skip_serializing_if = "Option::is_none")]
288    pub last_recalled_at: Option<DateTime<Utc>>,
289    pub message_count: i32,
290    pub start_time: DateTime<Utc>,
291    pub end_time: DateTime<Utc>,
292    pub created_at: DateTime<Utc>,
293    /// Channel where this episode occurred. None for legacy episodes.
294    #[serde(skip_serializing_if = "Option::is_none")]
295    pub channel_id: Option<String>,
296}
297
298/// Where an episode stopped: the last event it covers (recent episodes) or
299/// its end time (older ones, which recorded no event bound), as stored.
300#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct EpisodeBound {
302    pub end_event_id: Option<i64>,
303    pub end_time: Option<String>,
304}
305
306/// A person in the owner's social circle.
307#[derive(Debug, Clone, Serialize, Deserialize)]
308pub struct Person {
309    pub id: i64,
310    pub name: String,
311    pub aliases: Vec<String>,
312    pub relationship: Option<String>,
313    pub platform_ids: HashMap<String, String>,
314    pub notes: Option<String>,
315    pub communication_style: Option<String>,
316    pub language_preference: Option<String>,
317    pub last_interaction_at: Option<DateTime<Utc>>,
318    pub interaction_count: i64,
319    pub created_at: DateTime<Utc>,
320    pub updated_at: DateTime<Utc>,
321}
322
323/// A fact about a person (birthday, preference, interest, etc.).
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct PersonFact {
326    pub id: i64,
327    pub person_id: i64,
328    pub category: String,
329    pub key: String,
330    pub value: String,
331    pub source: String,
332    pub confidence: f32,
333    pub created_at: DateTime<Utc>,
334    pub updated_at: DateTime<Utc>,
335}
336
337/// Who may see which conversation history in a search.
338#[derive(Debug, Clone)]
339pub struct HistoryScope {
340    pub session_id: String,
341    pub channel_id: Option<String>,
342    pub visibility: ChannelVisibility,
343    pub user_role: UserRole,
344    pub trusted: bool,
345    pub include_subagents: bool,
346    pub session_filter: Option<String>,
347    pub task_filter: Option<String>,
348    pub snapshot_max_event_id: i64,
349}
350
351#[derive(Debug, Clone, Serialize)]
352pub struct HistoryMessage {
353    pub event_id: i64,
354    pub session_id: String,
355    #[serde(skip_serializing_if = "Option::is_none")]
356    pub task_id: Option<String>,
357    #[serde(skip_serializing_if = "Option::is_none")]
358    pub turn_id: Option<String>,
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub message_id: Option<String>,
361    pub role: String,
362    pub content: String,
363    pub created_at: String,
364    pub source_kind: String,
365    #[serde(skip_serializing_if = "Option::is_none")]
366    pub lexical_rank: Option<f64>,
367}
368
369/// One completed tool call of a retained turn. Fresh tasks do not see these in
370/// their transcript, so this is how they read what an earlier turn observed.
371#[derive(Debug, Clone, Serialize, Deserialize)]
372pub struct HistoryToolActivity {
373    pub tool: String,
374    pub success: bool,
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub arguments: Option<serde_json::Value>,
377    pub output: String,
378    /// Characters of `output` left out to fit the response.
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub output_omitted_chars: Option<usize>,
381}
382
383/// A recent turn of a session that ran tools.
384#[derive(Debug, Clone, PartialEq, Eq)]
385pub struct RecentToolTurn {
386    pub turn_id: String,
387    /// How many user turns back this one is; the newest prior turn is 1.
388    pub turns_ago: usize,
389    /// Tool name and how many calls of it completed, in first-use order.
390    pub tools: Vec<(String, usize)>,
391    /// Tool name and how many calls of it were refused before running, in
392    /// first-use order.
393    pub refused: Vec<(String, usize)>,
394}
395
396#[derive(Debug, Clone, Serialize)]
397pub struct TaskBookends {
398    #[serde(skip_serializing_if = "Option::is_none")]
399    pub objective: Option<HistoryMessage>,
400    #[serde(skip_serializing_if = "Option::is_none")]
401    pub generated_objective: Option<String>,
402    pub objective_source: String,
403    #[serde(skip_serializing_if = "Option::is_none")]
404    pub resolution: Option<HistoryMessage>,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub generated_resolution: Option<String>,
407    pub resolution_source: String,
408}
409
410#[derive(Debug, Clone, Default, Serialize)]
411pub struct ProjectionStats {
412    pub projected: u64,
413    pub orphans_removed: u64,
414    pub fts_rebuilt: bool,
415    pub episodes_repaired: u64,
416    pub pending: i64,
417}
418
419#[derive(Debug, Clone, Serialize)]
420pub struct HistoryCoverage {
421    pub canonical_messages: i64,
422    pub indexed_messages: i64,
423    pub pending_messages: i64,
424    #[serde(skip_serializing_if = "Option::is_none")]
425    pub oldest_indexed_at: Option<String>,
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub newest_indexed_at: Option<String>,
428}