aidaemon 0.11.10

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use chrono::Datelike;
use serde::Deserialize;
use serde_json::{json, Value};

use crate::traits::{Person, PersonFact, StateStore, Tool, ToolCapabilities};

pub struct ManagePeopleTool {
    state: Arc<dyn StateStore>,
}

impl ManagePeopleTool {
    pub fn new(state: Arc<dyn StateStore>) -> Self {
        Self { state }
    }
}

#[derive(Deserialize)]
struct ManagePeopleArgs {
    action: String,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    id: Option<i64>,
    #[serde(default)]
    relationship: Option<String>,
    #[serde(default)]
    notes: Option<String>,
    #[serde(default)]
    communication_style: Option<String>,
    #[serde(default)]
    language: Option<String>,
    #[serde(default)]
    category: Option<String>,
    #[serde(default)]
    key: Option<String>,
    #[serde(default)]
    value: Option<String>,
    #[serde(default)]
    person_name: Option<String>,
    #[serde(default)]
    platform_id: Option<String>,
    #[serde(default)]
    fact_id: Option<i64>,
    #[serde(default)]
    display_name: Option<String>,
    #[serde(default)]
    within_days: Option<i32>,
    #[serde(default)]
    inactive_days: Option<u32>,
}

fn manage_people_schema() -> Value {
    json!({
        "name": "manage_people",
        "description": "Owner's contacts: people, relationships, facts. Use add_fact to store new info.",
        "parameters": {
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["enable", "disable", "status", "add", "list", "view", "brief", "upcoming", "reconnect", "update", "remove", "add_fact", "remove_fact", "link", "export", "purge", "audit", "confirm"]
                },
                "name": { "type": "string" },
                "id": { "type": "integer" },
                "relationship": { "type": "string" },
                "notes": { "type": "string" },
                "communication_style": { "type": "string" },
                "language": { "type": "string" },
                "person_name": { "type": "string", "description": "Person for add_fact/remove_fact/link" },
                "category": { "type": "string", "description": "Fact category; avoid health/finance" },
                "key": { "type": "string" },
                "value": { "type": "string" },
                "platform_id": { "type": "string" },
                "display_name": { "type": "string" },
                "fact_id": { "type": "integer" },
                "within_days": { "type": "integer", "description": "days ahead" },
                "inactive_days": { "type": "integer" }
            },
            "required": ["action"],
            "additionalProperties": false
        }
    })
}

#[async_trait]
impl Tool for ManagePeopleTool {
    fn name(&self) -> &str {
        "manage_people"
    }

    fn description(&self) -> &str {
        "Manage the owner's contacts and social circle. Track people, their preferences, relationships, and important dates."
    }

    fn schema(&self) -> Value {
        manage_people_schema()
    }

    async fn call(&self, arguments: &str) -> anyhow::Result<String> {
        let args: ManagePeopleArgs = serde_json::from_str(arguments)?;

        // Toggle actions are always allowed regardless of enabled state
        match args.action.as_str() {
            "enable" => return self.handle_enable().await,
            "disable" => return self.handle_disable().await,
            "status" => return self.handle_status().await,
            _ => {}
        }

        // Gate all other actions behind the runtime setting
        if !self.is_people_enabled().await {
            return Ok(
                "People Intelligence is disabled. Use action 'enable' to turn it on.".to_string(),
            );
        }

        match args.action.as_str() {
            "add" => self.handle_add(&args).await,
            "list" => self.handle_list(&args).await,
            "view" => self.handle_view(&args).await,
            "brief" => self.handle_brief(&args).await,
            "upcoming" => self.handle_upcoming(&args).await,
            "reconnect" => self.handle_reconnect(&args).await,
            "update" => self.handle_update(&args).await,
            "remove" => self.handle_remove(&args).await,
            "add_fact" => self.handle_add_fact(&args).await,
            "remove_fact" => self.handle_remove_fact(&args).await,
            "link" => self.handle_link(&args).await,
            "export" => self.handle_export(&args).await,
            "purge" => self.handle_purge(&args).await,
            "audit" => self.handle_audit(&args).await,
            "confirm" => self.handle_confirm(&args).await,
            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)),
        }
    }

    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities {
            read_only: false,
            external_side_effect: false,
            needs_approval: true,
            idempotent: false,
            high_impact_write: false,
        }
    }
}

