aidaemon-memory 0.22.1

Swappable long-term memory for aidaemon agents: the MemoryStore traits plus SQLite and embedding implementations
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
use std::collections::HashMap;
use std::sync::Arc;

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

use aidaemon_tools::OutcomeTool as Tool;
use aidaemon_tools::semantics::{
    ToolCallSemantics, ToolCapabilities, ToolMutationEffects, semantics_for_exact_read_actions,
};
use aidaemon_tools::services::SettingsStore;

use crate::records::{Person, PersonFact};

/// The people store's tool. People intelligence is on while the host's
/// `people_enabled` setting is `"true"`; `enable`/`disable` set it.
pub struct ManagePeopleTool {
    store: Arc<dyn crate::stores::MemoryStores>,
    settings: Arc<dyn SettingsStore>,
}

impl ManagePeopleTool {
    pub fn new(
        settings: Arc<dyn SettingsStore>,
        store: Arc<dyn crate::stores::MemoryStores>,
    ) -> Self {
        Self { store, settings }
    }
}

#[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>,
    #[serde(default)]
    personal_memory: Option<crate::records::PersonalMemoryWrite>,
}

/// The tool's one description: the schema the model reads and
/// `description()` both use it.
const 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).";

/// The `personal_memory` block `remember` takes: people and places as
/// entities with call-local ids, their aliases, facts and relationships.
pub(crate) fn personal_memory_schema() -> Value {
    json!({
        "type": "object",
        "description": "remember: entities with call-local ids, then aliases, facts and relationships that refer to those ids. The owner is local_id \"owner\".",
        "properties": {
            "entities": {
                "type": "array",
                "description": "Each person, organization, project, place or account mentioned.",
                "items": {
                    "type": "object",
                    "properties": {
                        "local_id": {"type": "string", "description": "Id used by this call only."},
                        "entity_type": {"type": "string", "enum": ["person", "organization", "project", "place", "account"], "description": "What it is."},
                        "canonical_name": {"type": "string", "description": "Name as the owner gave it."},
                        "is_reference": {"type": "boolean", "description": "Resolve existing alias/name; false declares."},
                        "canonical_name_confirmed": {"type": "boolean", "description": "The owner stated this exact name."}
                    },
                    "required": ["local_id", "entity_type", "canonical_name"]
                }
            },
            "aliases": {
                "type": "array",
                "description": "Other names an entity goes by.",
                "items": {
                    "type": "object",
                    "properties": {
                        "entity_local_id": {"type": "string", "description": "The entity's local_id."},
                        "value": {"type": "string", "description": "The alias."},
                        "alias_type": {"type": "string", "enum": ["legal_name_variant", "preferred_name", "nickname", "username", "online_handle", "account_name"], "description": "Kind of alias."}
                    },
                    "required": ["entity_local_id", "value", "alias_type"]
                }
            },
            "facts": {
                "type": "array",
                "description": "Attributes of an entity (birthday, residence, ...).",
                "items": {
                    "type": "object",
                    "properties": {
                        "subject_local_id": {"type": "string", "description": "The entity's local_id."},
                        "predicate": {"type": "string", "description": "snake_case attribute, e.g. birthday."},
                        "value": {"type": "string", "description": "Normalized value."},
                        "display_value": {"type": "string", "description": "Value as written, when it differs."},
                        "valid_from": {"type": "string", "description": "RFC3339 or date it became true."},
                        "valid_to": {"type": "string", "description": "When it stopped being true."}
                    },
                    "required": ["subject_local_id", "predicate", "value"]
                }
            },
            "relationships": {
                "type": "array",
                "description": "Typed links between entities.",
                "items": {
                    "type": "object",
                    "properties": {
                        "source_local_id": {"type": "string", "description": "From entity."},
                        "relationship_type": {"type": "string", "enum": ["PARENT_OF", "CHILD_OF", "LIVES_WITH", "LIVES_IN", "USES_ALIAS", "USES_HANDLE", "HAS_ACCOUNT"], "description": "source → target."},
                        "target_local_id": {"type": "string", "description": "To entity."},
                        "valid_from": {"type": "string", "description": "When it began."},
                        "valid_to": {"type": "string", "description": "When it ended."}
                    },
                    "required": ["source_local_id", "relationship_type", "target_local_id"]
                }
            },
            "correction": {"type": "boolean", "description": "The owner is correcting an earlier value."}
        },
        "additionalProperties": false
    })
}

