Skip to main content

aidaemon_memory/full/tools/
manage_people.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use serde::Deserialize;
6use serde_json::{Value, json};
7
8use aidaemon_tools::OutcomeTool as Tool;
9use aidaemon_tools::semantics::{
10    ToolCallSemantics, ToolCapabilities, ToolMutationEffects, semantics_for_exact_read_actions,
11};
12use aidaemon_tools::services::SettingsStore;
13
14use crate::records::{Person, PersonFact};
15
16/// The people store's tool. People intelligence is on while the host's
17/// `people_enabled` setting is `"true"`; `enable`/`disable` set it.
18pub struct ManagePeopleTool {
19    store: Arc<dyn crate::stores::MemoryStores>,
20    settings: Arc<dyn SettingsStore>,
21}
22
23impl ManagePeopleTool {
24    pub fn new(
25        settings: Arc<dyn SettingsStore>,
26        store: Arc<dyn crate::stores::MemoryStores>,
27    ) -> Self {
28        Self { store, settings }
29    }
30}
31
32#[derive(Deserialize)]
33struct ManagePeopleArgs {
34    action: String,
35    #[serde(default)]
36    name: Option<String>,
37    #[serde(default)]
38    id: Option<i64>,
39    #[serde(default)]
40    relationship: Option<String>,
41    #[serde(default)]
42    notes: Option<String>,
43    #[serde(default)]
44    communication_style: Option<String>,
45    #[serde(default)]
46    language: Option<String>,
47    #[serde(default)]
48    category: Option<String>,
49    #[serde(default)]
50    key: Option<String>,
51    #[serde(default)]
52    value: Option<String>,
53    #[serde(default)]
54    person_name: Option<String>,
55    #[serde(default)]
56    platform_id: Option<String>,
57    #[serde(default)]
58    fact_id: Option<i64>,
59    #[serde(default)]
60    display_name: Option<String>,
61    #[serde(default)]
62    within_days: Option<i32>,
63    #[serde(default)]
64    inactive_days: Option<u32>,
65    #[serde(default)]
66    personal_memory: Option<crate::records::PersonalMemoryWrite>,
67}
68
69/// The tool's one description: the schema the model reads and
70/// `description()` both use it.
71const TOOL_DESCRIPTION: &str = "People in the owner's life. remember: store people, names, aliases, family and places in personal memory, which recall reads (always on). The other actions are the contacts book (People Intelligence).";
72
73/// The `personal_memory` block `remember` takes: people and places as
74/// entities with call-local ids, their aliases, facts and relationships.
75pub(crate) fn personal_memory_schema() -> Value {
76    json!({
77        "type": "object",
78        "description": "remember: entities with call-local ids, then aliases, facts and relationships that refer to those ids. The owner is local_id \"owner\".",
79        "properties": {
80            "entities": {
81                "type": "array",
82                "description": "Each person, organization, project, place or account mentioned.",
83                "items": {
84                    "type": "object",
85                    "properties": {
86                        "local_id": {"type": "string", "description": "Id used by this call only."},
87                        "entity_type": {"type": "string", "enum": ["person", "organization", "project", "place", "account"], "description": "What it is."},
88                        "canonical_name": {"type": "string", "description": "Name as the owner gave it."},
89                        "is_reference": {"type": "boolean", "description": "Resolve existing alias/name; false declares."},
90                        "canonical_name_confirmed": {"type": "boolean", "description": "The owner stated this exact name."}
91                    },
92                    "required": ["local_id", "entity_type", "canonical_name"]
93                }
94            },
95            "aliases": {
96                "type": "array",
97                "description": "Other names an entity goes by.",
98                "items": {
99                    "type": "object",
100                    "properties": {
101                        "entity_local_id": {"type": "string", "description": "The entity's local_id."},
102                        "value": {"type": "string", "description": "The alias."},
103                        "alias_type": {"type": "string", "enum": ["legal_name_variant", "preferred_name", "nickname", "username", "online_handle", "account_name"], "description": "Kind of alias."}
104                    },
105                    "required": ["entity_local_id", "value", "alias_type"]
106                }
107            },
108            "facts": {
109                "type": "array",
110                "description": "Attributes of an entity (birthday, residence, ...).",
111                "items": {
112                    "type": "object",
113                    "properties": {
114                        "subject_local_id": {"type": "string", "description": "The entity's local_id."},
115                        "predicate": {"type": "string", "description": "snake_case attribute, e.g. birthday."},
116                        "value": {"type": "string", "description": "Normalized value."},
117                        "display_value": {"type": "string", "description": "Value as written, when it differs."},
118                        "valid_from": {"type": "string", "description": "RFC3339 or date it became true."},
119                        "valid_to": {"type": "string", "description": "When it stopped being true."}
120                    },
121                    "required": ["subject_local_id", "predicate", "value"]
122                }
123            },
124            "relationships": {
125                "type": "array",
126                "description": "Typed links between entities.",
127                "items": {
128                    "type": "object",
129                    "properties": {
130                        "source_local_id": {"type": "string", "description": "From entity."},
131                        "relationship_type": {"type": "string", "enum": ["PARENT_OF", "CHILD_OF", "LIVES_WITH", "LIVES_IN", "USES_ALIAS", "USES_HANDLE", "HAS_ACCOUNT"], "description": "source → target."},
132                        "target_local_id": {"type": "string", "description": "To entity."},
133                        "valid_from": {"type": "string", "description": "When it began."},
134                        "valid_to": {"type": "string", "description": "When it ended."}
135                    },
136                    "required": ["source_local_id", "relationship_type", "target_local_id"]
137                }
138            },
139            "correction": {"type": "boolean", "description": "The owner is correcting an earlier value."}
140        },
141        "additionalProperties": false
142    })
143}
144
145fn manage_people_schema() -> Value {
146    json!({
147        "name": "manage_people",
148        "description": TOOL_DESCRIPTION,
149        "parameters": {
150            "type": "object",
151            "properties": {
152                "action": {
153                    "type": "string",
154                    "enum": ["remember", "enable", "disable", "status", "add", "list", "view", "brief", "upcoming", "reconnect", "update", "remove", "add_fact", "remove_fact", "link", "export", "purge", "audit", "confirm"]
155                },
156                "name": { "type": "string" },
157                "id": { "type": "integer" },
158                "relationship": { "type": "string" },
159                "notes": { "type": "string" },
160                "communication_style": { "type": "string" },
161                "language": { "type": "string" },
162                "person_name": { "type": "string", "description": "Person for add_fact/remove_fact/link" },
163                "category": { "type": "string", "description": "Fact category; avoid health/finance" },
164                "key": { "type": "string" },
165                "value": { "type": "string", "description": "For category birthday or important_date: an ISO date, YYYY-MM-DD, or --MM-DD without a year" },
166                "platform_id": { "type": "string" },
167                "display_name": { "type": "string" },
168                "fact_id": { "type": "integer" },
169                "within_days": { "type": "integer", "description": "days ahead" },
170                "inactive_days": { "type": "integer" },
171                "personal_memory": personal_memory_schema()
172            },
173            "required": ["action"],
174            "additionalProperties": false
175        }
176    })
177}
178
179#[async_trait]
180impl Tool for ManagePeopleTool {
181    fn name(&self) -> &str {
182        "manage_people"
183    }
184
185    fn description(&self) -> &str {
186        TOOL_DESCRIPTION
187    }
188
189    fn schema(&self) -> Value {
190        manage_people_schema()
191    }
192
193    async fn execute(
194        &self,
195        arguments: &str,
196        facts: &aidaemon_tools::semantics::ToolCallContext,
197    ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
198        let output: anyhow::Result<String> = async move {
199        let args: ManagePeopleArgs = serde_json::from_str(arguments)?;
200
201        // Toggle actions are always allowed regardless of enabled state, and
202        // so is `remember`: personal memory is not the contacts book.
203        match args.action.as_str() {
204            "remember" => return self.handle_remember(args, facts.channel_id.as_deref()).await,
205            "enable" => return self.handle_enable().await,
206            "disable" => return self.handle_disable().await,
207            "status" => return self.handle_status().await,
208            _ => {}
209        }
210
211        // Gate all other actions behind the runtime setting
212        if !self.is_people_enabled().await {
213            return Ok(
214                "People Intelligence is disabled. Use action 'enable' to turn it on.".to_string(),
215            );
216        }
217
218        match args.action.as_str() {
219            "add" => self.handle_add(&args).await,
220            "list" => self.handle_list(&args).await,
221            "view" => self.handle_view(&args).await,
222            "brief" => self.handle_brief(&args).await,
223            "upcoming" => self.handle_upcoming(&args).await,
224            "reconnect" => self.handle_reconnect(&args).await,
225            "update" => self.handle_update(&args).await,
226            "remove" => self.handle_remove(&args).await,
227            "add_fact" => self.handle_add_fact(&args).await,
228            "remove_fact" => self.handle_remove_fact(&args).await,
229            "link" => self.handle_link(&args).await,
230            "export" => self.handle_export(&args).await,
231            "purge" => self.handle_purge(&args).await,
232            "audit" => self.handle_audit(&args).await,
233            "confirm" => self.handle_confirm(&args).await,
234            other => Ok(format!("Unknown action: {}. Use: enable, disable, status, add, list, view, brief, upcoming, reconnect, update, remove, add_fact, remove_fact, link, export, purge, audit, confirm", other)),
235        }
236    }.await;
237        output.map(aidaemon_tools::semantics::ToolCallOutcome::from_output)
238    }
239}
240
241impl aidaemon_tools::semantics::ToolSemantics for ManagePeopleTool {
242    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
243        aidaemon_tools::semantics::ToolDispatchFacts {
244            status_from_arguments: true,
245            activity: aidaemon_tools::semantics::ToolActivity::Memory,
246            ..Default::default()
247        }
248    }
249
250    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
251        // `remember` writes the agent's memory, typed as remember_fact's
252        // writes are so a checklist step can be credited by it.
253        if action_of(arguments).as_deref() == Some("remember") {
254            return ToolCallSemantics::mutation_with(
255                ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::MEMORY_WRITE),
256            );
257        }
258        // Every other action writes the people store too (notes that go
259        // into later prompts, or who a sender is linked to), and is typed
260        // the same way: after outside content was read, such a write is
261        // checked like any other change to what the agent is told.
262        semantics_for_exact_read_actions(
263            arguments,
264            &["status", "list", "view", "brief", "upcoming", "audit"],
265            ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::MEMORY_WRITE),
266        )
267    }
268
269    fn capabilities(&self) -> ToolCapabilities {
270        ToolCapabilities {
271            read_only: false,
272            external_side_effect: false,
273            needs_approval: true,
274            idempotent: false,
275            high_impact_write: false,
276        }
277    }
278
279    /// Every action but `enable`/`disable` (a runtime setting) touches only
280    /// the agent's own people store.
281    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
282        let action = serde_json::from_str::<Value>(arguments)
283            .ok()
284            .and_then(|args| {
285                args.get("action")
286                    .and_then(Value::as_str)
287                    .map(str::to_string)
288            });
289        match action.as_deref() {
290            Some(
291                "remember" | "status" | "add" | "list" | "view" | "brief" | "upcoming"
292                | "reconnect" | "update" | "remove" | "add_fact" | "remove_fact" | "export"
293                | "purge" | "audit" | "confirm",
294            ) => aidaemon_core::CallEffects::none(),
295            // `link` binds a sender to a person, so that person's facts reach
296            // the sender's later turns: it widens who sees the owner's notes.
297            _ => aidaemon_core::CallEffects::unknown(),
298        }
299    }
300}
301
302/// The `action` argument, if any.
303fn action_of(arguments: &str) -> Option<String> {
304    serde_json::from_str::<Value>(arguments)
305        .ok()?
306        .get("action")?
307        .as_str()
308        .map(str::to_string)
309}
310
311impl ManagePeopleTool {
312    /// Store people, aliases, facts and relationships in structured personal
313    /// memory: the store recall projects into the owner's facts and core
314    /// profile.
315    async fn handle_remember(
316        &self,
317        args: ManagePeopleArgs,
318        channel_id: Option<&str>,
319    ) -> anyhow::Result<String> {
320        let Some(mut personal) = args.personal_memory.filter(|personal| {
321            !(personal.entities.is_empty()
322                && personal.aliases.is_empty()
323                && personal.facts.is_empty()
324                && personal.relationships.is_empty())
325        }) else {
326            return Ok("Missing required field: personal_memory (entities, aliases, facts or relationships)".to_string());
327        };
328        personal.direct_user_statement = true;
329        let result = self
330            .store
331            .reconcile_personal_memory(
332                &personal,
333                "agent",
334                None,
335                channel_id,
336                crate::records::FactPrivacy::Private,
337            )
338            .await?;
339        Ok(format!("Personal memory: {}", result.concise_summary()))
340    }
341
342    async fn resolve_person(&self, args: &ManagePeopleArgs) -> anyhow::Result<Option<Person>> {
343        if let Some(id) = args.id {
344            return self.store.get_person(id).await;
345        }
346        if let Some(ref name) = args.name {
347            return self.store.find_person_by_name(name).await;
348        }
349        if let Some(ref person_name) = args.person_name {
350            return self.store.find_person_by_name(person_name).await;
351        }
352        Ok(None)
353    }
354
355    async fn handle_add(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
356        let name = match &args.name {
357            Some(n) => n.clone(),
358            None => return Ok("Missing required field: name".to_string()),
359        };
360
361        let person = Person {
362            id: 0,
363            name: name.clone(),
364            aliases: vec![],
365            relationship: args.relationship.clone(),
366            platform_ids: HashMap::new(),
367            notes: args.notes.clone(),
368            communication_style: args.communication_style.clone(),
369            language_preference: args.language.clone(),
370            last_interaction_at: None,
371            interaction_count: 0,
372            created_at: chrono::Utc::now(),
373            updated_at: chrono::Utc::now(),
374        };
375
376        let id = self.store.upsert_person(&person).await?;
377        Ok(format!("Added person '{}' with ID {}", name, id))
378    }
379
380    async fn handle_list(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
381        let people = self.store.get_all_people().await?;
382        if people.is_empty() {
383            return Ok("No people tracked yet.".to_string());
384        }
385
386        let mut result = format!("**People** ({} total)\n", people.len());
387        for p in &people {
388            let rel = p.relationship.as_deref().unwrap_or("—");
389            let style = p.communication_style.as_deref().unwrap_or("—");
390            let interaction_info = if p.interaction_count > 0 {
391                format!(", {} interactions", p.interaction_count)
392            } else {
393                String::new()
394            };
395
396            // Filter by relationship if specified
397            if let Some(ref filter) = args.relationship
398                && p.relationship.as_deref() != Some(filter.as_str())
399            {
400                continue;
401            }
402
403            result.push_str(&format!(
404                "- **{}** (ID: {}) — {} | style: {}{}\n",
405                p.name, p.id, rel, style, interaction_info
406            ));
407        }
408        Ok(result)
409    }
410
411    async fn handle_view(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
412        let person = if let Some(id) = args.id {
413            self.store.get_person(id).await?
414        } else if let Some(ref name) = args.name {
415            self.store.find_person_by_name(name).await?
416        } else {
417            return Ok("Provide 'name' or 'id' to view a person.".to_string());
418        };
419
420        let person = match person {
421            Some(p) => p,
422            None => return Ok("Person not found.".to_string()),
423        };
424
425        let facts = self.store.get_person_facts(person.id, None).await?;
426        let mut result = format!("## {}", person.name);
427        if let Some(ref rel) = person.relationship {
428            result.push_str(&format!(" ({})", rel));
429        }
430        result.push('\n');
431
432        if !person.aliases.is_empty() {
433            result.push_str(&format!("**Aliases:** {}\n", person.aliases.join(", ")));
434        }
435        if let Some(ref style) = person.communication_style {
436            result.push_str(&format!("**Communication style:** {}\n", style));
437        }
438        if let Some(ref lang) = person.language_preference {
439            result.push_str(&format!("**Language:** {}\n", lang));
440        }
441        if !person.platform_ids.is_empty() {
442            let ids: Vec<String> = person
443                .platform_ids
444                .iter()
445                .map(|(k, v)| format!("{} ({})", k, v))
446                .collect();
447            result.push_str(&format!("**Platform IDs:** {}\n", ids.join(", ")));
448        }
449        if let Some(ref notes) = person.notes {
450            result.push_str(&format!("**Notes:** {}\n", notes));
451        }
452        result.push_str(&format!("**Interactions:** {}\n", person.interaction_count));
453        if let Some(ref last) = person.last_interaction_at {
454            result.push_str(&format!(
455                "**Last interaction:** {}\n",
456                last.format("%Y-%m-%d %H:%M")
457            ));
458        }
459
460        if !facts.is_empty() {
461            result.push_str("\n**Facts:**\n");
462            for f in &facts {
463                let confidence_marker = if f.confidence < 1.0 {
464                    format!(
465                        " (confidence: {:.0}%, source: {})",
466                        f.confidence * 100.0,
467                        f.source
468                    )
469                } else {
470                    String::new()
471                };
472                result.push_str(&format!(
473                    "- [{}] {}: {}{}\n",
474                    f.category, f.key, f.value, confidence_marker
475                ));
476            }
477        }
478
479        Ok(result)
480    }
481
482    async fn handle_brief(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
483        let person = match self.resolve_person(args).await? {
484            Some(p) => p,
485            None => return Ok("Provide 'name', 'person_name', or 'id' for brief.".to_string()),
486        };
487        let facts = self.store.get_person_facts(person.id, None).await?;
488
489        let relationship = person.relationship.as_deref().unwrap_or("unknown");
490        let style = person
491            .communication_style
492            .as_deref()
493            .unwrap_or("not specified");
494        let language = person
495            .language_preference
496            .as_deref()
497            .unwrap_or("not specified");
498        let last = person
499            .last_interaction_at
500            .map(|d| d.format("%Y-%m-%d").to_string())
501            .unwrap_or_else(|| "none recorded".to_string());
502
503        let mut top_notes = Vec::new();
504        for f in &facts {
505            if f.category == "preference"
506                || f.category == "interest"
507                || f.category == "family"
508                || f.category == "work"
509            {
510                top_notes.push(format!("{}: {}", f.key, f.value));
511            }
512            if top_notes.len() >= 4 {
513                break;
514            }
515        }
516
517        let today = chrono::Utc::now().date_naive();
518        let next_date = facts
519            .iter()
520            .filter(|f| f.category == "birthday" || f.category == "important_date")
521            .filter_map(|f| {
522                crate::dates::days_until_anniversary(&f.value, today)
523                    .map(|d| (d, format!("{} {} ({})", f.category, f.value, f.key)))
524            })
525            .min_by_key(|(d, _)| *d);
526
527        let opener = if style.to_ascii_lowercase().contains("formal") {
528            "Use a concise, respectful opener and avoid slang."
529        } else if style.to_ascii_lowercase().contains("warm")
530            || style.to_ascii_lowercase().contains("casual")
531        {
532            "Open warmly, personal tone first, then the main point."
533        } else {
534            "Start with a friendly check-in, then move to the purpose."
535        };
536
537        let mut result = format!(
538            "**People Brief: {}**\n- Relationship: {}\n- Communication style: {}\n- Language: {}\n- Last interaction: {}\n- Total interactions: {}",
539            person.name, relationship, style, language, last, person.interaction_count
540        );
541
542        if let Some((days, detail)) = next_date {
543            let when = if days == 0 {
544                "today".to_string()
545            } else if days == 1 {
546                "tomorrow".to_string()
547            } else {
548                format!("in {} days", days)
549            };
550            result.push_str(&format!("\n- Next important date: {} ({})", detail, when));
551        }
552
553        if !top_notes.is_empty() {
554            result.push_str("\n- Useful context:");
555            for note in &top_notes {
556                result.push_str(&format!("\n  - {}", note));
557            }
558        }
559        result.push_str(&format!("\n- Suggested approach: {}", opener));
560        Ok(result)
561    }
562
563    async fn handle_upcoming(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
564        let within_days = args.within_days.unwrap_or(14).clamp(1, 365);
565        let today = chrono::Utc::now().date_naive();
566        let mut rows: Vec<(i64, Person, PersonFact)> = Vec::new();
567
568        let people = self.store.get_all_people().await?;
569        for person in people {
570            let facts = self.store.get_person_facts(person.id, None).await?;
571            for fact in facts {
572                if fact.category != "birthday" && fact.category != "important_date" {
573                    continue;
574                }
575                if let Some(days) = crate::dates::days_until_anniversary(&fact.value, today)
576                    && days >= 0
577                    && days <= within_days as i64
578                {
579                    rows.push((days, person.clone(), fact));
580                }
581            }
582        }
583
584        if rows.is_empty() {
585            return Ok(format!(
586                "No upcoming birthdays/important dates in the next {} days.",
587                within_days
588            ));
589        }
590
591        rows.sort_by_key(|(days, person, _)| (*days, person.name.clone()));
592
593        let mut result = format!(
594            "**Upcoming Dates** ({} within {} days)\n",
595            rows.len(),
596            within_days
597        );
598        for (days, person, fact) in &rows {
599            let when = if *days == i64::MAX {
600                "date format unknown".to_string()
601            } else if *days == 0 {
602                "today".to_string()
603            } else if *days == 1 {
604                "tomorrow".to_string()
605            } else {
606                format!("in {} days", days)
607            };
608            let rel = person.relationship.as_deref().unwrap_or("—");
609            result.push_str(&format!(
610                "- **{}** ({}) — [{}] {}: {} ({})\n",
611                person.name, rel, fact.category, fact.key, fact.value, when
612            ));
613        }
614        Ok(result)
615    }
616
617    async fn handle_reconnect(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
618        let inactive_days = args.inactive_days.unwrap_or(30).clamp(1, 3650);
619        let people = self
620            .store
621            .get_people_needing_reconnect(inactive_days)
622            .await?;
623        if people.is_empty() {
624            return Ok(format!(
625                "No reconnect suggestions right now (threshold: {} days).",
626                inactive_days
627            ));
628        }
629
630        let now = chrono::Utc::now();
631        let mut result = format!(
632            "**Reconnect Suggestions** ({} people, threshold: {} days)\n",
633            people.len(),
634            inactive_days
635        );
636        for p in &people {
637            let days_since = p
638                .last_interaction_at
639                .map(|d| (now - d).num_days())
640                .unwrap_or(-1);
641            let rel = p.relationship.as_deref().unwrap_or("—");
642            let style = p.communication_style.as_deref().unwrap_or("default");
643            let last = p
644                .last_interaction_at
645                .map(|d| d.format("%Y-%m-%d").to_string())
646                .unwrap_or_else(|| "unknown".to_string());
647            let nudge = if style.to_ascii_lowercase().contains("formal") {
648                "send a concise check-in"
649            } else {
650                "send a warm personal check-in"
651            };
652            result.push_str(&format!(
653                "- **{}** ({}) — last: {} (~{} days), style: {}, suggestion: {}\n",
654                p.name, rel, last, days_since, style, nudge
655            ));
656        }
657        Ok(result)
658    }
659
660    async fn handle_update(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
661        let person = if let Some(id) = args.id {
662            self.store.get_person(id).await?
663        } else if let Some(ref name) = args.name {
664            self.store.find_person_by_name(name).await?
665        } else {
666            return Ok("Provide 'name' or 'id' to update a person.".to_string());
667        };
668
669        let mut person = match person {
670            Some(p) => p,
671            None => return Ok("Person not found.".to_string()),
672        };
673
674        if let Some(ref name) = args.name
675            && args.id.is_some()
676        {
677            // Only update name if id was used to identify (name is being changed)
678            person.name = name.clone();
679        }
680        if let Some(ref rel) = args.relationship {
681            person.relationship = Some(rel.clone());
682        }
683        if let Some(ref notes) = args.notes {
684            person.notes = Some(notes.clone());
685        }
686        if let Some(ref style) = args.communication_style {
687            person.communication_style = Some(style.clone());
688        }
689        if let Some(ref lang) = args.language {
690            person.language_preference = Some(lang.clone());
691        }
692
693        self.store.upsert_person(&person).await?;
694        Ok(format!("Updated person '{}'", person.name))
695    }
696
697    async fn handle_remove(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
698        let person = if let Some(id) = args.id {
699            self.store.get_person(id).await?
700        } else if let Some(ref name) = args.name {
701            self.store.find_person_by_name(name).await?
702        } else {
703            return Ok("Provide 'name' or 'id' to remove a person.".to_string());
704        };
705
706        let person = match person {
707            Some(p) => p,
708            None => return Ok("Person not found.".to_string()),
709        };
710
711        self.store.delete_person(person.id).await?;
712        Ok(format!(
713            "Removed '{}' and all associated facts.",
714            person.name
715        ))
716    }
717
718    async fn handle_add_fact(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
719        let person_name = match &args.person_name {
720            Some(n) => n,
721            None => return Ok("Missing required field: person_name".to_string()),
722        };
723        let category = match &args.category {
724            Some(c) => c,
725            None => return Ok("Missing required field: category".to_string()),
726        };
727        let key = match &args.key {
728            Some(k) => k,
729            None => return Ok("Missing required field: key".to_string()),
730        };
731        let value = match &args.value {
732            Some(v) => v,
733            None => return Ok("Missing required field: value".to_string()),
734        };
735        if crate::dates::is_date_fact_category(category)
736            && let Some(error) = crate::dates::date_argument_error(value)
737        {
738            anyhow::bail!("Not added: {error}");
739        }
740
741        let person = match self.store.find_person_by_name(person_name).await? {
742            Some(p) => p,
743            None => {
744                return Ok(format!(
745                    "Person '{}' not found. Add them first.",
746                    person_name
747                ));
748            }
749        };
750
751        self.store
752            .upsert_person_fact(person.id, category, key, value, "agent", 1.0)
753            .await?;
754        Ok(format!(
755            "Added fact [{}/{}] = '{}' for {}",
756            category, key, value, person.name
757        ))
758    }
759
760    async fn handle_remove_fact(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
761        let fact_id = match args.fact_id {
762            Some(id) => id,
763            None => return Ok("Missing required field: fact_id".to_string()),
764        };
765
766        self.store.delete_person_fact(fact_id).await?;
767        Ok(format!("Removed fact {}", fact_id))
768    }
769
770    async fn handle_link(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
771        let person_name = match &args.person_name {
772            Some(n) => n,
773            None => return Ok("Missing required field: person_name".to_string()),
774        };
775        let platform_id = match &args.platform_id {
776            Some(p) => p,
777            None => {
778                return Ok(
779                    "Missing required field: platform_id (e.g., 'slack:U123', 'telegram:456')"
780                        .to_string(),
781                );
782            }
783        };
784        let display_name = args.display_name.as_deref().unwrap_or("");
785
786        let person = match self.store.find_person_by_name(person_name).await? {
787            Some(p) => p,
788            None => return Ok(format!("Person '{}' not found.", person_name)),
789        };
790
791        self.store
792            .link_platform_id(person.id, platform_id, display_name)
793            .await?;
794        Ok(format!(
795            "Linked platform ID '{}' to {}",
796            platform_id, person.name
797        ))
798    }
799
800    async fn handle_export(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
801        let person_name = match &args.person_name {
802            Some(n) => n,
803            None => match &args.name {
804                Some(n) => n,
805                None => return Ok("Missing required field: person_name or name".to_string()),
806            },
807        };
808
809        let person = match self.store.find_person_by_name(person_name).await? {
810            Some(p) => p,
811            None => return Ok(format!("Person '{}' not found.", person_name)),
812        };
813
814        let facts = self.store.get_person_facts(person.id, None).await?;
815        let export = json!({
816            "person": person,
817            "facts": facts,
818        });
819
820        Ok(serde_json::to_string_pretty(&export)?)
821    }
822
823    async fn handle_purge(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
824        let person_name = match &args.person_name {
825            Some(n) => n,
826            None => match &args.name {
827                Some(n) => n,
828                None => return Ok("Missing required field: person_name or name".to_string()),
829            },
830        };
831
832        let person = match self.store.find_person_by_name(person_name).await? {
833            Some(p) => p,
834            None => return Ok(format!("Person '{}' not found.", person_name)),
835        };
836
837        let facts = self.store.get_person_facts(person.id, None).await?;
838        self.store.delete_person(person.id).await?;
839        Ok(format!(
840            "Purged '{}': deleted person record + {} facts + all platform links.",
841            person.name,
842            facts.len()
843        ))
844    }
845
846    async fn handle_audit(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
847        if let Some(ref name) = args.person_name.as_ref().or(args.name.as_ref()) {
848            let person = match self.store.find_person_by_name(name).await? {
849                Some(p) => p,
850                None => return Ok(format!("Person '{}' not found.", name)),
851            };
852
853            let facts = self.store.get_person_facts(person.id, None).await?;
854            let auto_facts: Vec<&PersonFact> =
855                facts.iter().filter(|f| f.confidence < 1.0).collect();
856
857            if auto_facts.is_empty() {
858                return Ok(format!(
859                    "No auto-extracted facts for {}. All facts are owner-verified.",
860                    person.name
861                ));
862            }
863
864            let mut result = format!(
865                "**Auto-extracted facts for {}** ({} unverified)\n",
866                person.name,
867                auto_facts.len()
868            );
869            for f in auto_facts {
870                result.push_str(&format!(
871                    "- [ID: {}] [{}/{}] = '{}' (confidence: {:.0}%, source: {})\n",
872                    f.id,
873                    f.category,
874                    f.key,
875                    f.value,
876                    f.confidence * 100.0,
877                    f.source
878                ));
879            }
880            result.push_str("\nUse `confirm` with `fact_id` to verify a fact.");
881            Ok(result)
882        } else {
883            // Audit all people
884            let people = self.store.get_all_people().await?;
885            let mut total_unverified = 0;
886            let mut result = String::from("**Audit Summary**\n");
887
888            for p in &people {
889                let facts = self.store.get_person_facts(p.id, None).await?;
890                let unverified = facts.iter().filter(|f| f.confidence < 1.0).count();
891                if unverified > 0 {
892                    result.push_str(&format!(
893                        "- **{}**: {} unverified facts\n",
894                        p.name, unverified
895                    ));
896                    total_unverified += unverified;
897                }
898            }
899
900            if total_unverified == 0 {
901                return Ok("All people facts are verified.".to_string());
902            }
903            result.push_str(&format!(
904                "\nTotal: {} unverified facts across all people.",
905                total_unverified
906            ));
907            Ok(result)
908        }
909    }
910
911    async fn handle_confirm(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
912        let fact_id = match args.fact_id {
913            Some(id) => id,
914            None => return Ok("Missing required field: fact_id".to_string()),
915        };
916
917        self.store.confirm_person_fact(fact_id).await?;
918        Ok(format!(
919            "Confirmed fact {} (confidence set to 100%, source set to 'owner').",
920            fact_id
921        ))
922    }
923
924    async fn is_people_enabled(&self) -> bool {
925        self.settings
926            .get_setting("people_enabled")
927            .await
928            .ok()
929            .flatten()
930            .as_deref()
931            == Some("true")
932    }
933
934    async fn handle_enable(&self) -> anyhow::Result<String> {
935        self.settings.set_setting("people_enabled", "true").await?;
936        Ok("People Intelligence enabled. I'll now track contacts, learn about people you mention, and provide proactive social reminders.".to_string())
937    }
938
939    async fn handle_disable(&self) -> anyhow::Result<String> {
940        self.settings.set_setting("people_enabled", "false").await?;
941        Ok("People Intelligence disabled. All existing data is preserved — use 'enable' to turn it back on.".to_string())
942    }
943
944    async fn handle_status(&self) -> anyhow::Result<String> {
945        let enabled = self.is_people_enabled().await;
946        let people_count = self.store.get_all_people().await.unwrap_or_default().len();
947        let canonical = self
948            .store
949            .get_canonical_memory_facts()
950            .await
951            .unwrap_or_default();
952        let relationship_edges = canonical
953            .iter()
954            .filter(|fact| fact.category == "relationships")
955            .count();
956        let canonical_attributes = canonical.len().saturating_sub(relationship_edges);
957        Ok(format!(
958            "Legacy People Intelligence: **{}**\n\
959             Legacy contact records: {}\n\
960             Structured personal memory: {} active facts/aliases, {} active directed relationship edges\n\
961             These are separate compatibility layers. Do not describe legacy contact rows as populated structured graph edges.",
962            if enabled { "enabled" } else { "disabled" },
963            people_count,
964            canonical_attributes,
965            relationship_edges,
966        ))
967    }
968}
969
970#[cfg(test)]
971mod tests {
972    use super::*;
973    use crate::full::tools::test_support::{Settings, ToolCalls as _, memory};
974    use aidaemon_tools::semantics::ToolSemantics;
975
976    /// The people store is the agent's own; the enable/disable setting and
977    /// `link` (which widens who sees a person's facts) stay undeclared.
978    #[tokio::test]
979    async fn people_store_actions_declare_no_effects() {
980        let tool = setup_tool().await;
981        let effects = |action: &str| tool.call_effects(&json!({"action": action}).to_string());
982        for action in [
983            "add", "update", "remove", "add_fact", "purge", "export", "view",
984        ] {
985            assert_eq!(
986                effects(action),
987                aidaemon_core::CallEffects::none(),
988                "{action}"
989            );
990        }
991        for action in ["enable", "disable", "link", "unknown"] {
992            assert!(!effects(action).complete, "{action}");
993        }
994    }
995
996    /// `remember` writes structured personal memory, the store recall
997    /// projects into the owner's facts, and works with the contacts book off.
998    #[tokio::test]
999    async fn remember_writes_personal_memory_that_recall_reads_with_people_off() {
1000        let settings = Arc::new(Settings::default());
1001        settings
1002            .set_setting("people_enabled", "false")
1003            .await
1004            .unwrap();
1005        let store = memory().await;
1006        let tool = ManagePeopleTool::new(settings, store.clone());
1007        let args = json!({
1008            "action": "remember",
1009            "personal_memory": {
1010                "entities": [
1011                    {"local_id": "owner", "entity_type": "person", "canonical_name": "Owner"},
1012                    {"local_id": "mia", "entity_type": "person", "canonical_name": "Mia"}
1013                ],
1014                "facts": [{"subject_local_id": "mia", "predicate": "birthday", "value": "2019-04-02"}],
1015                "relationships": [{"source_local_id": "owner", "relationship_type": "PARENT_OF", "target_local_id": "mia"}]
1016            }
1017        });
1018        let out = tool.call(&args.to_string()).await.unwrap();
1019        assert!(out.starts_with("Personal memory:"), "{out}");
1020        assert!(
1021            tool.call_semantics(&args.to_string())
1022                .mutation_effects
1023                .satisfies(ToolMutationEffects::MEMORY_WRITE)
1024        );
1025        assert_eq!(
1026            tool.call_effects(&args.to_string()),
1027            aidaemon_core::CallEffects::none()
1028        );
1029        let canonical = crate::stores::FactStore::get_canonical_memory_facts(store.as_ref())
1030            .await
1031            .unwrap();
1032        assert!(
1033            canonical
1034                .iter()
1035                .any(|fact| fact.key.contains("Mia") && fact.value == "2019-04-02"),
1036            "{canonical:?}"
1037        );
1038
1039        let empty = tool
1040            .call(&json!({"action": "remember", "personal_memory": {}}).to_string())
1041            .await
1042            .unwrap();
1043        assert!(empty.starts_with("Missing required field"), "{empty}");
1044    }
1045
1046    async fn setup_tool() -> ManagePeopleTool {
1047        let settings = Arc::new(Settings::default());
1048        settings
1049            .set_setting("people_enabled", "true")
1050            .await
1051            .unwrap();
1052        ManagePeopleTool::new(settings, memory().await)
1053    }
1054
1055    #[tokio::test]
1056    async fn status_distinguishes_legacy_people_from_structured_edges() {
1057        let tool = setup_tool().await;
1058        let result = tool
1059            .call(&json!({"action": "status"}).to_string())
1060            .await
1061            .unwrap();
1062        assert!(result.contains("Legacy contact records:"));
1063        assert!(result.contains("active directed relationship edges"));
1064        assert!(result.contains("separate compatibility layers"));
1065    }
1066
1067    #[tokio::test]
1068    async fn an_ambiguous_date_is_refused() {
1069        let tool = setup_tool().await;
1070        tool.call(&json!({"action": "add", "name": "Alice Rivera"}).to_string())
1071            .await
1072            .unwrap();
1073        for value in ["05/03", "May 3", "05-03"] {
1074            let refused = tool
1075                .call(
1076                    &json!({
1077                        "action": "add_fact",
1078                        "person_name": "Alice Rivera",
1079                        "category": "birthday",
1080                        "key": "birthday",
1081                        "value": value
1082                    })
1083                    .to_string(),
1084                )
1085                .await;
1086            let error = refused.expect_err(value).to_string();
1087            assert!(error.contains("YYYY-MM-DD"), "{value}: {error}");
1088        }
1089        let added = tool
1090            .call(
1091                &json!({
1092                    "action": "add_fact",
1093                    "person_name": "Alice Rivera",
1094                    "category": "birthday",
1095                    "key": "birthday",
1096                    "value": "--05-03"
1097                })
1098                .to_string(),
1099            )
1100            .await
1101            .unwrap();
1102        assert!(added.contains("Added fact"), "{added}");
1103    }
1104
1105    #[tokio::test]
1106    async fn upcoming_lists_people_with_dates() {
1107        let tool = setup_tool().await;
1108
1109        let add_result = tool
1110            .call(
1111                &json!({
1112                    "action": "add",
1113                    "name": "Alice",
1114                    "relationship": "friend"
1115                })
1116                .to_string(),
1117            )
1118            .await
1119            .unwrap();
1120        assert!(
1121            add_result.contains("Added person"),
1122            "unexpected add output: {}",
1123            add_result
1124        );
1125
1126        let upcoming = chrono::Utc::now().date_naive() + chrono::Duration::days(2);
1127        let date_value = upcoming.format("--%m-%d").to_string();
1128        let add_fact_result = tool
1129            .call(
1130                &json!({
1131                    "action": "add_fact",
1132                    "person_name": "Alice",
1133                    "category": "birthday",
1134                    "key": "birthday",
1135                    "value": date_value
1136                })
1137                .to_string(),
1138            )
1139            .await
1140            .unwrap();
1141        assert!(
1142            add_fact_result.contains("Added fact"),
1143            "unexpected add_fact output: {}",
1144            add_fact_result
1145        );
1146
1147        let result = tool
1148            .call(
1149                &json!({
1150                    "action": "upcoming",
1151                    "within_days": 7
1152                })
1153                .to_string(),
1154            )
1155            .await
1156            .unwrap();
1157        assert!(
1158            result.contains("Upcoming Dates"),
1159            "unexpected upcoming output: {}",
1160            result
1161        );
1162        assert!(
1163            result.contains("Alice"),
1164            "unexpected upcoming output: {}",
1165            result
1166        );
1167    }
1168
1169    #[tokio::test]
1170    async fn reconnect_lists_inactive_people() {
1171        let tool = setup_tool().await;
1172
1173        tool.call(
1174            &json!({
1175                "action": "add",
1176                "name": "Bob",
1177                "relationship": "friend",
1178                "communication_style": "warm"
1179            })
1180            .to_string(),
1181        )
1182        .await
1183        .unwrap();
1184        tool.call(
1185            &json!({
1186                "action": "link",
1187                "person_name": "Bob",
1188                "platform_id": "slack:U_BOB",
1189                "display_name": "bob"
1190            })
1191            .to_string(),
1192        )
1193        .await
1194        .unwrap();
1195
1196        // Touch interaction now; with inactive_days=1 this should not show.
1197        // Use the state method via the tool boundary by resolving person brief,
1198        // then calling reconnect with a low threshold to validate output shape.
1199        let brief = tool
1200            .call(
1201                &json!({
1202                    "action": "brief",
1203                    "name": "Bob"
1204                })
1205                .to_string(),
1206            )
1207            .await
1208            .unwrap();
1209        assert!(brief.contains("People Brief: Bob"));
1210
1211        let result = tool
1212            .call(
1213                &json!({
1214                    "action": "reconnect",
1215                    "inactive_days": 1
1216                })
1217                .to_string(),
1218            )
1219            .await
1220            .unwrap();
1221        // Might be empty depending on interaction timestamps; assert stable text contract.
1222        assert!(
1223            result.contains("Reconnect Suggestions")
1224                || result.contains("No reconnect suggestions right now")
1225        );
1226    }
1227
1228    #[tokio::test]
1229    async fn brief_includes_core_guidance() {
1230        let tool = setup_tool().await;
1231        tool.call(
1232            &json!({
1233                "action": "add",
1234                "name": "Carol",
1235                "relationship": "coworker",
1236                "communication_style": "formal",
1237                "language": "English"
1238            })
1239            .to_string(),
1240        )
1241        .await
1242        .unwrap();
1243        tool.call(
1244            &json!({
1245                "action": "add_fact",
1246                "person_name": "Carol",
1247                "category": "work",
1248                "key": "role",
1249                "value": "Engineering Manager"
1250            })
1251            .to_string(),
1252        )
1253        .await
1254        .unwrap();
1255
1256        let result = tool
1257            .call(
1258                &json!({
1259                    "action": "brief",
1260                    "name": "Carol"
1261                })
1262                .to_string(),
1263            )
1264            .await
1265            .unwrap();
1266        assert!(result.contains("People Brief: Carol"));
1267        assert!(result.contains("Suggested approach"));
1268    }
1269}