impl ManagePeopleTool {
    fn days_until_date(value: &str, today: chrono::NaiveDate) -> Option<i64> {
        use chrono::NaiveDate;
        let trimmed = value.trim();

        // Build the anniversary date directly from (current year, month, day)
        // rather than mutating `today`. Mutating `today` breaks when today's
        // day-of-month (e.g. the 31st) does not exist in the target month
        // (e.g. June), causing `with_month` to return None for valid dates.
        let anniversary_days = |month: u32, day: u32| -> Option<i64> {
            let this_year = NaiveDate::from_ymd_opt(today.year(), month, day)?;
            let diff = (this_year - today).num_days();
            Some(if diff < 0 { diff + 365 } else { diff })
        };

        if let Ok(d) = NaiveDate::parse_from_str(trimmed, "%Y-%m-%d") {
            return anniversary_days(d.month(), d.day());
        }

        if let Ok(d) = NaiveDate::parse_from_str(&format!("2000-{}", trimmed), "%Y-%m-%d") {
            return anniversary_days(d.month(), d.day());
        }
        if let Ok(d) = NaiveDate::parse_from_str(&format!("2000/{}", trimmed), "%Y/%m/%d") {
            return anniversary_days(d.month(), d.day());
        }

        let months = [
            ("january", 1),
            ("february", 2),
            ("march", 3),
            ("april", 4),
            ("may", 5),
            ("june", 6),
            ("july", 7),
            ("august", 8),
            ("september", 9),
            ("october", 10),
            ("november", 11),
            ("december", 12),
        ];
        let lower = trimmed.to_lowercase();
        for (name, num) in &months {
            if let Some(rest) = lower.strip_prefix(name) {
                let rest = rest.trim().trim_start_matches([',', ' ']);
                if let Ok(day) = rest.parse::<u32>() {
                    return anniversary_days(*num, day);
                }
            }
        }
        None
    }

    async fn resolve_person(&self, args: &ManagePeopleArgs) -> anyhow::Result<Option<Person>> {
        if let Some(id) = args.id {
            return self.state.get_person(id).await;
        }
        if let Some(ref name) = args.name {
            return self.state.find_person_by_name(name).await;
        }
        if let Some(ref person_name) = args.person_name {
            return self.state.find_person_by_name(person_name).await;
        }
        Ok(None)
    }

    async fn handle_add(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let name = match &args.name {
            Some(n) => n.clone(),
            None => return Ok("Missing required field: name".to_string()),
        };

        let person = Person {
            id: 0,
            name: name.clone(),
            aliases: vec![],
            relationship: args.relationship.clone(),
            platform_ids: HashMap::new(),
            notes: args.notes.clone(),
            communication_style: args.communication_style.clone(),
            language_preference: args.language.clone(),
            last_interaction_at: None,
            interaction_count: 0,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        };

        let id = self.state.upsert_person(&person).await?;
        Ok(format!("Added person '{}' with ID {}", name, id))
    }

    async fn handle_list(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let people = self.state.get_all_people().await?;
        if people.is_empty() {
            return Ok("No people tracked yet.".to_string());
        }

        let mut result = format!("**People** ({} total)\n", people.len());
        for p in &people {
            let rel = p.relationship.as_deref().unwrap_or("—");
            let style = p.communication_style.as_deref().unwrap_or("—");
            let interaction_info = if p.interaction_count > 0 {
                format!(", {} interactions", p.interaction_count)
            } else {
                String::new()
            };

            // Filter by relationship if specified
            if let Some(ref filter) = args.relationship {
                if p.relationship.as_deref() != Some(filter.as_str()) {
                    continue;
                }
            }

            result.push_str(&format!(
                "- **{}** (ID: {}) — {} | style: {}{}\n",
                p.name, p.id, rel, style, interaction_info
            ));
        }
        Ok(result)
    }

