Skip to main content

aidaemon_memory/full/tools/
manage_memories.rs

1//! `manage_memories`: read, search, forget and re-scope what the memory
2//! holds. A host that manages more than memory through the same tool (the
3//! daemon's goals) presents its own combined tool and runs these actions
4//! through [`ManageMemoriesTool::run`].
5
6use std::sync::Arc;
7
8use aidaemon_core::ChannelVisibility;
9use aidaemon_tools::OutcomeTool as Tool;
10use aidaemon_tools::semantics::{
11    ApprovalCall, OwnerApprovalNeed, ToolCallContext, ToolCallMetadata, ToolCallOutcome,
12    ToolCallSemantics, ToolCapabilities, ToolMutationEffects, ToolOutcomeStatus,
13    semantics_for_exact_read_actions,
14};
15use async_trait::async_trait;
16use serde::Deserialize;
17use serde_json::{Value, json};
18
19use crate::records::{Fact, FactPrivacy};
20use crate::stores::MemoryStores;
21
22/// The actions this tool runs.
23pub const MEMORY_ACTIONS: &[&str] = &[
24    "list",
25    "health",
26    "repair",
27    "forget",
28    "set_privacy",
29    "search",
30    "search_episodes",
31];
32
33/// The actions that only read.
34const READ_ACTIONS: &[&str] = &["list", "health", "search", "search_episodes"];
35
36fn compact_provenance_excerpt(text: &str) -> String {
37    let single_line = text.split_whitespace().collect::<Vec<_>>().join(" ");
38    crate::text::truncate_chars(&single_line, 180)
39}
40
41/// The stored facts and episodes, managed by the model: list, search,
42/// forget, change who may see a fact, and check or repair the store.
43pub struct ManageMemoriesTool {
44    store: Arc<dyn MemoryStores>,
45}
46
47impl ManageMemoriesTool {
48    pub fn new(store: Arc<dyn MemoryStores>) -> Self {
49        Self { store }
50    }
51
52    /// The active fact a `set_privacy` call names, if any.
53    async fn find_fact(&self, category: &str, key: &str) -> anyhow::Result<Option<Fact>> {
54        Ok(self
55            .store
56            .get_facts(Some(category))
57            .await?
58            .into_iter()
59            .find(|f| f.key == key && f.superseded_at.is_none()))
60    }
61
62    /// The owner card for a `set_privacy` call that widens who may see a
63    /// fact; narrowing, a call naming no active fact, and every other
64    /// action need none. The subject is the exact arguments approved.
65    pub async fn privacy_approval(&self, arguments: &Value) -> OwnerApprovalNeed {
66        let Ok(args) = serde_json::from_value::<ManageArgs>(arguments.clone()) else {
67            return OwnerApprovalNeed::NotNeeded;
68        };
69        let (Some(category), Some(key), Some(privacy)) = (
70            args.category.as_deref(),
71            args.key.as_deref(),
72            args.privacy.as_deref(),
73        ) else {
74            return OwnerApprovalNeed::NotNeeded;
75        };
76        if args.action != "set_privacy" {
77            return OwnerApprovalNeed::NotNeeded;
78        }
79        let to = FactPrivacy::from_str_lossy(privacy);
80        let value = match self.find_fact(category, key).await {
81            Ok(Some(fact)) if fact.privacy.widens_to(to) => {
82                format!(" = \"{}\"", crate::text::truncate_chars(&fact.value, 83))
83            }
84            Ok(_) => return OwnerApprovalNeed::NotNeeded,
85            // The lookup failed: ask with what the call names rather than
86            // waving it through (the run reads the store again).
87            Err(_) => String::new(),
88        };
89        OwnerApprovalNeed::Ask(aidaemon_core::OwnerApprovalRequest::plain(format!("Make memory {to}: [{category}] {key}{value}"), json!({"action": "set_privacy", "category": category, "key": key, "privacy": to.to_string()})
90                .to_string(), aidaemon_core::ApprovalRisk::High, vec![match to {
91                FactPrivacy::Global => "This will make this memory visible across all channels",
92                _ => "This will make this memory visible in its channel, not only in DMs",
93            }
94            .to_string()]))
95    }
96}
97
98#[derive(Deserialize)]
99struct ManageArgs {
100    action: String,
101    limit: Option<usize>,
102    category: Option<String>,
103    key: Option<String>,
104    privacy: Option<String>,
105    query: Option<String>,
106}
107
108const TOOL_DESCRIPTION: &str = "Memories. search=stored facts; search_episodes=generated summaries of past chats (exact messages: search_history). Store via remember_fact.";
109
110/// The memory actions' parameters, each described. A host that offers more
111/// actions on the same tool (personal goals) extends this map.
112pub fn memory_parameters() -> serde_json::Map<String, Value> {
113    let Value::Object(map) = json!({
114        "action": { "type": "string", "enum": MEMORY_ACTIONS, "description": "forget and set_privacy name one fact by category and key." },
115        "limit": { "type": "integer", "description": "Max results." },
116        "category": { "type": "string", "description": "forget/set_privacy: the fact's category; list: filter." },
117        "key": { "type": "string", "description": "forget/set_privacy: the fact's key." },
118        "privacy": { "type": "string", "enum": ["global", "channel", "private"], "description": "set_privacy: who may see it." },
119        "query": { "type": "string", "description": "search: what to find. search_episodes: a topic, or omit for the latest chats." }
120    }) else {
121        unreachable!("a JSON object literal")
122    };
123    map
124}
125
126/// The answer to an action the tool does not have, naming the ones it has.
127pub fn unknown_action_message(action: &str, actions: &[&str]) -> String {
128    format!("Unknown action: '{action}'. Use {}.", actions.join(", "))
129}
130
131fn manage_memories_schema() -> Value {
132    json!({
133        "name": "manage_memories",
134        "description": TOOL_DESCRIPTION,
135        "parameters": {
136            "type": "object",
137            "properties": memory_parameters(),
138            "required": ["action"],
139            "additionalProperties": false
140        }
141    })
142}
143
144/// Memory is persistent agent state, so writes are `configuration` and a
145/// forget is also `destructive`.
146fn memory_action_effects(arguments: &str) -> ToolMutationEffects {
147    match action_of(arguments).as_deref() {
148        Some("forget") => {
149            ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::DESTRUCTIVE)
150        }
151        Some("set_privacy") => ToolMutationEffects::CONFIGURATION,
152        _ => ToolMutationEffects::NONE,
153    }
154}
155
156/// The `action` argument, if any.
157fn action_of(arguments: &str) -> Option<String> {
158    serde_json::from_str::<Value>(arguments)
159        .ok()?
160        .get("action")?
161        .as_str()
162        .map(str::to_string)
163}
164
165#[async_trait]
166impl Tool for ManageMemoriesTool {
167    fn name(&self) -> &str {
168        "manage_memories"
169    }
170
171    fn description(&self) -> &str {
172        TOOL_DESCRIPTION
173    }
174
175    fn schema(&self) -> Value {
176        manage_memories_schema()
177    }
178
179    async fn execute(
180        &self,
181        arguments: &str,
182        facts: &ToolCallContext,
183    ) -> anyhow::Result<ToolCallOutcome> {
184        let output = self.run(arguments, facts).await?;
185        let trimmed = output.trim_start();
186        let outcome_status = if trimmed.starts_with("Unknown action:") {
187            ToolOutcomeStatus::FailedPermanent
188        } else if trimmed.starts_with("No matching") {
189            ToolOutcomeStatus::CompletedWithNegativeResult
190        } else {
191            ToolOutcomeStatus::Succeeded
192        };
193        Ok(ToolCallOutcome {
194            output,
195            metadata: ToolCallMetadata {
196                outcome_status: Some(outcome_status),
197                ..ToolCallMetadata::default()
198            },
199            finish: None,
200        })
201    }
202}
203
204#[async_trait]
205impl aidaemon_tools::semantics::ToolSemantics for ManageMemoriesTool {
206    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
207        aidaemon_tools::semantics::ToolDispatchFacts {
208            offering: aidaemon_tools::semantics::Offering::Core,
209            status_from_arguments: true,
210            activity: aidaemon_tools::semantics::ToolActivity::Memory,
211            ..Default::default()
212        }
213    }
214
215    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
216        semantics_for_exact_read_actions(arguments, READ_ACTIONS, memory_action_effects(arguments))
217    }
218
219    fn capabilities(&self) -> ToolCapabilities {
220        ToolCapabilities::APPROVED_HIGH_IMPACT_LOCAL
221    }
222
223    /// `set_privacy` asks the owner when it widens who may see a fact.
224    async fn owner_approval_request(
225        &self,
226        call: &ApprovalCall<'_>,
227        _facts: &ToolCallContext,
228    ) -> OwnerApprovalNeed {
229        self.privacy_approval(call.arguments).await
230    }
231
232    /// Reads, `repair` and `forget` touch only the agent's own memory
233    /// store. `set_privacy` widens who may see a fact, so it stays
234    /// undeclared.
235    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
236        match action_of(arguments).as_deref() {
237            Some("list" | "health" | "search" | "search_episodes" | "repair" | "forget") => {
238                aidaemon_core::CallEffects::none()
239            }
240            _ => aidaemon_core::CallEffects::unknown(),
241        }
242    }
243}
244
245impl ManageMemoriesTool {
246    /// Run one call with the dispatcher's `facts` (session, role, channel,
247    /// trust), never facts from the arguments. An action outside
248    /// [`MEMORY_ACTIONS`] is answered as unknown.
249    pub async fn run(&self, arguments: &str, facts: &ToolCallContext) -> anyhow::Result<String> {
250        let args: ManageArgs = serde_json::from_str(arguments)?;
251        let trusted_session = facts.trusted_session;
252        let audience = call_audience(facts);
253
254        match args.action.as_str() {
255            "health" => {
256                let report = self.store.memory_health_report().await?;
257                Ok(serde_json::to_string_pretty(&report)?)
258            }
259            "repair" => {
260                let report = self.store.repair_memory_projections().await?;
261                Ok(serde_json::to_string_pretty(&report)?)
262            }
263            "list" => {
264                let mut facts = self.store.get_canonical_memory_facts().await?;
265                let canonical_owner_keys: std::collections::HashSet<String> = facts
266                    .iter()
267                    .filter(|fact| fact.category == "user")
268                    .map(|fact| crate::text::owner_projection_family(&fact.key))
269                    .collect();
270                facts.extend(
271                    self.store
272                        .get_all_facts_with_provenance()
273                        .await?
274                        .into_iter()
275                        .filter(|fact| {
276                            let cat_lower = fact.category.trim().to_ascii_lowercase();
277                            let is_owner_cat =
278                                matches!(cat_lower.as_str(), "user" | "personal" | "profile")
279                                    || (cat_lower == "preference"
280                                        && crate::text::is_owner_profile_key(&fact.key));
281                            !is_owner_cat
282                                || !canonical_owner_keys
283                                    .contains(&crate::text::owner_projection_family(&fact.key))
284                        }),
285                );
286                // The same visibility rule recall applies: what this turn's
287                // audience may not see is never listed into its reply.
288                facts.retain(|fact| audience.may_see(Some(&fact_access(fact))));
289                if facts.is_empty() {
290                    return Ok("No memories stored.".to_string());
291                }
292
293                let filtered = if let Some(ref cat) = args.category {
294                    facts
295                        .into_iter()
296                        .filter(|f| f.category == *cat)
297                        .collect::<Vec<_>>()
298                } else {
299                    facts
300                };
301
302                let limit = args.limit.unwrap_or(100).clamp(1, 200);
303                let total = filtered.len();
304                let shown = filtered.into_iter().take(limit).collect::<Vec<_>>();
305
306                let mut output = format!(
307                    "**Stored Memories** (showing {} of {} facts)\n\n",
308                    shown.len(),
309                    total
310                );
311                let mut current_cat = String::new();
312                for f in &shown {
313                    if f.category != current_cat {
314                        current_cat = f.category.clone();
315                        output.push_str(&format!("### {}\n", current_cat));
316                    }
317                    let privacy_label = f.privacy.to_string();
318                    let channel_label = f.channel_id.as_deref().unwrap_or("global");
319                    let age = chrono::Utc::now().signed_duration_since(f.updated_at);
320                    let age_str = if age.num_days() > 0 {
321                        format!("{}d ago", age.num_days())
322                    } else if age.num_hours() > 0 {
323                        format!("{}h ago", age.num_hours())
324                    } else {
325                        "just now".to_string()
326                    };
327                    output.push_str(&format!(
328                        "- **{}**: {} (privacy: {}, from: {}, updated: {})\n",
329                        f.key, f.value, privacy_label, channel_label, age_str
330                    ));
331                }
332                if total > shown.len() {
333                    output.push_str(&format!(
334                        "\n(Results truncated to {}. Provide a higher `limit` to see more.)",
335                        shown.len()
336                    ));
337                }
338                Ok(output)
339            }
340            "forget" => {
341                let key_raw = args
342                    .key
343                    .as_deref()
344                    .ok_or_else(|| anyhow::anyhow!("'key' is required for forget action"))?;
345                let category = args
346                    .category
347                    .as_deref()
348                    .ok_or_else(|| anyhow::anyhow!("'category' is required for forget action"))?;
349
350                // Reject empty / whitespace-only / too-short keys. A blank key would
351                // make partial key matching true for every
352                // fact, wiping the store. A single character is also too broad to be
353                // a safe substring match across all facts.
354                let key = key_raw.trim();
355                if key.is_empty() {
356                    anyhow::bail!("'key' must not be empty or whitespace for forget action");
357                }
358                if key.chars().count() < 2 {
359                    anyhow::bail!(
360                        "'key' must be at least 2 characters for forget action (got {:?}); use manage_memories(action='list') to see exact keys",
361                        key
362                    );
363                }
364
365                // Canonicalize the requested key for fuzzy matching
366                let canon = |k: &str| -> String {
367                    let mut out = String::with_capacity(k.len());
368                    let mut last_sep = false;
369                    for ch in k.trim().chars() {
370                        if ch.is_ascii_alphanumeric() {
371                            out.push(ch.to_ascii_lowercase());
372                            last_sep = false;
373                        } else if !last_sep {
374                            out.push('_');
375                            last_sep = true;
376                        }
377                    }
378                    out.trim_matches('_').to_string()
379                };
380
381                let key_canonical = canon(key);
382
383                // Within the explicitly-requested category an exact or canonical
384                // key match is authoritative. Only when none exists may a partial
385                // key select facts, and then only as whole `_`-separated key
386                // segments ("color" -> "favorite_color"). A fact key contained
387                // in the requested key is never a match: forgetting
388                // `qa_pet_name` used to also delete the owner's `name` fact.
389                let exact_in_category = |f: &crate::records::Fact| -> bool {
390                    f.superseded_at.is_none() && (f.key == key || canon(&f.key) == key_canonical)
391                };
392                let key_segments: Vec<&str> = key_canonical.split('_').collect();
393                let partial_in_category = |f: &crate::records::Fact| -> bool {
394                    if f.superseded_at.is_some() || key_canonical.is_empty() {
395                        return false;
396                    }
397                    let fk_canon = canon(&f.key);
398                    let fact_segments: Vec<&str> = fk_canon.split('_').collect();
399                    fact_segments
400                        .windows(key_segments.len())
401                        .any(|window| window == key_segments.as_slice())
402                };
403
404                // Across OTHER categories (the "duplicate sweep") only accept exact
405                // or canonical matches. Substring matching outside the requested
406                // category is too broad and can delete unrelated facts.
407                let matches_key_cross_category = |f: &crate::records::Fact| -> bool {
408                    if f.superseded_at.is_some() {
409                        return false;
410                    }
411                    f.key == key || canon(&f.key) == key_canonical
412                };
413
414                let mut to_delete: Vec<(i64, String, String)> = Vec::new();
415                let mut seen_ids = std::collections::HashSet::new();
416
417                let facts = self.store.get_facts(Some(category)).await?;
418                let has_exact = facts.iter().any(&exact_in_category);
419                for f in &facts {
420                    let selected = if has_exact {
421                        exact_in_category(f)
422                    } else {
423                        partial_in_category(f)
424                    };
425                    if selected && seen_ids.insert(f.id) {
426                        to_delete.push((f.id, f.category.clone(), f.key.clone()));
427                    }
428                }
429
430                // Also check OTHER categories for exact/canonical duplicates only.
431                let all_facts = self.store.get_facts(None).await?;
432                for f in &all_facts {
433                    if f.category == category {
434                        continue;
435                    }
436                    if matches_key_cross_category(f) && seen_ids.insert(f.id) {
437                        to_delete.push((f.id, f.category.clone(), f.key.clone()));
438                    }
439                }
440
441                // Also check canonical personal memory (owner profile facts,
442                // aliases, relationships) so canonical-only records can be
443                // forgotten via `manage_memories(action="forget")`.
444                let canonical_facts = self.store.get_canonical_memory_facts().await?;
445                let req_personal_key = crate::text::canonical_personal_key(key);
446                let req_family = crate::text::owner_projection_family(key);
447                let cat_lower = category.trim().to_ascii_lowercase();
448                for f in &canonical_facts {
449                    let same_cat = f.category.eq_ignore_ascii_case(&cat_lower);
450                    let owner_alias_cat = f.category == "user"
451                        && (matches!(cat_lower.as_str(), "user" | "personal" | "profile")
452                            || (cat_lower == "preference"
453                                && crate::text::is_owner_profile_key(&req_personal_key)));
454                    let personal_match = (same_cat || owner_alias_cat)
455                        && (f.key == key
456                            || canon(&f.key) == key_canonical
457                            || crate::text::canonical_personal_key(&f.key) == req_personal_key
458                            || crate::text::owner_projection_family(&f.key) == req_family);
459                    if personal_match && seen_ids.insert(f.id) {
460                        to_delete.push((f.id, f.category.clone(), f.key.clone()));
461                    }
462                }
463
464                if to_delete.is_empty() {
465                    Ok(format!(
466                        "No active fact found matching key '{}' in any category. Use manage_memories(action='list') to see stored facts and their exact keys.",
467                        key
468                    ))
469                } else {
470                    let mut forgotten = Vec::new();
471                    for (id, cat, k) in &to_delete {
472                        self.store.delete_fact(*id).await?;
473                        forgotten.push(format!("[{}] {}", cat, k));
474                    }
475                    Ok(format!(
476                        "Forgotten {} fact(s): {}",
477                        forgotten.len(),
478                        forgotten.join(", ")
479                    ))
480                }
481            }
482            "set_privacy" => {
483                let key = args
484                    .key
485                    .as_deref()
486                    .ok_or_else(|| anyhow::anyhow!("'key' is required for set_privacy action"))?;
487                let category = args.category.as_deref().ok_or_else(|| {
488                    anyhow::anyhow!("'category' is required for set_privacy action")
489                })?;
490                let privacy_str = args.privacy.as_deref().ok_or_else(|| {
491                    anyhow::anyhow!("'privacy' is required for set_privacy action")
492                })?;
493                let privacy = FactPrivacy::from_str_lossy(privacy_str);
494
495                let fact = self.find_fact(category, key).await?;
496
497                match fact {
498                    Some(f) => {
499                        // The kernel asked the owner before a widening
500                        // runs; one that reaches here without its
501                        // judgment is refused.
502                        if f.privacy.widens_to(privacy) && facts.kernel_approved.is_none() {
503                            anyhow::bail!(
504                                "widening a memory's privacy requires approval through the agent \
505                                 kernel; it was called outside an approved agent call"
506                            );
507                        }
508                        self.store.update_fact_privacy(f.id, privacy).await?;
509                        Ok(format!(
510                            "Updated privacy: [{}] {} → {}",
511                            category, key, privacy
512                        ))
513                    }
514                    None => Ok(format!("No active fact found: [{}] {}", category, key)),
515                }
516            }
517            "search" => {
518                let query = args.query.as_deref().unwrap_or("");
519                if query.is_empty() {
520                    return Ok("Please provide a search query.".to_string());
521                }
522
523                let limit = args.limit.unwrap_or(10).clamp(1, 200);
524                let mut report = self
525                    .store
526                    .search_facts(query, limit, &crate::search::FactSearchConfig::default())
527                    .await?;
528                report
529                    .hits
530                    .retain(|hit| audience.may_see(Some(&fact_access(&hit.fact))));
531                if report.hits.is_empty() {
532                    return Ok(format!("No memories matching '{}'.", query));
533                }
534
535                let counts = format!(
536                    "{} shown of {} considered",
537                    report.hits.len(),
538                    report.considered
539                );
540                let mut output = format!(
541                    "══ Stored facts matching '{}' ({}) ══\n\
542                     IMPORTANT: Use these EXACT values when answering — do not substitute or infer.\n\n",
543                    query, counts
544                );
545                for hit in &report.hits {
546                    let f = &hit.fact;
547                    let privacy_label = f.privacy.to_string();
548                    let channel_label = f.channel_id.as_deref().unwrap_or("global");
549                    let marker = if hit.kind == crate::search::MatchKind::Semantic {
550                        " (semantic match)"
551                    } else {
552                        ""
553                    };
554                    // Surface WHEN the fact was learned so the model can answer
555                    // temporal questions ("when did I tell you X?") directly from
556                    // search results instead of reaching for the wrong tool.
557                    let learned_ts = f.first_seen_at.unwrap_or(f.created_at).to_rfc3339();
558                    let learned = aidaemon_tools::duration_format::format_age(&learned_ts);
559                    let evidence = f
560                        .source_excerpt
561                        .as_deref()
562                        .map(compact_provenance_excerpt)
563                        .filter(|excerpt| !excerpt.is_empty())
564                        .map(|excerpt| {
565                            format!(
566                                "; evidence: {}",
567                                serde_json::to_string(&excerpt)
568                                    .unwrap_or_else(|_| "\"[unavailable]\"".to_string())
569                            )
570                        })
571                        .unwrap_or_default();
572                    output.push_str(&format!(
573                        "• [{}] {} → \"{}\" (fact_id: {}, source: {}, privacy: {}, from: {}, learned: {}{}){}\n",
574                        f.category,
575                        f.key,
576                        f.value,
577                        f.id,
578                        f.source,
579                        privacy_label,
580                        channel_label,
581                        learned,
582                        evidence,
583                        marker
584                    ));
585                }
586                if !report.related.is_empty() {
587                    output.push_str("\n── Related context (connected facts) ──\n");
588                    for hit in &report.related {
589                        output.push_str(&format!(
590                            "• [{}] {} → \"{}\"\n",
591                            hit.fact.category, hit.fact.key, hit.fact.value
592                        ));
593                    }
594                }
595
596                Ok(output)
597            }
598            "search_episodes" => {
599                // Active recall over episodic memory (past-conversation summaries).
600                // Facts answer "what is X"; episodes answer "what did we discuss /
601                // do, and when". With a query → semantic search; without one →
602                // most-recent conversations (browse). This tool is owner-only (the
603                // session tool roster is empty for non-owners), with explicit
604                // channel/session scoping for non-private origins.
605                let query = args.query.as_deref().unwrap_or("").trim();
606                let limit = args.limit.unwrap_or(8).clamp(1, 50);
607                let visibility = facts
608                    .channel_visibility
609                    .unwrap_or(ChannelVisibility::Internal);
610                let episodes = match visibility {
611                    ChannelVisibility::Private => {
612                        self.store.get_relevant_episodes(query, limit).await?
613                    }
614                    ChannelVisibility::PrivateGroup | ChannelVisibility::Public => {
615                        self.store
616                            .get_relevant_episodes_for_channel(
617                                query,
618                                limit,
619                                facts.channel_id.as_deref(),
620                            )
621                            .await?
622                    }
623                    ChannelVisibility::PublicExternal => {
624                        return Ok(
625                            "Past-conversation recall is disabled in public-external channels."
626                                .to_string(),
627                        );
628                    }
629                    ChannelVisibility::Internal if trusted_session => {
630                        self.store.get_relevant_episodes(query, limit).await?
631                    }
632                    ChannelVisibility::Internal => {
633                        let session_id = facts.session().unwrap_or("");
634                        self.store
635                            .get_relevant_episodes_for_session(query, limit, session_id)
636                            .await?
637                    }
638                };
639                let recalled: Vec<i64> = episodes.iter().map(|episode| episode.id).collect();
640                let _ = self.store.record_memory_recall(&[], &recalled).await;
641                if episodes.is_empty() {
642                    return Ok(if query.is_empty() {
643                        "No past conversations recorded yet.".to_string()
644                    } else {
645                        format!("No past conversations found matching '{}'.", query)
646                    });
647                }
648
649                let header = if query.is_empty() {
650                    format!(
651                        "══ Generated episode summaries: recent conversations ({}) ══\n\n",
652                        episodes.len()
653                    )
654                } else {
655                    format!(
656                        "══ Generated episode summaries matching '{}' ({}) ══\n\n",
657                        query,
658                        episodes.len()
659                    )
660                };
661                let mut output = header;
662                for e in &episodes {
663                    let when =
664                        aidaemon_tools::duration_format::format_age(&e.created_at.to_rfc3339());
665                    output.push_str(&format!("• [{}] {}", when, e.summary.trim()));
666                    if let Some(topics) = e.topics.as_ref().filter(|t| !t.is_empty()) {
667                        output.push_str(&format!(" (topics: {})", topics.join(", ")));
668                    }
669                    if let Some(outcome) = e.outcome.as_deref().filter(|o| !o.is_empty()) {
670                        output.push_str(&format!(" [outcome: {}]", outcome));
671                    }
672                    output.push('\n');
673                }
674                output.push_str(
675                    "\nThese are semantic, generated summaries. Use search_history for exact \
676                     retained user/assistant wording, anchored context, and message paging.\n",
677                );
678                Ok(output)
679            }
680            other => Ok(unknown_action_message(other, MEMORY_ACTIONS)),
681        }
682    }
683}
684
685/// Who the call's reply reaches, from the dispatcher's typed facts: the
686/// owner (or a trusted scheduled session) in its own conversation sees all of
687/// its memory; anyone else sees only what was learned in their channel.
688fn call_audience(facts: &ToolCallContext) -> crate::types::RecallAudience {
689    let visibility = facts
690        .channel_visibility
691        .unwrap_or(ChannelVisibility::Internal);
692    let owner =
693        matches!(facts.user_role, Some(aidaemon_core::UserRole::Owner)) || facts.trusted_session;
694    crate::types::RecallAudience::new(visibility, facts.channel_id.clone(), owner)
695}
696
697fn fact_access(fact: &Fact) -> crate::types::FactAccess {
698    crate::types::FactAccess {
699        privacy: fact.privacy,
700        channel_id: fact.channel_id.clone(),
701    }
702}
703
704#[cfg(test)]
705mod tests {
706    use super::*;
707
708    #[test]
709    fn provenance_excerpt_is_single_line_utf8_safe_and_bounded() {
710        let input = format!("User said:\n\t{}", "🦀".repeat(250));
711        let compact = compact_provenance_excerpt(&input);
712        assert!(!compact.contains('\n'));
713        assert!(!compact.contains('\t'));
714        assert!(compact.chars().count() <= 180);
715        assert!(compact.ends_with("..."));
716    }
717
718    async fn tool_with_channel_fact() -> (Arc<crate::sqlite::SqliteMemory>, ManageMemoriesTool) {
719        use crate::stores::FactStore as _;
720        let store = crate::full::tools::test_support::memory().await;
721        store
722            .upsert_fact(
723                "preference",
724                "report_format",
725                "short summaries for Alice Rivera",
726                "owner",
727                Some("telegram:synthetic-channel-1"),
728                FactPrivacy::Channel,
729            )
730            .await
731            .unwrap();
732        (store.clone(), ManageMemoriesTool::new(store))
733    }
734
735    #[tokio::test]
736    async fn list_and_search_hide_what_the_audience_may_not_see() {
737        use crate::stores::FactStore as _;
738        let (store, tool) = tool_with_channel_fact().await;
739        store
740            .upsert_fact(
741                "preference",
742                "home_city",
743                "Lisbon",
744                "owner",
745                None,
746                FactPrivacy::Global,
747            )
748            .await
749            .unwrap();
750        let guest = ToolCallContext {
751            channel_visibility: Some(ChannelVisibility::PrivateGroup),
752            channel_id: Some("telegram:synthetic-channel-2".to_string()),
753            user_role: Some(aidaemon_core::UserRole::Guest),
754            ..Default::default()
755        };
756        let listed = tool.run(r#"{"action":"list"}"#, &guest).await.unwrap();
757        assert!(!listed.contains("Lisbon"), "{listed}");
758        assert!(!listed.contains("Alice Rivera"), "{listed}");
759        let found = tool
760            .run(r#"{"action":"search","query":"Lisbon"}"#, &guest)
761            .await
762            .unwrap();
763        assert!(!found.contains("home_city"), "{found}");
764
765        let owner = ToolCallContext {
766            channel_visibility: Some(ChannelVisibility::Private),
767            user_role: Some(aidaemon_core::UserRole::Owner),
768            ..Default::default()
769        };
770        let listed = tool.run(r#"{"action":"list"}"#, &owner).await.unwrap();
771        assert!(
772            listed.contains("Lisbon") && listed.contains("Alice Rivera"),
773            "{listed}"
774        );
775    }
776
777    async fn privacy_of(store: &crate::sqlite::SqliteMemory) -> FactPrivacy {
778        use crate::stores::FactStore as _;
779        store.get_facts(Some("preference")).await.unwrap()[0].privacy
780    }
781
782    #[tokio::test]
783    async fn widening_privacy_asks_with_its_exact_arguments() {
784        let (_, tool) = tool_with_channel_fact().await;
785        let args = json!({"action": "set_privacy", "category": "preference", "key": "report_format", "privacy": "global"});
786        let OwnerApprovalNeed::Ask(request) = tool.privacy_approval(&args).await else {
787            panic!("widening a fact must ask");
788        };
789        assert_eq!(
790            request.summary,
791            "Make memory global: [preference] report_format = \"short summaries for Alice Rivera\""
792        );
793        assert_eq!(request.risk, aidaemon_core::ApprovalRisk::High);
794        let subject: Value = serde_json::from_str(&request.subject).unwrap();
795        assert_eq!(subject, args);
796        for narrower in [
797            json!({"action": "set_privacy", "category": "preference", "key": "report_format", "privacy": "private"}),
798            json!({"action": "set_privacy", "category": "preference", "key": "absent", "privacy": "global"}),
799            json!({"action": "list"}),
800        ] {
801            assert!(matches!(
802                tool.privacy_approval(&narrower).await,
803                OwnerApprovalNeed::NotNeeded
804            ));
805        }
806    }
807
808    #[tokio::test]
809    async fn widening_without_the_kernel_is_refused_and_narrowing_is_not() {
810        let (store, tool) = tool_with_channel_fact().await;
811        let widen = r#"{"action":"set_privacy","category":"preference","key":"report_format","privacy":"global"}"#;
812        let err = tool
813            .run(widen, &ToolCallContext::default())
814            .await
815            .unwrap_err();
816        assert!(
817            err.to_string()
818                .contains("requires approval through the agent kernel"),
819            "{err}"
820        );
821        assert_eq!(privacy_of(&store).await, FactPrivacy::Channel);
822        tool.run(
823            widen,
824            &ToolCallContext {
825                kernel_approved: Some(aidaemon_tools::semantics::ApprovalScope::Call),
826                ..Default::default()
827            },
828        )
829        .await
830        .unwrap();
831        assert_eq!(privacy_of(&store).await, FactPrivacy::Global);
832        let narrow = r#"{"action":"set_privacy","category":"preference","key":"report_format","privacy":"private"}"#;
833        tool.run(narrow, &ToolCallContext::default()).await.unwrap();
834        assert_eq!(privacy_of(&store).await, FactPrivacy::Private);
835    }
836
837    #[tokio::test]
838    async fn forget_retracts_canonical_only_owner_fact() {
839        use crate::records::{
840            PersonalAliasCandidate, PersonalEntityCandidate, PersonalMemoryWrite,
841        };
842        use crate::stores::FactStore as _;
843        let store = crate::full::tools::test_support::memory().await;
844        let update = PersonalMemoryWrite {
845            direct_user_statement: true,
846            entities: vec![PersonalEntityCandidate {
847                local_id: "owner".to_string(),
848                entity_type: "person".to_string(),
849                canonical_name: "Owner".to_string(),
850                is_reference: false,
851                canonical_name_confirmed: false,
852            }],
853            aliases: vec![PersonalAliasCandidate {
854                entity_local_id: "owner".to_string(),
855                value: "Alice".to_string(),
856                alias_type: "preferred_name".to_string(),
857            }],
858            ..Default::default()
859        };
860        store
861            .reconcile_personal_memory(
862                &update,
863                "user_stated",
864                Some("Call me Alice"),
865                None,
866                FactPrivacy::Global,
867            )
868            .await
869            .unwrap();
870        assert!(
871            store
872                .get_canonical_memory_facts()
873                .await
874                .unwrap()
875                .iter()
876                .any(|f| f.key == "preferred_name" && f.value == "Alice")
877        );
878        let tool = ManageMemoriesTool::new(store.clone());
879        let owner = ToolCallContext {
880            channel_visibility: Some(ChannelVisibility::Private),
881            user_role: Some(aidaemon_core::UserRole::Owner),
882            ..Default::default()
883        };
884        let out = tool
885            .run(
886                r#"{"action":"forget","category":"user","key":"preferred_name"}"#,
887                &owner,
888            )
889            .await
890            .unwrap();
891        assert!(out.contains("Forgot"), "{out}");
892        assert!(
893            !store
894                .get_canonical_memory_facts()
895                .await
896                .unwrap()
897                .iter()
898                .any(|f| f.key == "preferred_name" && f.value == "Alice")
899        );
900    }
901}