1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! The daemon-shaped memory storage contract: facts (with privacy, channel
//! provenance and the extraction graph), episodes, exact history and
//! people. A store implements the slices it supports; every method has a
//! conservative default.
use std::collections::HashSet;
use aidaemon_core::ChannelVisibility;
use async_trait::async_trait;
use crate::records::*;
/// Exact-history operations exposed to the search tool through a domain port.
#[async_trait]
pub trait HistorySearchStore: Send + Sync {
async fn history_snapshot_max_event_id(&self) -> anyhow::Result<i64>;
async fn history_coverage(&self) -> anyhow::Result<HistoryCoverage>;
async fn repair_history_projection(
&self,
max_batches: usize,
) -> anyhow::Result<ProjectionStats>;
async fn search_history(
&self,
query: &str,
scope: &HistoryScope,
limit: usize,
semantic_sessions: &HashSet<String>,
) -> anyhow::Result<Vec<HistoryMessage>>;
async fn history_context(
&self,
event_id: i64,
radius: usize,
scope: &HistoryScope,
) -> anyhow::Result<Vec<HistoryMessage>>;
async fn history_event_for_message_id(
&self,
message_id: &str,
scope: &HistoryScope,
) -> anyhow::Result<Option<i64>>;
async fn history_turn(
&self,
turn_id: &str,
scope: &HistoryScope,
) -> anyhow::Result<Vec<HistoryMessage>>;
/// The tool calls of a turn the scope may read; empty when it may not.
async fn history_turn_tool_activity(
&self,
turn_id: &str,
scope: &HistoryScope,
) -> anyhow::Result<Vec<HistoryToolActivity>>;
/// Which of the session's last `turns` prior user turns ran tools, oldest
/// first. Carries no message or tool content.
async fn history_recent_tool_turns(
&self,
session_id: &str,
turns: usize,
) -> anyhow::Result<Vec<RecentToolTurn>>;
async fn history_page(
&self,
anchor: i64,
older: bool,
scope: &HistoryScope,
limit: usize,
) -> anyhow::Result<Vec<HistoryMessage>>;
async fn history_task_bookends(
&self,
task_id: Option<&str>,
session_id: &str,
scope: &HistoryScope,
) -> anyhow::Result<TaskBookends>;
}
/// A reviewer's verdict on two facts the overlap detector paired. Stored
/// with both facts' content hashes: an edit to either one voids it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OverlapReviewVerdict {
/// Two different pieces of knowledge: never flag the pair again.
Distinct,
/// One attribute with two values that only the owner can settle.
Conflict,
/// Reviewed by background hygiene with no automatic action taken (e.g.
/// cross-scope or rank-guarded); keeps the UI hint visible while stopping
/// background hygiene from re-billing the unchanged pair.
Reviewed,
}
impl OverlapReviewVerdict {
pub fn as_str(self) -> &'static str {
match self {
Self::Distinct => "distinct",
Self::Conflict => "conflict",
Self::Reviewed => "reviewed",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value.trim() {
"distinct" => Some(Self::Distinct),
"conflict" => Some(Self::Conflict),
"reviewed" => Some(Self::Reviewed),
_ => None,
}
}
}
/// Layer-2 facts storage and retrieval (including privacy + channel provenance).
#[async_trait]
pub trait FactStore: Send + Sync {
/// Reconcile an entity-aware personal-memory write atomically.
async fn reconcile_personal_memory(
&self,
_write: &PersonalMemoryWrite,
_source: &str,
_source_excerpt: Option<&str>,
_channel_id: Option<&str>,
_privacy: FactPrivacy,
) -> anyhow::Result<PersonalMemoryWriteResult> {
anyhow::bail!("structured personal memory is not supported by this store")
}
/// Compatibility projection of active canonical facts and relationships.
async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
Ok(Vec::new())
}
/// Record that these facts and episodes were shown to a model. Recall
/// counts drive Core Profile salience and decay, so only content that
/// actually reached a prompt or a tool result may count; fetching a
/// candidate that was then cut by a budget is not a recall.
async fn record_memory_recall(
&self,
_fact_ids: &[i64],
_episode_ids: &[i64],
) -> anyhow::Result<()> {
Ok(())
}
/// Supersede active automated facts that restate another active fact in
/// the same category, keeping the most authoritative copy. Returns how
/// many rows were folded. Soft: superseded rows remain as history.
async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
Ok(0)
}
/// Retire automated facts that hold an older or farther-sourced value of
/// the attribute another active fact holds (numbers differ, whole facts
/// nearly identical, one visibility class): see
/// [`crate::sqlite::plan_numeric_conflicts`]. Owner-stated facts are
/// never retired by an automated one, and two owner-stated values are
/// left for the owner. Returns how many rows were retired.
async fn resolve_numeric_fact_conflicts(&self) -> anyhow::Result<usize> {
Ok(0)
}
/// Reversibly archive background-extracted facts nobody has used: never
/// recalled, not updated for `min_idle_days`, outside the identity
/// categories. Owner-stated and quoted facts are never touched.
/// `min_idle_days <= 0` archives nothing. Returns how many were archived.
async fn archive_unused_automated_facts(
&self,
_now: chrono::DateTime<chrono::Utc>,
_min_idle_days: i64,
) -> anyhow::Result<u64> {
Ok(0)
}
/// Fold one active automated fact into another active fact that keeps
/// its knowledge (a reviewed duplicate). Refuses an owner-stated
/// `folded_id`, a `kept_id` from a farther source, and a fold that would
/// hide the knowledge from an audience that could see it. Returns
/// whether the fold happened; [`FactStore::unfold_fact`] reverses it.
async fn fold_fact_into(&self, _folded_id: i64, _kept_id: i64) -> anyhow::Result<bool> {
Ok(false)
}
/// Fold one active flat fact into another active flat fact on an explicit
/// owner action (e.g. tapping Merge in the Memory UI). Allows merging any
/// two active positive flat facts the owner selected, while preserving
/// recall counts, fold tombstones, overlap cleanup, and live projections.
async fn owner_fold_fact_into(&self, _folded_id: i64, _kept_id: i64) -> anyhow::Result<bool> {
Ok(false)
}
/// Promote an active flat fact to owner-confirmed (`user_stated`) without
/// changing its value, so inferred/derived memories leave "Needs review"
/// in one tap. Returns the updated fact if found.
async fn confirm_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
Ok(None)
}
/// Bring a folded fact back as active, when no active fact holds its key.
async fn unfold_fact(&self, _folded_id: i64) -> anyhow::Result<Option<Fact>> {
Ok(None)
}
/// Replace an automated fact's value (a merged wording of duplicates).
/// Refuses owner-stated facts: their words are the owner's.
async fn refine_automated_fact_value(
&self,
_fact_id: i64,
_new_value: &str,
) -> anyhow::Result<Option<Fact>> {
Ok(None)
}
/// Record a verdict on two overlapping facts, bound to their current
/// contents.
async fn record_overlap_review(
&self,
_fact_a_id: i64,
_fact_b_id: i64,
_verdict: OverlapReviewVerdict,
_reviewer: &str,
) -> anyhow::Result<()> {
Ok(())
}
/// The verdict on this pair, if one was given and neither fact has
/// changed since.
async fn has_valid_overlap_review(
&self,
_fact_a_id: i64,
_fact_b_id: i64,
) -> anyhow::Result<Option<OverlapReviewVerdict>> {
Ok(None)
}
/// Whether a fact with this id exists and is not retired (it may be
/// archived).
async fn fact_exists(&self, fact_id: i64) -> anyhow::Result<bool> {
Ok(self.get_fact_by_id(fact_id).await?.is_some())
}
/// The fact with this id, if it is not retired (it may be archived).
async fn get_fact_by_id(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
Ok(None)
}
/// When the named background memory job last ran.
async fn job_last_run_at(
&self,
_job_name: &str,
) -> anyhow::Result<Option<chrono::DateTime<chrono::Utc>>> {
Ok(None)
}
/// Record that the named background memory job ran at `at`.
async fn record_job_run_at(
&self,
_job_name: &str,
_at: chrono::DateTime<chrono::Utc>,
) -> anyhow::Result<()> {
Ok(())
}
/// Upsert a fact with channel provenance and privacy level.
async fn upsert_fact(
&self,
category: &str,
key: &str,
value: &str,
source: &str,
channel_id: Option<&str>,
privacy: FactPrivacy,
) -> anyhow::Result<()> {
self.upsert_fact_with_provenance(
category, key, value, source, channel_id, privacy, None, None,
)
.await
}
/// Upsert a fact with full provenance data.
#[allow(clippy::too_many_arguments)]
async fn upsert_fact_with_provenance(
&self,
category: &str,
key: &str,
value: &str,
source: &str,
channel_id: Option<&str>,
privacy: FactPrivacy,
first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
source_excerpt: Option<&str>,
) -> anyhow::Result<()>;
/// Get all facts, optionally filtered by category.
async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>>;
/// Get facts semantically relevant to a query, falling back to `get_facts` on error.
async fn get_relevant_facts(&self, _query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
// Default: return all facts (capped). Implementations can override with semantic filtering.
let mut facts = self.get_facts(None).await?;
facts.truncate(max);
Ok(facts)
}
/// Get facts for a specific channel context, respecting privacy levels.
///
/// `requester_is_owner` controls the DM short-circuit: only the owner sees the
/// full unfiltered graph (incl. Private + other-channel facts) in a 1:1 DM. A
/// non-owner (an allowlisted Guest) gets the same privacy filtering as a group
/// channel — Global + same-channel facts only, never Private or other-channel —
/// so owner secrets can't leak into a guest's prompt context.
async fn get_relevant_facts_for_channel(
&self,
query: &str,
max: usize,
_channel_id: Option<&str>,
_visibility: ChannelVisibility,
_requester_is_owner: bool,
) -> anyhow::Result<Vec<Fact>> {
self.get_relevant_facts(query, max).await
}
/// Update a fact's privacy level (e.g., channel → global after approval).
async fn update_fact_privacy(
&self,
_fact_id: i64,
_privacy: FactPrivacy,
) -> anyhow::Result<()> {
Ok(())
}
/// Record where the active fact at this key came from.
async fn stamp_fact_provenance(
&self,
_category: &str,
_key: &str,
_source: &str,
_first_seen_at: Option<chrono::DateTime<chrono::Utc>>,
_source_excerpt: Option<&str>,
) -> anyhow::Result<()> {
Ok(())
}
/// Soft-delete a fact by superseding it.
async fn delete_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
Ok(())
}
/// Soft-delete a fact by category and key. Returns true if a fact was found and deleted.
async fn delete_fact_by_key(&self, _category: &str, _key: &str) -> anyhow::Result<bool> {
Ok(false)
}
/// Edit an active fact's value in place as an explicit owner update.
/// Supports both positive flat fact ids and negative canonical ids where
/// editable (owner facts and aliases). Returns the updated fact if found.
async fn update_fact_value(&self, _fact_id: i64, _value: &str) -> anyhow::Result<Option<Fact>> {
Ok(None)
}
/// Reversibly archive an active fact so it leaves passive recall without
/// permanent deletion. Returns true if an active fact was archived.
async fn archive_fact(&self, _fact_id: i64) -> anyhow::Result<bool> {
Ok(false)
}
/// Restore a previously archived fact back to active memory.
async fn restore_fact(&self, _fact_id: i64) -> anyhow::Result<Option<Fact>> {
Ok(None)
}
/// Archived facts available for restore, newest first.
async fn get_archived_facts(&self, _limit: usize) -> anyhow::Result<Vec<Fact>> {
Ok(Vec::new())
}
/// Automatically archive active facts whose typed `expires_at` has passed.
async fn archive_expired_facts(
&self,
_now: chrono::DateTime<chrono::Utc>,
) -> anyhow::Result<u64> {
Ok(0)
}
/// Map of active fact id -> another active fact id that looks like a
/// conceptual duplicate/overlap (for UI review hints).
async fn detect_fact_overlaps(&self) -> anyhow::Result<std::collections::HashMap<i64, i64>> {
Ok(std::collections::HashMap::new())
}
/// Get all active facts with provenance info for memory management display.
async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
self.get_facts(None).await
}
/// Explicit fact search: one ranked list plus query-relevant related
/// facts. Ranking lives in [`crate::search`]; a store only gathers facts
/// and scores. The default returns an empty report so stores without
/// search keep compiling.
async fn search_facts(
&self,
_query: &str,
_limit: usize,
_config: &crate::search::FactSearchConfig,
) -> anyhow::Result<crate::search::FactSearchReport> {
Ok(crate::search::FactSearchReport::default())
}
/// Persist a model-extracted semantic graph for an already-written fact.
/// Implementations must validate the graph and retain claim provenance.
async fn project_extracted_fact_graph(
&self,
_category: &str,
_key: &str,
_source_excerpt: &str,
_graph: &ExtractedMemoryGraph,
) -> anyhow::Result<()> {
Ok(())
}
/// Refresh canonical claim/vector projections for the active fact at this key.
async fn refresh_fact_memory(&self, _category: &str, _key: &str) -> anyhow::Result<()> {
Ok(())
}
async fn memory_health_report(&self) -> anyhow::Result<MemoryHealthReport> {
Ok(MemoryHealthReport::default())
}
async fn repair_memory_projections(&self) -> anyhow::Result<MemoryHealthReport> {
self.memory_health_report().await
}
}
/// Episodic memory storage and retrieval.
#[async_trait]
pub trait EpisodeStore: Send + Sync {
/// Refresh derived canonical-memory projections for an episode. Stores that
/// do not maintain secondary indexes may keep the default no-op.
async fn project_episode_memory(&self, _episode_id: i64) -> anyhow::Result<()> {
Ok(())
}
/// Get episodes relevant to a query.
async fn get_relevant_episodes(
&self,
_query: &str,
_limit: usize,
) -> anyhow::Result<Vec<Episode>> {
Ok(vec![])
}
/// Get episodes for a specific channel context.
async fn get_relevant_episodes_for_channel(
&self,
_query: &str,
_limit: usize,
_channel_id: Option<&str>,
) -> anyhow::Result<Vec<Episode>> {
Ok(vec![])
}
/// Get episodes only from one canonical session (used by untrusted
/// internal/sub-agent origins).
async fn get_relevant_episodes_for_session(
&self,
_query: &str,
_limit: usize,
_session_id: &str,
) -> anyhow::Result<Vec<Episode>> {
Ok(vec![])
}
/// Where the session's most recent episode stopped, if it has one.
async fn last_episode_bound(&self, _session_id: &str) -> anyhow::Result<Option<EpisodeBound>> {
Ok(None)
}
/// `(session id, latest episode end time)` for every session with an
/// episode.
async fn latest_episode_ends(&self) -> anyhow::Result<Vec<(String, String)>> {
Ok(vec![])
}
/// Record a session episode; returns its id. A store that keeps
/// episodes also embeds the summary for recall.
async fn record_session_episode(
&self,
_episode: &crate::episodes::SessionEpisode,
) -> anyhow::Result<i64> {
anyhow::bail!("this store does not record session episodes")
}
}
/// People persistence (social graph).
#[async_trait]
pub trait PeopleStore: Send + Sync {
/// Create or update a person record. Returns the person ID.
async fn upsert_person(&self, _person: &Person) -> anyhow::Result<i64> {
Ok(0)
}
/// Get a person by their database ID.
async fn get_person(&self, _id: i64) -> anyhow::Result<Option<Person>> {
Ok(None)
}
/// Look up a person by a platform-qualified sender ID (e.g., "slack:U123").
async fn get_person_by_platform_id(
&self,
_platform_id: &str,
) -> anyhow::Result<Option<Person>> {
Ok(None)
}
/// Find a person by name or alias (case-insensitive).
async fn find_person_by_name(&self, _name: &str) -> anyhow::Result<Option<Person>> {
Ok(None)
}
/// Get all people.
async fn get_all_people(&self) -> anyhow::Result<Vec<Person>> {
Ok(vec![])
}
/// Delete a person and all their facts (cascade).
async fn delete_person(&self, _id: i64) -> anyhow::Result<()> {
Ok(())
}
/// Link a platform identity to a person.
async fn link_platform_id(
&self,
_person_id: i64,
_platform_id: &str,
_display_name: &str,
) -> anyhow::Result<()> {
Ok(())
}
/// Update interaction tracking for a person.
async fn touch_person_interaction(&self, _person_id: i64) -> anyhow::Result<()> {
Ok(())
}
/// Create or update a fact about a person.
async fn upsert_person_fact(
&self,
_person_id: i64,
_category: &str,
_key: &str,
_value: &str,
_source: &str,
_confidence: f32,
) -> anyhow::Result<()> {
Ok(())
}
/// Get facts about a person, optionally filtered by category.
async fn get_person_facts(
&self,
_person_id: i64,
_category: Option<&str>,
) -> anyhow::Result<Vec<PersonFact>> {
Ok(vec![])
}
/// Delete a person fact by ID.
async fn delete_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
Ok(())
}
/// Confirm an auto-extracted person fact (set confidence to 1.0).
async fn confirm_person_fact(&self, _fact_id: i64) -> anyhow::Result<()> {
Ok(())
}
/// Get people with upcoming dates (birthdays, important dates) within N days.
async fn get_people_with_upcoming_dates(
&self,
_within_days: i32,
) -> anyhow::Result<Vec<(Person, PersonFact)>> {
Ok(vec![])
}
/// Delete stale auto-extracted person facts older than N days with confidence < 1.0.
async fn prune_stale_person_facts(&self, _retention_days: u32) -> anyhow::Result<u64> {
Ok(0)
}
/// Get people who haven't interacted in more than N days.
async fn get_people_needing_reconnect(
&self,
_inactive_days: u32,
) -> anyhow::Result<Vec<Person>> {
Ok(vec![])
}
}
/// An entity to create or merge in the memory graph.
#[derive(Debug, Clone)]
pub struct GraphEntityUpsert {
pub entity_type: String,
pub canonical_name: String,
pub display_name: String,
pub aliases: Vec<String>,
pub channel_id: Option<String>,
pub privacy: FactPrivacy,
}
#[derive(Debug, Clone)]
pub struct GraphEdgeUpsert {
pub source_entity_id: i64,
pub target_entity_id: i64,
pub relation: String,
pub source_claim_id: i64,
pub confidence: f32,
pub channel_id: Option<String>,
pub privacy: FactPrivacy,
}
#[derive(Debug, Clone)]
pub struct GraphSearchScope {
pub channel_id: Option<String>,
pub visibility: ChannelVisibility,
pub requester_is_owner: bool,
}
#[derive(Debug, Clone)]
pub struct GraphNeighbor {
pub entity_id: i64,
pub display_name: String,
pub relation: String,
pub depth: usize,
}
/// The memory graph: entities and the relations between them, each edge
/// backed by the claim (fact) that asserts it, so retracting the claim
/// invalidates the edge.
#[async_trait]
pub trait MemoryGraphStore: Send + Sync {
async fn upsert_entity(&self, entity: GraphEntityUpsert) -> anyhow::Result<i64>;
async fn upsert_edge(&self, edge: GraphEdgeUpsert) -> anyhow::Result<()>;
async fn invalidate_claim(&self, claim_id: i64, valid_to: &str) -> anyhow::Result<()>;
async fn neighbors(
&self,
start_entity_id: i64,
max_depth: usize,
scope: &GraphSearchScope,
) -> anyhow::Result<Vec<GraphNeighbor>>;
}
/// How unrecalled memory fades. Facts not recalled for `fact_idle_days`
/// lose `1 / fact_decay_divisor` of their recall count per pass (at least
/// one); episodes not recalled for `episode_idle_days` lose one; behavior
/// patterns not seen for `pattern_idle_days` lose `pattern_step`
/// confidence (down to 0.1). Background-extracted facts never recalled
/// and untouched for `unused_automated_fact_days` are archived (0 keeps
/// them).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DecayPolicy {
pub fact_idle_days: i64,
pub fact_decay_divisor: i64,
pub episode_idle_days: i64,
pub pattern_idle_days: i64,
pub pattern_step: f32,
pub unused_automated_fact_days: i64,
}
impl Default for DecayPolicy {
fn default() -> Self {
Self {
fact_idle_days: 14,
fact_decay_divisor: 10,
episode_idle_days: 30,
pattern_idle_days: 30,
pattern_step: 0.05,
unused_automated_fact_days: 60,
}
}
}
/// Fading of unrecalled memory, applied by the store.
#[async_trait]
pub trait MemoryDecay: Send + Sync {
async fn decay(
&self,
policy: &DecayPolicy,
now: chrono::DateTime<chrono::Utc>,
) -> anyhow::Result<()>;
}
/// One maintenance pass: archive expired facts, merge restated facts,
/// retire superseded numeric values, archive unused automated facts, then
/// let unrecalled memory fade, so decay sees one active row per piece of
/// knowledge. Runs every step each call; a caller that must not repeat a
/// daily pass (a restart) checks [`FactStore::job_last_run_at`] first.
pub async fn decay_memory<S>(store: &S, policy: &DecayPolicy) -> anyhow::Result<()>
where
S: FactStore + MemoryDecay + ?Sized,
{
let now = chrono::Utc::now();
if let Err(error) = store.archive_expired_facts(now).await {
tracing::warn!(%error, "Failed to archive expired facts");
}
if let Err(error) = store.fold_restated_facts().await {
tracing::warn!(%error, "Failed to fold restated facts");
}
if let Err(error) = store.resolve_numeric_fact_conflicts().await {
tracing::warn!(%error, "Failed to resolve numeric fact conflicts");
}
if policy.unused_automated_fact_days > 0
&& let Err(error) = store
.archive_unused_automated_facts(now, policy.unused_automated_fact_days)
.await
{
tracing::warn!(%error, "Failed to archive unused automated facts");
}
store.decay(policy, now).await
}
/// Every store behind the daemon-shaped memory contract, as one handle.
pub trait MemoryStores:
FactStore + EpisodeStore + PeopleStore + crate::LearningStore + MemoryGraphStore + MemoryDecay
{
}
impl<T> MemoryStores for T where
T: FactStore
+ EpisodeStore
+ PeopleStore
+ crate::LearningStore
+ MemoryGraphStore
+ MemoryDecay
{
}