    async fn handle_view(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person = if let Some(id) = args.id {
            self.state.get_person(id).await?
        } else if let Some(ref name) = args.name {
            self.state.find_person_by_name(name).await?
        } else {
            return Ok("Provide 'name' or 'id' to view a person.".to_string());
        };

        let person = match person {
            Some(p) => p,
            None => return Ok("Person not found.".to_string()),
        };

        let facts = self.state.get_person_facts(person.id, None).await?;
        let mut result = format!("## {}", person.name);
        if let Some(ref rel) = person.relationship {
            result.push_str(&format!(" ({})", rel));
        }
        result.push('\n');

        if !person.aliases.is_empty() {
            result.push_str(&format!("**Aliases:** {}\n", person.aliases.join(", ")));
        }
        if let Some(ref style) = person.communication_style {
            result.push_str(&format!("**Communication style:** {}\n", style));
        }
        if let Some(ref lang) = person.language_preference {
            result.push_str(&format!("**Language:** {}\n", lang));
        }
        if !person.platform_ids.is_empty() {
            let ids: Vec<String> = person
                .platform_ids
                .iter()
                .map(|(k, v)| format!("{} ({})", k, v))
                .collect();
            result.push_str(&format!("**Platform IDs:** {}\n", ids.join(", ")));
        }
        if let Some(ref notes) = person.notes {
            result.push_str(&format!("**Notes:** {}\n", notes));
        }
        result.push_str(&format!("**Interactions:** {}\n", person.interaction_count));
        if let Some(ref last) = person.last_interaction_at {
            result.push_str(&format!(
                "**Last interaction:** {}\n",
                last.format("%Y-%m-%d %H:%M")
            ));
        }

        if !facts.is_empty() {
            result.push_str("\n**Facts:**\n");
            for f in &facts {
                let confidence_marker = if f.confidence < 1.0 {
                    format!(
                        " (confidence: {:.0}%, source: {})",
                        f.confidence * 100.0,
                        f.source
                    )
                } else {
                    String::new()
                };
                result.push_str(&format!(
                    "- [{}] {}: {}{}\n",
                    f.category, f.key, f.value, confidence_marker
                ));
            }
        }

        Ok(result)
    }

    async fn handle_brief(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person = match self.resolve_person(args).await? {
            Some(p) => p,
            None => return Ok("Provide 'name', 'person_name', or 'id' for brief.".to_string()),
        };
        let facts = self.state.get_person_facts(person.id, None).await?;

        let relationship = person.relationship.as_deref().unwrap_or("unknown");
        let style = person
            .communication_style
            .as_deref()
            .unwrap_or("not specified");
        let language = person
            .language_preference
            .as_deref()
            .unwrap_or("not specified");
        let last = person
            .last_interaction_at
            .map(|d| d.format("%Y-%m-%d").to_string())
            .unwrap_or_else(|| "none recorded".to_string());

        let mut top_notes = Vec::new();
        for f in &facts {
            if f.category == "preference"
                || f.category == "interest"
                || f.category == "family"
                || f.category == "work"
            {
                top_notes.push(format!("{}: {}", f.key, f.value));
            }
            if top_notes.len() >= 4 {
                break;
            }
        }

        let today = chrono::Utc::now().date_naive();
        let next_date = facts
            .iter()
            .filter(|f| f.category == "birthday" || f.category == "important_date")
            .filter_map(|f| {
                Self::days_until_date(&f.value, today)
                    .map(|d| (d, format!("{} {} ({})", f.category, f.value, f.key)))
            })
            .min_by_key(|(d, _)| *d);

        let opener = if style.to_ascii_lowercase().contains("formal") {
            "Use a concise, respectful opener and avoid slang."
        } else if style.to_ascii_lowercase().contains("warm")
            || style.to_ascii_lowercase().contains("casual")
        {
            "Open warmly, personal tone first, then the main point."
        } else {
            "Start with a friendly check-in, then move to the purpose."
        };

        let mut result = format!(
            "**People Brief: {}**\n- Relationship: {}\n- Communication style: {}\n- Language: {}\n- Last interaction: {}\n- Total interactions: {}",
            person.name, relationship, style, language, last, person.interaction_count
        );

        if let Some((days, detail)) = next_date {
            let when = if days == 0 {
                "today".to_string()
            } else if days == 1 {
                "tomorrow".to_string()
            } else {
                format!("in {} days", days)
            };
            result.push_str(&format!("\n- Next important date: {} ({})", detail, when));
        }

        if !top_notes.is_empty() {
            result.push_str("\n- Useful context:");
            for note in &top_notes {
                result.push_str(&format!("\n  - {}", note));
            }
        }
        result.push_str(&format!("\n- Suggested approach: {}", opener));
        Ok(result)
    }