fn manage_people_schema() -> Value {
    json!({
        "name": "manage_people",
        "description": TOOL_DESCRIPTION,
        "parameters": {
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["remember", "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", "description": "For category birthday or important_date: an ISO date, YYYY-MM-DD, or --MM-DD without a year" },
                "platform_id": { "type": "string" },
                "display_name": { "type": "string" },
                "fact_id": { "type": "integer" },
                "within_days": { "type": "integer", "description": "days ahead" },
                "inactive_days": { "type": "integer" },
                "personal_memory": personal_memory_schema()
            },
            "required": ["action"],
            "additionalProperties": false
        }
    })
}

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

    fn description(&self) -> &str {
        TOOL_DESCRIPTION
    }

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

    async fn execute(
        &self,
        arguments: &str,
        facts: &aidaemon_tools::semantics::ToolCallContext,
    ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
        let output: anyhow::Result<String> = async move {
        let args: ManagePeopleArgs = serde_json::from_str(arguments)?;

        // Toggle actions are always allowed regardless of enabled state, and
        // so is `remember`: personal memory is not the contacts book.
        match args.action.as_str() {
            "remember" => return self.handle_remember(args, facts.channel_id.as_deref()).await,
            "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)),
        }
    }.await;
        output.map(aidaemon_tools::semantics::ToolCallOutcome::from_output)
    }
}

impl aidaemon_tools::semantics::ToolSemantics for ManagePeopleTool {
    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
        aidaemon_tools::semantics::ToolDispatchFacts {
            status_from_arguments: true,
            activity: aidaemon_tools::semantics::ToolActivity::Memory,
            ..Default::default()
        }
    }

    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
        // `remember` writes the agent's memory, typed as remember_fact's
        // writes are so a checklist step can be credited by it.
        if action_of(arguments).as_deref() == Some("remember") {
            return ToolCallSemantics::mutation_with(
                ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::MEMORY_WRITE),
            );
        }
        // Every other action writes the people store too (notes that go
        // into later prompts, or who a sender is linked to), and is typed
        // the same way: after outside content was read, such a write is
        // checked like any other change to what the agent is told.
        semantics_for_exact_read_actions(
            arguments,
            &["status", "list", "view", "brief", "upcoming", "audit"],
            ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::MEMORY_WRITE),
        )
    }

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

    /// Every action but `enable`/`disable` (a runtime setting) touches only
    /// the agent's own people store.
    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
        let action = serde_json::from_str::<Value>(arguments)
            .ok()
            .and_then(|args| {
                args.get("action")
                    .and_then(Value::as_str)
                    .map(str::to_string)
            });
        match action.as_deref() {
            Some(
                "remember" | "status" | "add" | "list" | "view" | "brief" | "upcoming"
                | "reconnect" | "update" | "remove" | "add_fact" | "remove_fact" | "export"
                | "purge" | "audit" | "confirm",
            ) => aidaemon_core::CallEffects::none(),
            // `link` binds a sender to a person, so that person's facts reach
            // the sender's later turns: it widens who sees the owner's notes.
            _ => aidaemon_core::CallEffects::unknown(),
        }
    }
}

/// The `action` argument, if any.
fn action_of(arguments: &str) -> Option<String> {
    serde_json::from_str::<Value>(arguments)
        .ok()?
        .get("action")?
        .as_str()
        .map(str::to_string)
}