    async fn handle_upcoming(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let within_days = args.within_days.unwrap_or(14).clamp(1, 365);
        let today = chrono::Utc::now().date_naive();
        let mut rows: Vec<(i64, Person, PersonFact)> = Vec::new();

        let people = self.state.get_all_people().await?;
        for person in people {
            let facts = self.state.get_person_facts(person.id, None).await?;
            for fact in facts {
                if fact.category != "birthday" && fact.category != "important_date" {
                    continue;
                }
                if let Some(days) = Self::days_until_date(&fact.value, today) {
                    if days >= 0 && days <= within_days as i64 {
                        rows.push((days, person.clone(), fact));
                    }
                }
            }
        }

        if rows.is_empty() {
            return Ok(format!(
                "No upcoming birthdays/important dates in the next {} days.",
                within_days
            ));
        }

        rows.sort_by_key(|(days, person, _)| (*days, person.name.clone()));

        let mut result = format!(
            "**Upcoming Dates** ({} within {} days)\n",
            rows.len(),
            within_days
        );
        for (days, person, fact) in &rows {
            let when = if *days == i64::MAX {
                "date format unknown".to_string()
            } else if *days == 0 {
                "today".to_string()
            } else if *days == 1 {
                "tomorrow".to_string()
            } else {
                format!("in {} days", days)
            };
            let rel = person.relationship.as_deref().unwrap_or("—");
            result.push_str(&format!(
                "- **{}** ({}) — [{}] {}: {} ({})\n",
                person.name, rel, fact.category, fact.key, fact.value, when
            ));
        }
        Ok(result)
    }

    async fn handle_reconnect(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let inactive_days = args.inactive_days.unwrap_or(30).clamp(1, 3650);
        let people = self
            .state
            .get_people_needing_reconnect(inactive_days)
            .await?;
        if people.is_empty() {
            return Ok(format!(
                "No reconnect suggestions right now (threshold: {} days).",
                inactive_days
            ));
        }

        let now = chrono::Utc::now();
        let mut result = format!(
            "**Reconnect Suggestions** ({} people, threshold: {} days)\n",
            people.len(),
            inactive_days
        );
        for p in &people {
            let days_since = p
                .last_interaction_at
                .map(|d| (now - d).num_days())
                .unwrap_or(-1);
            let rel = p.relationship.as_deref().unwrap_or("—");
            let style = p.communication_style.as_deref().unwrap_or("default");
            let last = p
                .last_interaction_at
                .map(|d| d.format("%Y-%m-%d").to_string())
                .unwrap_or_else(|| "unknown".to_string());
            let nudge = if style.to_ascii_lowercase().contains("formal") {
                "send a concise check-in"
            } else {
                "send a warm personal check-in"
            };
            result.push_str(&format!(
                "- **{}** ({}) — last: {} (~{} days), style: {}, suggestion: {}\n",
                p.name, rel, last, days_since, style, nudge
            ));
        }
        Ok(result)
    }

    async fn handle_update(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person = if let Some(id) = args.id {
            self.state.get_person(id).await?
        } else if let Some(ref name) = args.name {
            self.state.find_person_by_name(name).await?
        } else {
            return Ok("Provide 'name' or 'id' to update a person.".to_string());
        };

        let mut person = match person {
            Some(p) => p,
            None => return Ok("Person not found.".to_string()),
        };

        if let Some(ref name) = args.name {
            if args.id.is_some() {
                // Only update name if id was used to identify (name is being changed)
                person.name = name.clone();
            }
        }
        if let Some(ref rel) = args.relationship {
            person.relationship = Some(rel.clone());
        }
        if let Some(ref notes) = args.notes {
            person.notes = Some(notes.clone());
        }
        if let Some(ref style) = args.communication_style {
            person.communication_style = Some(style.clone());
        }
        if let Some(ref lang) = args.language {
            person.language_preference = Some(lang.clone());
        }

        self.state.upsert_person(&person).await?;
        Ok(format!("Updated person '{}'", person.name))
    }

    async fn handle_remove(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person = if let Some(id) = args.id {
            self.state.get_person(id).await?
        } else if let Some(ref name) = args.name {
            self.state.find_person_by_name(name).await?
        } else {
            return Ok("Provide 'name' or 'id' to remove a person.".to_string());
        };

        let person = match person {
            Some(p) => p,
            None => return Ok("Person not found.".to_string()),
        };

        self.state.delete_person(person.id).await?;
        Ok(format!(
            "Removed '{}' and all associated facts.",
            person.name
        ))
    }

    async fn handle_add_fact(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person_name = match &args.person_name {
            Some(n) => n,
            None => return Ok("Missing required field: person_name".to_string()),
        };
        let category = match &args.category {
            Some(c) => c,
            None => return Ok("Missing required field: category".to_string()),
        };
        let key = match &args.key {
            Some(k) => k,
            None => return Ok("Missing required field: key".to_string()),
        };
        let value = match &args.value {
            Some(v) => v,
            None => return Ok("Missing required field: value".to_string()),
        };

        let person = match self.state.find_person_by_name(person_name).await? {
            Some(p) => p,
            None => {
                return Ok(format!(
                    "Person '{}' not found. Add them first.",
                    person_name
                ))
            }
        };

        self.state
            .upsert_person_fact(person.id, category, key, value, "agent", 1.0)
            .await?;
        Ok(format!(
            "Added fact [{}/{}] = '{}' for {}",
            category, key, value, person.name
        ))
    }

    async fn handle_remove_fact(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let fact_id = match args.fact_id {
            Some(id) => id,
            None => return Ok("Missing required field: fact_id".to_string()),
        };

        self.state.delete_person_fact(fact_id).await?;
        Ok(format!("Removed fact {}", fact_id))
    }

    async fn handle_link(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person_name = match &args.person_name {
            Some(n) => n,
            None => return Ok("Missing required field: person_name".to_string()),
        };
        let platform_id = match &args.platform_id {
            Some(p) => p,
            None => {
                return Ok(
                    "Missing required field: platform_id (e.g., 'slack:U123', 'telegram:456')"
                        .to_string(),
                )
            }
        };
        let display_name = args.display_name.as_deref().unwrap_or("");

        let person = match self.state.find_person_by_name(person_name).await? {
            Some(p) => p,
            None => return Ok(format!("Person '{}' not found.", person_name)),
        };

        self.state
            .link_platform_id(person.id, platform_id, display_name)
            .await?;
        Ok(format!(
            "Linked platform ID '{}' to {}",
            platform_id, person.name
        ))
    }

    async fn handle_export(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person_name = match &args.person_name {
            Some(n) => n,
            None => match &args.name {
                Some(n) => n,
                None => return Ok("Missing required field: person_name or name".to_string()),
            },
        };

        let person = match self.state.find_person_by_name(person_name).await? {
            Some(p) => p,
            None => return Ok(format!("Person '{}' not found.", person_name)),
        };

        let facts = self.state.get_person_facts(person.id, None).await?;
        let export = json!({
            "person": person,
            "facts": facts,
        });

        Ok(serde_json::to_string_pretty(&export)?)
    }

    async fn handle_purge(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let person_name = match &args.person_name {
            Some(n) => n,
            None => match &args.name {
                Some(n) => n,
                None => return Ok("Missing required field: person_name or name".to_string()),
            },
        };

        let person = match self.state.find_person_by_name(person_name).await? {
            Some(p) => p,
            None => return Ok(format!("Person '{}' not found.", person_name)),
        };

        let facts = self.state.get_person_facts(person.id, None).await?;
        self.state.delete_person(person.id).await?;
        Ok(format!(
            "Purged '{}': deleted person record + {} facts + all platform links.",
            person.name,
            facts.len()
        ))
    }