impl ManagePeopleTool {
    /// Store people, aliases, facts and relationships in structured personal
    /// memory: the store recall projects into the owner's facts and core
    /// profile.
    async fn handle_remember(
        &self,
        args: ManagePeopleArgs,
        channel_id: Option<&str>,
    ) -> anyhow::Result<String> {
        let Some(mut personal) = args.personal_memory.filter(|personal| {
            !(personal.entities.is_empty()
                && personal.aliases.is_empty()
                && personal.facts.is_empty()
                && personal.relationships.is_empty())
        }) else {
            return Ok("Missing required field: personal_memory (entities, aliases, facts or relationships)".to_string());
        };
        personal.direct_user_statement = true;
        let result = self
            .store
            .reconcile_personal_memory(
                &personal,
                "agent",
                None,
                channel_id,
                crate::records::FactPrivacy::Private,
            )
            .await?;
        Ok(format!("Personal memory: {}", result.concise_summary()))
    }

    async fn resolve_person(&self, args: &ManagePeopleArgs) -> anyhow::Result<Option<Person>> {
        if let Some(id) = args.id {
            return self.store.get_person(id).await;
        }
        if let Some(ref name) = args.name {
            return self.store.find_person_by_name(name).await;
        }
        if let Some(ref person_name) = args.person_name {
            return self.store.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.store.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.store.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
                && 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.store.get_person(id).await?
        } else if let Some(ref name) = args.name {
            self.store.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.store.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.store.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| {
                crate::dates::days_until_anniversary(&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.store.get_all_people().await?;
        for person in people {
            let facts = self.store.get_person_facts(person.id, None).await?;
            for fact in facts {
                if fact.category != "birthday" && fact.category != "important_date" {
                    continue;
                }
                if let Some(days) = crate::dates::days_until_anniversary(&fact.value, today)
                    && 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
            .store
            .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.store.get_person(id).await?
        } else if let Some(ref name) = args.name {
            self.store.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
            && 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.store.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.store.get_person(id).await?
        } else if let Some(ref name) = args.name {
            self.store.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.store.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()),
        };
        if crate::dates::is_date_fact_category(category)
            && let Some(error) = crate::dates::date_argument_error(value)
        {
            anyhow::bail!("Not added: {error}");
        }

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

        self.store
            .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.store.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.store.find_person_by_name(person_name).await? {
            Some(p) => p,
            None => return Ok(format!("Person '{}' not found.", person_name)),
        };

        self.store
            .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.store.find_person_by_name(person_name).await? {
            Some(p) => p,
            None => return Ok(format!("Person '{}' not found.", person_name)),
        };

        let facts = self.store.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.store.find_person_by_name(person_name).await? {
            Some(p) => p,
            None => return Ok(format!("Person '{}' not found.", person_name)),
        };

        let facts = self.store.get_person_facts(person.id, None).await?;
        self.store.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.store.find_person_by_name(name).await? {
                Some(p) => p,
                None => return Ok(format!("Person '{}' not found.", name)),
            };

            let facts = self.store.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.store.get_all_people().await?;
            let mut total_unverified = 0;
            let mut result = String::from("**Audit Summary**\n");

            for p in &people {
                let facts = self.store.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.store.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.settings
            .get_setting("people_enabled")
            .await
            .ok()
            .flatten()
            .as_deref()
            == Some("true")
    }

    async fn handle_enable(&self) -> anyhow::Result<String> {
        self.settings.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.settings.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.store.get_all_people().await.unwrap_or_default().len();
        let canonical = self
            .store
            .get_canonical_memory_facts()
            .await
            .unwrap_or_default();
        let relationship_edges = canonical
            .iter()
            .filter(|fact| fact.category == "relationships")
            .count();
        let canonical_attributes = canonical.len().saturating_sub(relationship_edges);
        Ok(format!(
            "Legacy People Intelligence: **{}**\n\
             Legacy contact records: {}\n\
             Structured personal memory: {} active facts/aliases, {} active directed relationship edges\n\
             These are separate compatibility layers. Do not describe legacy contact rows as populated structured graph edges.",
            if enabled { "enabled" } else { "disabled" },
            people_count,
            canonical_attributes,
            relationship_edges,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::full::tools::test_support::{Settings, ToolCalls as _, memory};
    use aidaemon_tools::semantics::ToolSemantics;

    /// The people store is the agent's own; the enable/disable setting and
    /// `link` (which widens who sees a person's facts) stay undeclared.
    #[tokio::test]
    async fn people_store_actions_declare_no_effects() {
        let tool = setup_tool().await;
        let effects = |action: &str| tool.call_effects(&json!({"action": action}).to_string());
        for action in [
            "add", "update", "remove", "add_fact", "purge", "export", "view",
        ] {
            assert_eq!(
                effects(action),
                aidaemon_core::CallEffects::none(),
                "{action}"
            );
        }
        for action in ["enable", "disable", "link", "unknown"] {
            assert!(!effects(action).complete, "{action}");
        }
    }

    /// `remember` writes structured personal memory, the store recall
    /// projects into the owner's facts, and works with the contacts book off.
    #[tokio::test]
    async fn remember_writes_personal_memory_that_recall_reads_with_people_off() {
        let settings = Arc::new(Settings::default());
        settings
            .set_setting("people_enabled", "false")
            .await
            .unwrap();
        let store = memory().await;
        let tool = ManagePeopleTool::new(settings, store.clone());
        let args = json!({
            "action": "remember",
            "personal_memory": {
                "entities": [
                    {"local_id": "owner", "entity_type": "person", "canonical_name": "Owner"},
                    {"local_id": "mia", "entity_type": "person", "canonical_name": "Mia"}
                ],
                "facts": [{"subject_local_id": "mia", "predicate": "birthday", "value": "2019-04-02"}],
                "relationships": [{"source_local_id": "owner", "relationship_type": "PARENT_OF", "target_local_id": "mia"}]
            }
        });
        let out = tool.call(&args.to_string()).await.unwrap();
        assert!(out.starts_with("Personal memory:"), "{out}");
        assert!(
            tool.call_semantics(&args.to_string())
                .mutation_effects
                .satisfies(ToolMutationEffects::MEMORY_WRITE)
        );
        assert_eq!(
            tool.call_effects(&args.to_string()),
            aidaemon_core::CallEffects::none()
        );
        let canonical = crate::stores::FactStore::get_canonical_memory_facts(store.as_ref())
            .await
            .unwrap();
        assert!(
            canonical
                .iter()
                .any(|fact| fact.key.contains("Mia") && fact.value == "2019-04-02"),
            "{canonical:?}"
        );

        let empty = tool
            .call(&json!({"action": "remember", "personal_memory": {}}).to_string())
            .await
            .unwrap();
        assert!(empty.starts_with("Missing required field"), "{empty}");
    }

    async fn setup_tool() -> ManagePeopleTool {
        let settings = Arc::new(Settings::default());
        settings
            .set_setting("people_enabled", "true")
            .await
            .unwrap();
        ManagePeopleTool::new(settings, memory().await)
    }

    #[tokio::test]
    async fn status_distinguishes_legacy_people_from_structured_edges() {
        let tool = setup_tool().await;
        let result = tool
            .call(&json!({"action": "status"}).to_string())
            .await
            .unwrap();
        assert!(result.contains("Legacy contact records:"));
        assert!(result.contains("active directed relationship edges"));
        assert!(result.contains("separate compatibility layers"));
    }

    #[tokio::test]
    async fn an_ambiguous_date_is_refused() {
        let tool = setup_tool().await;
        tool.call(&json!({"action": "add", "name": "Alice Rivera"}).to_string())
            .await
            .unwrap();
        for value in ["05/03", "May 3", "05-03"] {
            let refused = tool
                .call(
                    &json!({
                        "action": "add_fact",
                        "person_name": "Alice Rivera",
                        "category": "birthday",
                        "key": "birthday",
                        "value": value
                    })
                    .to_string(),
                )
                .await;
            let error = refused.expect_err(value).to_string();
            assert!(error.contains("YYYY-MM-DD"), "{value}: {error}");
        }
        let added = tool
            .call(
                &json!({
                    "action": "add_fact",
                    "person_name": "Alice Rivera",
                    "category": "birthday",
                    "key": "birthday",
                    "value": "--05-03"
                })
                .to_string(),
            )
            .await
            .unwrap();
        assert!(added.contains("Added fact"), "{added}");
    }

    #[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"));
    }
}