    async fn handle_audit(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        if let Some(ref name) = args.person_name.as_ref().or(args.name.as_ref()) {
            let person = match self.state.find_person_by_name(name).await? {
                Some(p) => p,
                None => return Ok(format!("Person '{}' not found.", name)),
            };

            let facts = self.state.get_person_facts(person.id, None).await?;
            let auto_facts: Vec<&PersonFact> =
                facts.iter().filter(|f| f.confidence < 1.0).collect();

            if auto_facts.is_empty() {
                return Ok(format!(
                    "No auto-extracted facts for {}. All facts are owner-verified.",
                    person.name
                ));
            }

            let mut result = format!(
                "**Auto-extracted facts for {}** ({} unverified)\n",
                person.name,
                auto_facts.len()
            );
            for f in auto_facts {
                result.push_str(&format!(
                    "- [ID: {}] [{}/{}] = '{}' (confidence: {:.0}%, source: {})\n",
                    f.id,
                    f.category,
                    f.key,
                    f.value,
                    f.confidence * 100.0,
                    f.source
                ));
            }
            result.push_str("\nUse `confirm` with `fact_id` to verify a fact.");
            Ok(result)
        } else {
            // Audit all people
            let people = self.state.get_all_people().await?;
            let mut total_unverified = 0;
            let mut result = String::from("**Audit Summary**\n");

            for p in &people {
                let facts = self.state.get_person_facts(p.id, None).await?;
                let unverified = facts.iter().filter(|f| f.confidence < 1.0).count();
                if unverified > 0 {
                    result.push_str(&format!(
                        "- **{}**: {} unverified facts\n",
                        p.name, unverified
                    ));
                    total_unverified += unverified;
                }
            }

            if total_unverified == 0 {
                return Ok("All people facts are verified.".to_string());
            }
            result.push_str(&format!(
                "\nTotal: {} unverified facts across all people.",
                total_unverified
            ));
            Ok(result)
        }
    }

    async fn handle_confirm(&self, args: &ManagePeopleArgs) -> anyhow::Result<String> {
        let fact_id = match args.fact_id {
            Some(id) => id,
            None => return Ok("Missing required field: fact_id".to_string()),
        };

        self.state.confirm_person_fact(fact_id).await?;
        Ok(format!(
            "Confirmed fact {} (confidence set to 100%, source set to 'owner').",
            fact_id
        ))
    }

    async fn is_people_enabled(&self) -> bool {
        self.state
            .get_setting("people_enabled")
            .await
            .ok()
            .flatten()
            .as_deref()
            == Some("true")
    }

    async fn handle_enable(&self) -> anyhow::Result<String> {
        self.state.set_setting("people_enabled", "true").await?;
        Ok("People Intelligence enabled. I'll now track contacts, learn about people you mention, and provide proactive social reminders.".to_string())
    }

    async fn handle_disable(&self) -> anyhow::Result<String> {
        self.state.set_setting("people_enabled", "false").await?;
        Ok("People Intelligence disabled. All existing data is preserved — use 'enable' to turn it back on.".to_string())
    }

    async fn handle_status(&self) -> anyhow::Result<String> {
        let enabled = self.is_people_enabled().await;
        let people_count = self.state.get_all_people().await.unwrap_or_default().len();
        Ok(format!(
            "People Intelligence: **{}**\nPeople tracked: {}",
            if enabled { "enabled" } else { "disabled" },
            people_count
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::embeddings::EmbeddingService;
    use crate::state::SqliteStateStore;
    use crate::traits::store_prelude::*;

    #[test]
    fn schema_fits_payload_budget() {
        // Pillar C of 2026-06-06-cross-turn-prefix-stability-design.md:
        // admin-tool schemas ride in EVERY provider call; this ceiling is the
        // per-tool payload budget. If you trip this assert by adding features,
        // compress the description text — do not raise the ceiling without
        // updating the Pillar C implementation plan.
        let bytes = serde_json::to_string(&manage_people_schema())
            .unwrap()
            .len();
        assert!(
            bytes <= 1000,
            "manage_people schema is {bytes} bytes, budget is 1000"
        );
    }

    async fn setup_tool() -> ManagePeopleTool {
        let db_file = tempfile::NamedTempFile::new().unwrap();
        let db_path = db_file.path().to_str().unwrap().to_string();
        let embedding_service = Arc::new(EmbeddingService::new().unwrap());
        let state = Arc::new(
            SqliteStateStore::new(&db_path, 100, None, embedding_service)
                .await
                .unwrap(),
        );
        state.set_setting("people_enabled", "true").await.unwrap();
        std::mem::forget(db_file);
        ManagePeopleTool::new(state as Arc<dyn StateStore>)
    }

    #[tokio::test]
    async fn upcoming_lists_people_with_dates() {
        let tool = setup_tool().await;

        let add_result = tool
            .call(
                &json!({
                    "action": "add",
                    "name": "Alice",
                    "relationship": "friend"
                })
                .to_string(),
            )
            .await
            .unwrap();
        assert!(
            add_result.contains("Added person"),
            "unexpected add output: {}",
            add_result
        );

        let upcoming = chrono::Utc::now().date_naive() + chrono::Duration::days(2);
        let date_value = upcoming.format("%m-%d").to_string();
        let add_fact_result = tool
            .call(
                &json!({
                    "action": "add_fact",
                    "person_name": "Alice",
                    "category": "birthday",
                    "key": "birthday",
                    "value": date_value
                })
                .to_string(),
            )
            .await
            .unwrap();
        assert!(
            add_fact_result.contains("Added fact"),
            "unexpected add_fact output: {}",
            add_fact_result
        );

        let result = tool
            .call(
                &json!({
                    "action": "upcoming",
                    "within_days": 7
                })
                .to_string(),
            )
            .await
            .unwrap();
        assert!(
            result.contains("Upcoming Dates"),
            "unexpected upcoming output: {}",
            result
        );
        assert!(
            result.contains("Alice"),
            "unexpected upcoming output: {}",
            result
        );
    }

    #[tokio::test]
    async fn reconnect_lists_inactive_people() {
        let tool = setup_tool().await;

        tool.call(
            &json!({
                "action": "add",
                "name": "Bob",
                "relationship": "friend",
                "communication_style": "warm"
            })
            .to_string(),
        )
        .await
        .unwrap();
        tool.call(
            &json!({
                "action": "link",
                "person_name": "Bob",
                "platform_id": "slack:U_BOB",
                "display_name": "bob"
            })
            .to_string(),
        )
        .await
        .unwrap();

        // Touch interaction now; with inactive_days=1 this should not show.
        // Use the state method via the tool boundary by resolving person brief,
        // then calling reconnect with a low threshold to validate output shape.
        let brief = tool
            .call(
                &json!({
                    "action": "brief",
                    "name": "Bob"
                })
                .to_string(),
            )
            .await
            .unwrap();
        assert!(brief.contains("People Brief: Bob"));

        let result = tool
            .call(
                &json!({
                    "action": "reconnect",
                    "inactive_days": 1
                })
                .to_string(),
            )
            .await
            .unwrap();
        // Might be empty depending on interaction timestamps; assert stable text contract.
        assert!(
            result.contains("Reconnect Suggestions")
                || result.contains("No reconnect suggestions right now")
        );
    }

    #[tokio::test]
    async fn brief_includes_core_guidance() {
        let tool = setup_tool().await;
        tool.call(
            &json!({
                "action": "add",
                "name": "Carol",
                "relationship": "coworker",
                "communication_style": "formal",
                "language": "English"
            })
            .to_string(),
        )
        .await
        .unwrap();
        tool.call(
            &json!({
                "action": "add_fact",
                "person_name": "Carol",
                "category": "work",
                "key": "role",
                "value": "Engineering Manager"
            })
            .to_string(),
        )
        .await
        .unwrap();

        let result = tool
            .call(
                &json!({
                    "action": "brief",
                    "name": "Carol"
                })
                .to_string(),
            )
            .await
            .unwrap();
        assert!(result.contains("People Brief: Carol"));
        assert!(result.contains("Suggested approach"));
    }
}