Skip to main content

aidaemon_memory/full/tools/
remember_fact.rs

1use std::sync::Arc;
2
3use async_trait::async_trait;
4use serde::Deserialize;
5use serde_json::{Value, json};
6use tokio::sync::RwLock;
7
8use aidaemon_tools::OutcomeTool as Tool;
9use aidaemon_tools::semantics::{
10    ToolCallSemantics, ToolCapabilities, ToolMutationEffects, ToolRole,
11};
12
13use crate::project::{MemoryScope, NoteKind, NoteSource, NoteWrite, ProjectNotes};
14use crate::records::{
15    FactPrivacy, PersonalAliasCandidate, PersonalEntityCandidate, PersonalFactCandidate,
16    PersonalMemoryWrite,
17};
18use crate::stores::FactStore;
19use aidaemon_core::ProjectRef;
20
21pub struct RememberFactTool {
22    state: Arc<dyn FactStore>,
23    /// Current channel_id set by the agent before tool execution.
24    pub current_channel_id: Arc<RwLock<Option<String>>>,
25    /// Project memory: on a turn that works in a project, what the turn
26    /// learns about the project is kept here instead of in `state`.
27    project_notes: Option<Arc<ProjectNotes>>,
28    /// The project of the one turn this instance serves, for a host whose
29    /// dispatcher does not set `ToolCallContext::project`.
30    turn_project: Option<ProjectRef>,
31}
32
33impl RememberFactTool {
34    pub fn new(state: Arc<dyn FactStore>) -> Self {
35        Self {
36            state,
37            current_channel_id: Arc::new(RwLock::new(None)),
38            project_notes: None,
39            turn_project: None,
40        }
41    }
42
43    /// Keep project facts in `notes` on turns that work in a project.
44    pub fn with_project_notes(mut self, notes: Arc<ProjectNotes>) -> Self {
45        self.project_notes = Some(notes);
46        self
47    }
48
49    /// This instance serves one turn that works in `project`.
50    pub fn for_project(mut self, project: Option<ProjectRef>) -> Self {
51        self.turn_project = project;
52        self
53    }
54
55    /// The project the call's turn works in, when project memory is on.
56    fn project(
57        &self,
58        facts: &aidaemon_tools::semantics::ToolCallContext,
59    ) -> Option<(Arc<ProjectNotes>, ProjectRef)> {
60        let notes = self.project_notes.clone()?;
61        let project = facts
62            .project
63            .clone()
64            .or_else(|| self.turn_project.clone())?;
65        Some((notes, project))
66    }
67}
68
69#[derive(Deserialize)]
70struct RememberArgs {
71    category: Option<String>,
72    key: Option<String>,
73    value: Option<String>,
74    /// Forget the single `category`/`key` fact instead of storing a value.
75    #[serde(default)]
76    delete: bool,
77    #[serde(default)]
78    facts: Option<Vec<FactEntry>>,
79    /// People and relationships moved to `manage_people` `remember`; a call
80    /// that still sends them is answered with that and stores nothing.
81    #[serde(default)]
82    personal_memory: Option<PersonalMemoryWrite>,
83    /// `project` or `personal`, for the single fact and as the default of
84    /// `facts` entries without their own.
85    #[serde(default)]
86    scope: Option<String>,
87}
88
89/// The `scope` parameter, shared by the single fact and `facts` entries.
90static SCOPE_SCHEMA: std::sync::LazyLock<Value> = std::sync::LazyLock::new(|| {
91    json!({
92        "type": "string",
93        "enum": ["project", "personal"],
94        "description": "In a project conversation: project (default) keeps it in the project's notes, personal keeps it for the owner. Facts about the owner are always personal."
95    })
96});
97
98/// The `evidence` parameter, shared by the single fact and `facts` entries.
99/// The learner reads it after the run: a quote found in the owner's own
100/// message marks the fact as stated by the owner, anything else as derived
101/// (see `TaskLearner`'s provenance stamping).
102static EVIDENCE_SCHEMA: std::sync::LazyLock<Value> = std::sync::LazyLock::new(|| {
103    json!({
104        "type": "string",
105        "description": "The owner's own words stating this fact, copied verbatim from their message. Omit when they did not state it (inferred, asked, negated, or from a tool, file or page)."
106    })
107});
108
109/// The `evidence` of a `facts` entry: as [`EVIDENCE_SCHEMA`], described once.
110static ENTRY_EVIDENCE_SCHEMA: std::sync::LazyLock<Value> =
111    std::sync::LazyLock::new(|| json!({"type": "string"}));
112
113/// The `scope` of a `facts` entry: as [`SCOPE_SCHEMA`], described once.
114static ENTRY_SCOPE_SCHEMA: std::sync::LazyLock<Value> =
115    std::sync::LazyLock::new(|| json!({"type": "string", "enum": ["project", "personal"]}));
116
117/// How a call that still carries people is answered.
118pub const PEOPLE_MOVED: &str = "remember_fact no longer stores people; nothing was stored. Send the same personal_memory to manage_people with action \"remember\", and any owner facts here without it.";
119
120#[derive(Deserialize)]
121struct FactEntry {
122    category: String,
123    key: String,
124    #[serde(default)]
125    value: String,
126    #[serde(default)]
127    delete: bool,
128    #[serde(default)]
129    scope: Option<String>,
130}
131
132/// True when this exact call would delete at least one fact. Mirrors the
133/// entry selection in `call`: a non-empty `facts` batch wins, otherwise the
134/// single key/value pair. Deletion is the typed `delete` flag, never a value.
135pub fn call_deletes_facts(arguments: &str) -> bool {
136    let Ok(args) = serde_json::from_str::<RememberArgs>(arguments) else {
137        return false;
138    };
139    match args.facts.filter(|facts| !facts.is_empty()) {
140        Some(facts) => facts.iter().any(|entry| entry.delete),
141        None => args.delete && args.key.is_some_and(|key| !key.trim().is_empty()),
142    }
143}
144
145#[async_trait]
146impl Tool for RememberFactTool {
147    fn name(&self) -> &str {
148        "remember_fact"
149    }
150
151    fn description(&self) -> &str {
152        "Store or forget stable facts about the owner and their environment, not task research, generated content, goals, or schedules. Other people, family and relationships: manage_people remember."
153    }
154
155    fn schema(&self) -> Value {
156        json!({
157            "name": "remember_fact",
158            "description": self.description(),
159            "parameters": {
160                "type": "object",
161                "properties": {
162                    "category": {
163                        "type": "string"
164                    },
165                    "key": {
166                        "type": "string"
167                    },
168                    "value": {
169                        "type": "string",
170                        "description": "Stored as written, including \"none\"."
171                    },
172                    "delete": {
173                        "type": "boolean",
174                        "description": "Forget category/key; value is ignored."
175                    },
176                    "scope": SCOPE_SCHEMA.clone(),
177                    "evidence": EVIDENCE_SCHEMA.clone(),
178                    "facts": {
179                        "type": "array",
180                        "items": {
181                            "type": "object",
182                            "properties": {
183                                "category": {
184                                    "type": "string"
185                                },
186                                "key": {
187                                    "type": "string"
188                                },
189                                "value": {
190                                    "type": "string",
191                                    "description": "Stored as written, including \"none\"."
192                                },
193                                "delete": {
194                                    "type": "boolean",
195                                    "description": "Forget this fact; value is ignored."
196                                },
197                                "scope": ENTRY_SCOPE_SCHEMA.clone(),
198                                "evidence": ENTRY_EVIDENCE_SCHEMA.clone()
199                            },
200                            "required": ["category", "key"]
201                        }
202                    }
203                },
204                "additionalProperties": false
205            }
206        })
207    }
208
209    async fn execute(
210        &self,
211        arguments: &str,
212        _facts: &aidaemon_tools::semantics::ToolCallContext,
213    ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
214        let output: anyhow::Result<String> = async move {
215            let args: RememberArgs = serde_json::from_str(arguments)?;
216            let channel_id = self.current_channel_id.read().await.clone();
217
218            let mut results = Vec::new();
219
220            // An empty personal_memory block (models often send every schema
221            // section) carries nothing; one with people is answered with
222            // where people went, and nothing in the call is stored.
223            if call_carries_people(arguments) {
224                return Ok(PEOPLE_MOVED.to_string());
225            }
226            let facts = args.facts.filter(|facts| !facts.is_empty());
227            let single_key = args.key.filter(|key| !key.trim().is_empty());
228
229            // Build the list of facts to store (batch or single)
230            let entries: Vec<FactEntry> = if let Some(facts) = facts {
231                facts
232            } else {
233                // Single-fact mode: require all three fields
234                let category = args.category.ok_or_else(|| {
235                    anyhow::anyhow!("'category' is required (or use 'facts' array)")
236                })?;
237                let key = single_key
238                    .ok_or_else(|| anyhow::anyhow!("'key' is required (or use 'facts' array)"))?;
239                let value = args.value.unwrap_or_default();
240                vec![FactEntry {
241                    category,
242                    key,
243                    value,
244                    delete: args.delete,
245                    scope: None,
246                }]
247            };
248            // Each entry's own scope, else the call's.
249            let call_scope = args.scope.clone();
250            let entries: Vec<FactEntry> = entries
251                .into_iter()
252                .map(|mut entry| {
253                    if entry.scope.is_none() {
254                        entry.scope = call_scope.clone();
255                    }
256                    entry
257                })
258                .collect();
259
260            // On a turn in a project, what belongs to the project becomes
261            // its notes and never reaches the fact store, so it cannot
262            // replace or merge with any of the owner's facts.
263            let project = self.project(_facts);
264            let mut project_indices = std::collections::BTreeSet::new();
265            for (index, entry) in entries.iter().enumerate() {
266                let requested = match entry.scope.as_deref() {
267                    None => None,
268                    Some(raw) => match MemoryScope::parse(raw) {
269                        Some(scope) => Some(scope),
270                        None => {
271                            results.push(format!(
272                                "Not stored [{}] {}: scope must be \"project\" or \"personal\"",
273                                entry.category, entry.key
274                            ));
275                            project_indices.insert(index);
276                            continue;
277                        }
278                    },
279                };
280                let in_project = project.is_some();
281                if requested == Some(MemoryScope::Project) && !in_project {
282                    results.push(format!(
283                        "Not stored [{}] {}: project memory is not available in this conversation; leave scope out to remember it for the owner",
284                        entry.category, entry.key
285                    ));
286                    project_indices.insert(index);
287                    continue;
288                }
289                if crate::project::route(&entry.category, requested, in_project)
290                    != MemoryScope::Project
291                {
292                    continue;
293                }
294                project_indices.insert(index);
295                let Some((notes, project)) = project.clone() else {
296                    continue;
297                };
298                results.push(project_note(notes, project, entry).await);
299            }
300
301            let mut structured = PersonalMemoryWrite {
302                direct_user_statement: true,
303                ..Default::default()
304            };
305            let mut owner_added = false;
306            let mut structured_indices = std::collections::BTreeSet::new();
307            for (index, entry) in entries.iter().enumerate() {
308                if project_indices.contains(&index)
309                    || !matches!(
310                        entry.category.trim().to_ascii_lowercase().as_str(),
311                        "user" | "personal" | "profile"
312                    )
313                {
314                    continue;
315                }
316                let key = entry.key.trim().to_ascii_lowercase();
317                let supported = matches!(
318                    key.as_str(),
319                    "name"
320                        | "full_name"
321                        | "preferred_name"
322                        | "nickname"
323                        | "username"
324                        | "online_nickname"
325                        | "online_handle"
326                        | "handle"
327                        | "birthday"
328                        | "birth_date"
329                        | "date_of_birth"
330                        | "residence"
331                        | "current_residence"
332                        | "birthplace"
333                        | "place_of_birth"
334                );
335                // A forget takes the delete path below, which also retracts
336                // the canonical record. An empty value is reported there.
337                if !supported || entry.delete || entry.value.trim().is_empty() {
338                    continue;
339                }
340                if !owner_added {
341                    structured.entities.push(PersonalEntityCandidate {
342                        local_id: "owner".to_string(),
343                        entity_type: "person".to_string(),
344                        canonical_name: if matches!(key.as_str(), "name" | "full_name") {
345                            entry.value.clone()
346                        } else {
347                            "Owner".to_string()
348                        },
349                        is_reference: false,
350                        canonical_name_confirmed: matches!(key.as_str(), "name" | "full_name"),
351                    });
352                    owner_added = true;
353                } else if matches!(key.as_str(), "name" | "full_name")
354                    && let Some(owner) = structured.entities.first_mut()
355                {
356                    owner.canonical_name = entry.value.clone();
357                    owner.canonical_name_confirmed = true;
358                }
359                match key.as_str() {
360                    "name" | "full_name" => structured.aliases.push(PersonalAliasCandidate {
361                        entity_local_id: "owner".to_string(),
362                        value: entry.value.clone(),
363                        alias_type: "legal_name_variant".to_string(),
364                    }),
365                    "preferred_name" | "nickname" => {
366                        structured.aliases.push(PersonalAliasCandidate {
367                            entity_local_id: "owner".to_string(),
368                            value: entry.value.clone(),
369                            alias_type: key,
370                        })
371                    }
372                    "username" | "online_nickname" | "online_handle" | "handle" => {
373                        structured.aliases.push(PersonalAliasCandidate {
374                            entity_local_id: "owner".to_string(),
375                            value: entry.value.clone(),
376                            alias_type: "online_handle".to_string(),
377                        })
378                    }
379                    _ => structured.facts.push(PersonalFactCandidate {
380                        subject_local_id: "owner".to_string(),
381                        predicate: key,
382                        value: entry.value.clone(),
383                        display_value: None,
384                        valid_from: None,
385                        valid_to: None,
386                        retract: false,
387                    }),
388                }
389                structured_indices.insert(index);
390            }
391
392            if !structured.entities.is_empty() {
393                let result = self
394                    .state
395                    .reconcile_personal_memory(
396                        &structured,
397                        "agent",
398                        None,
399                        channel_id.as_deref(),
400                        FactPrivacy::Private,
401                    )
402                    .await?;
403                results.push(format!("Personal memory: {}", result.concise_summary()));
404                for index in &structured_indices {
405                    let entry = &entries[*index];
406                    results.push(format!(
407                        "Remembered: [{}] {} = {} (canonical)",
408                        entry.category, entry.key, entry.value
409                    ));
410                }
411            }
412
413            for (index, entry) in entries.iter().enumerate() {
414                if structured_indices.contains(&index) || project_indices.contains(&index) {
415                    continue;
416                }
417                if entry.delete {
418                    let deleted = self
419                        .state
420                        .delete_fact_by_key(&entry.category, &entry.key)
421                        .await?;
422                    if deleted {
423                        results.push(format!("Deleted: [{}] {}", entry.category, entry.key));
424                    } else {
425                        results.push(format!(
426                            "Not found (nothing to delete): [{}] {}",
427                            entry.category, entry.key
428                        ));
429                    }
430                    continue;
431                }
432                if entry.value.trim().is_empty() {
433                    results.push(format!(
434                        "Not stored [{}] {}: value is empty (set delete: true to forget it)",
435                        entry.category, entry.key
436                    ));
437                    continue;
438                }
439
440                self.state
441                    .upsert_fact(
442                        &entry.category,
443                        &entry.key,
444                        &entry.value,
445                        "agent",
446                        channel_id.as_deref(),
447                        FactPrivacy::Global,
448                    )
449                    .await?;
450                results.push(format!(
451                    "Remembered: [{}] {} = {}",
452                    entry.category, entry.key, entry.value
453                ));
454            }
455
456            Ok(results.join("\n"))
457        }
458        .await;
459        let people_moved = call_carries_people(arguments);
460        output.map(|output| {
461            let mut outcome = aidaemon_tools::semantics::ToolCallOutcome::from_output(output);
462            if people_moved {
463                outcome.metadata.outcome_status =
464                    Some(aidaemon_tools::semantics::ToolOutcomeStatus::FailedPermanent);
465            }
466            outcome
467        })
468    }
469}
470
471/// Writes or deletes one entry in `project`'s notes, as a result line.
472async fn project_note(notes: Arc<ProjectNotes>, project: ProjectRef, entry: &FactEntry) -> String {
473    let kind = crate::project::kind_for_category(&entry.category);
474    let label = format!("[{}] {}", entry.category, entry.key);
475    let name = project.name.clone();
476    let category = entry.category.clone();
477    let key = entry.key.clone();
478    if entry.delete {
479        let deleted = tokio::task::spawn_blocking(move || notes.delete(&project, Some(kind), &key))
480            .await
481            .map_err(|error| error.to_string())
482            .and_then(|result| result.map_err(|error| error.to_string()));
483        return match deleted {
484            Ok(true) => format!("Deleted from project {name}: {label}"),
485            Ok(false) => format!("Not found in project {name} (nothing to delete): {label}"),
486            Err(error) => format!("Not deleted {label}: {error}"),
487        };
488    }
489    if entry.value.trim().is_empty() {
490        return format!("Not stored {label}: value is empty (set delete: true to forget it)");
491    }
492    let value = entry.value.clone();
493    let write = NoteWrite {
494        kind,
495        key,
496        category: Some(category),
497        description: None,
498        body: value.clone(),
499        source: NoteSource::Agent,
500    };
501    let written = tokio::task::spawn_blocking(move || notes.write(&project, &write))
502        .await
503        .map_err(|error| error.to_string())
504        .and_then(|result| result.map_err(|error| error.to_string()));
505    match written {
506        Ok(_) => {
507            let kind = if kind == NoteKind::Fact {
508                String::new()
509            } else {
510                format!(" ({})", kind.as_str())
511            };
512            format!("Remembered for project {name}{kind}: {label} = {value}")
513        }
514        Err(error) => format!("Not stored {label}: {error}"),
515    }
516}
517
518/// Whether the call still sends people (a non-empty `personal_memory`).
519fn call_carries_people(arguments: &str) -> bool {
520    serde_json::from_str::<RememberArgs>(arguments)
521        .ok()
522        .and_then(|args| args.personal_memory)
523        .is_some_and(|personal| {
524            !(personal.entities.is_empty()
525                && personal.aliases.is_empty()
526                && personal.facts.is_empty()
527                && personal.relationships.is_empty())
528        })
529}
530
531impl aidaemon_tools::semantics::ToolSemantics for RememberFactTool {
532    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
533        aidaemon_tools::semantics::ToolDispatchFacts {
534            offering: aidaemon_tools::semantics::Offering::Core,
535            activity: aidaemon_tools::semantics::ToolActivity::Fixed(
536                aidaemon_core::card::ActivityKind::Remember,
537            ),
538            channel_reach: aidaemon_tools::semantics::ChannelReach::Public,
539            status_label: Some("updating memory"),
540            ..Default::default()
541        }
542    }
543
544    fn tool_role(&self) -> ToolRole {
545        ToolRole::Universal
546    }
547
548    /// Memory is persistent agent state: a write is typed `configuration`
549    /// and a deletion is also `destructive`, so the receipt can prove a
550    /// checklist step declared with either label. An untyped receipt could
551    /// not, which made the model report a deletion it had just performed as
552    /// "already deleted".
553    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
554        if call_deletes_facts(arguments) {
555            ToolCallSemantics::mutation_with(
556                ToolMutationEffects::CONFIGURATION
557                    .union(ToolMutationEffects::MEMORY_WRITE)
558                    .union(ToolMutationEffects::DESTRUCTIVE),
559            )
560        } else {
561            ToolCallSemantics::mutation_with(
562                ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::MEMORY_WRITE),
563            )
564        }
565    }
566
567    fn capabilities(&self) -> ToolCapabilities {
568        ToolCapabilities {
569            read_only: false,
570            external_side_effect: false,
571            needs_approval: false,
572            idempotent: true,
573            high_impact_write: false,
574        }
575    }
576
577    /// Only the agent's own memory store changes, so a decline earlier in
578    /// the run never puts a fact to the owner.
579    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
580        aidaemon_core::CallEffects::none()
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587    use crate::full::tools::test_support::{ToolCalls as _, memory};
588    use crate::sqlite::SqliteMemory;
589    use aidaemon_tools::semantics::ToolSemantics;
590
591    async fn setup() -> (RememberFactTool, Arc<SqliteMemory>, ()) {
592        let state = memory().await;
593        (RememberFactTool::new(state.clone()), state, ())
594    }
595
596    #[tokio::test]
597    async fn empty_personal_memory_block_does_not_drop_batch_facts() {
598        let (tool, state, _db) = setup().await;
599        // Shape a live model sent: every schema section filled in, with the
600        // real content only in the top-level `facts` array.
601        let args = json!({
602            "category": "preference",
603            "key": "",
604            "value": "",
605            "facts": [
606                {"category": "personal", "key": "qa_codename", "value": "SYNTH-CODE-7"},
607                {"category": "preference", "key": "favorite_test_number", "value": "1729"}
608            ],
609            "personal_memory": {
610                "aliases": [], "entities": [], "facts": [], "relationships": [],
611                "correction": false, "direct_user_statement": true
612            }
613        });
614        let out = tool.call(&args.to_string()).await.unwrap();
615        assert!(!out.contains("already current"), "{out}");
616        assert!(out.contains("qa_codename = SYNTH-CODE-7"), "{out}");
617
618        let facts = state.get_facts(None).await.unwrap();
619        assert!(
620            facts
621                .iter()
622                .any(|f| f.key == "qa_codename" && f.value == "SYNTH-CODE-7")
623        );
624        assert!(
625            facts
626                .iter()
627                .any(|f| f.key == "favorite_test_number" && f.value == "1729")
628        );
629    }
630
631    #[tokio::test]
632    async fn empty_personal_memory_and_no_facts_is_an_error_not_a_noop() {
633        let (tool, _state, _db) = setup().await;
634        let args = json!({
635            "key": "",
636            "value": "",
637            "personal_memory": {"entities": [], "aliases": [], "facts": [], "relationships": []}
638        });
639        assert!(tool.call(&args.to_string()).await.is_err());
640    }
641
642    /// People moved to manage_people: a call that still sends them stores
643    /// nothing (not even the facts beside them) and says where they went.
644    #[tokio::test]
645    async fn a_call_with_people_names_manage_people_and_stores_nothing() {
646        let (tool, state, _db) = setup().await;
647        let args = json!({
648            "facts": [{"category": "preference", "key": "editor", "value": "synthetic-editor"}],
649            "personal_memory": {
650                "entities": [{"local_id": "zoe", "entity_type": "person", "canonical_name": "Zoe"}]
651            }
652        });
653        let outcome = tool
654            .execute(&args.to_string(), &Default::default())
655            .await
656            .unwrap();
657        assert!(
658            outcome.output.contains("manage_people"),
659            "{}",
660            outcome.output
661        );
662        assert_eq!(
663            outcome.metadata.outcome_status,
664            Some(aidaemon_tools::semantics::ToolOutcomeStatus::FailedPermanent)
665        );
666        assert!(state.get_facts(None).await.unwrap().is_empty());
667        assert!(state.get_canonical_memory_facts().await.unwrap().is_empty());
668    }
669
670    /// The owner's own profile keys still land in structured memory.
671    #[tokio::test]
672    async fn owner_profile_keys_still_reach_structured_memory() {
673        let (tool, state, _db) = setup().await;
674        let out = tool
675            .call(
676                &json!({"category": "user", "key": "birthday", "value": "1990-01-02"}).to_string(),
677            )
678            .await
679            .unwrap();
680        assert!(out.contains("(canonical)"), "{out}");
681        assert!(
682            state
683                .get_canonical_memory_facts()
684                .await
685                .unwrap()
686                .iter()
687                .any(|fact| fact.category == "user" && fact.value == "1990-01-02")
688        );
689    }
690
691    /// A value is stored as written: "none" is an answer, and wording such
692    /// as "from now on" is not an attack. Forgetting is the typed flag.
693    #[tokio::test]
694    async fn values_are_stored_as_written_and_delete_is_typed() {
695        let (tool, state, _db) = setup().await;
696        let stored = |key: &'static str| {
697            let state = state.clone();
698            async move {
699                state
700                    .get_facts(None)
701                    .await
702                    .unwrap()
703                    .into_iter()
704                    .find(|f| f.key == key)
705                    .map(|f| f.value)
706            }
707        };
708        for (key, value) in [
709            ("allergies", "none"),
710            ("middle_name", "N/A"),
711            ("work_schedule", "From now on I work remote Fridays"),
712            ("quarter_goal", "my goal is to ship the synthetic widget"),
713        ] {
714            let out = tool
715                .call(&json!({"category": "user", "key": key, "value": value}).to_string())
716                .await
717                .unwrap();
718            assert!(out.contains("Remembered"), "{out}");
719            assert_eq!(stored(key).await.as_deref(), Some(value));
720        }
721
722        let out = tool
723            .call(&json!({"category": "user", "key": "allergies", "delete": true}).to_string())
724            .await
725            .unwrap();
726        assert!(out.contains("Deleted"), "{out}");
727        assert_eq!(stored("allergies").await, None);
728
729        let out = tool
730            .call(&json!({"category": "user", "key": "middle_name", "value": ""}).to_string())
731            .await
732            .unwrap();
733        assert!(out.contains("Not stored"), "{out}");
734        assert_eq!(stored("middle_name").await.as_deref(), Some("N/A"));
735    }
736
737    #[tokio::test]
738    async fn memory_receipts_are_typed_for_checklist_credit() {
739        let (tool, _state, _db) = setup().await;
740        let effects = |args: Value| tool.call_semantics(&args.to_string()).mutation_effects;
741
742        let batch_delete = effects(json!({
743            "facts": [{"category": "user", "key": "qa_codename", "delete": true}],
744            "key": "", "value": ""
745        }));
746        assert!(batch_delete.satisfies(ToolMutationEffects::DESTRUCTIVE));
747        assert!(batch_delete.satisfies(ToolMutationEffects::CONFIGURATION));
748        assert!(
749            effects(json!({"category": "user", "key": "qa_codename", "delete": true}))
750                .satisfies(ToolMutationEffects::DESTRUCTIVE)
751        );
752        // A value that reads like a forget is a value.
753        assert!(
754            !effects(json!({"category": "user", "key": "qa_codename", "value": "delete"}))
755                .satisfies(ToolMutationEffects::DESTRUCTIVE)
756        );
757
758        let store = effects(json!({
759            "facts": [{"category": "user", "key": "qa_codename", "value": "SYNTH-CODE-7"}],
760            "key": "", "value": ""
761        }));
762        assert!(store.satisfies(ToolMutationEffects::CONFIGURATION));
763        assert!(!store.satisfies(ToolMutationEffects::DESTRUCTIVE));
764        // A plan that calls saving a fact a derived write can close, but a
765        // saved fact is never a workspace file, and a config change alone is
766        // not a saved fact.
767        assert!(store.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE));
768        assert!(!store.satisfies(ToolMutationEffects::LOCAL_WORKSPACE_WRITE));
769        assert!(
770            !ToolMutationEffects::CONFIGURATION.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE)
771        );
772        // An empty key names nothing to delete.
773        assert!(
774            !effects(json!({"key": "", "delete": true}))
775                .satisfies(ToolMutationEffects::DESTRUCTIVE)
776        );
777    }
778
779    mod project_scope {
780        use super::*;
781        use crate::project::{NoteKind, ProjectNotes};
782        use aidaemon_tools::semantics::ToolCallContext;
783
784        struct Fixture {
785            tool: RememberFactTool,
786            state: Arc<SqliteMemory>,
787            notes: Arc<ProjectNotes>,
788            project: ProjectRef,
789            _dir: tempfile::TempDir,
790        }
791
792        async fn fixture() -> Fixture {
793            let state = memory().await;
794            let dir = tempfile::tempdir().unwrap();
795            let notes = Arc::new(ProjectNotes::new(dir.path()));
796            let tool = RememberFactTool::new(state.clone()).with_project_notes(notes.clone());
797            let project = ProjectRef::new(
798                "project-00000000-0000-4000-8000-000000000001",
799                "Acme Site",
800                None,
801            )
802            .unwrap();
803            Fixture {
804                tool,
805                state,
806                notes,
807                project,
808                _dir: dir,
809            }
810        }
811
812        async fn call_in(
813            tool: &RememberFactTool,
814            project: Option<&ProjectRef>,
815            args: Value,
816        ) -> String {
817            let facts = ToolCallContext {
818                project: project.cloned(),
819                ..Default::default()
820            };
821            tool.execute(&args.to_string(), &facts)
822                .await
823                .unwrap()
824                .output
825        }
826
827        #[tokio::test]
828        async fn a_project_fact_never_touches_personal_memory() {
829            let f = fixture().await;
830            for (category, key, value) in [
831                ("user", "name", "Alice Rivera"),
832                ("preference", "editor", "vim"),
833                ("technical", "test_command", "pytest -q"),
834            ] {
835                f.state
836                    .upsert_fact(category, key, value, "user", None, FactPrivacy::Global)
837                    .await
838                    .unwrap();
839            }
840            let before = f.state.get_facts(None).await.unwrap();
841            // Same key as a personal fact, and a near-synonym of another.
842            let out = call_in(
843                &f.tool,
844                Some(&f.project),
845                json!({"facts": [
846                    {"category": "technical", "key": "test_command", "value": "make test"},
847                    {"category": "technical", "key": "editor_config", "value": "vim modelines are off here"}
848                ]}),
849            )
850            .await;
851            assert!(out.contains("Remembered for project Acme Site"), "{out}");
852            let after = f.state.get_facts(None).await.unwrap();
853            let ids = |facts: &[crate::records::Fact]| {
854                let mut v: Vec<_> = facts.iter().map(|x| (x.id, x.value.clone())).collect();
855                v.sort();
856                v
857            };
858            assert_eq!(ids(&before), ids(&after));
859            assert!(
860                f.notes
861                    .read(&f.project, NoteKind::Fact, "test_command")
862                    .unwrap()
863                    .contains("make test")
864            );
865            assert_eq!(f.notes.entries(&f.project).len(), 2);
866        }
867
868        #[tokio::test]
869        async fn without_a_project_nothing_changes() {
870            let f = fixture().await;
871            let out = call_in(
872                &f.tool,
873                None,
874                json!({"category": "technical", "key": "test_command", "value": "make test"}),
875            )
876            .await;
877            assert_eq!(out, "Remembered: [technical] test_command = make test");
878            assert!(f.notes.entries(&f.project).is_empty());
879            let out = call_in(
880                &f.tool,
881                None,
882                json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "project"}),
883            )
884            .await;
885            assert!(out.contains("project memory is not available"), "{out}");
886            assert!(
887                f.state
888                    .get_facts(None)
889                    .await
890                    .unwrap()
891                    .iter()
892                    .all(|x| x.key != "db")
893            );
894        }
895
896        #[tokio::test]
897        async fn the_owner_stays_personal_in_a_project() {
898            let f = fixture().await;
899            let out = call_in(
900                &f.tool,
901                Some(&f.project),
902                json!({"facts": [
903                    {"category": "user", "key": "residence", "value": "Springfield", "scope": "project"},
904                    {"category": "preference", "key": "indentation", "value": "tabs"},
905                    {"category": "technical", "key": "laptop", "value": "a synthetic laptop", "scope": "personal"}
906                ]}),
907            )
908            .await;
909            assert!(out.contains("canonical"), "{out}");
910            let facts = f.state.get_facts(None).await.unwrap();
911            assert!(facts.iter().any(|x| x.key == "indentation"), "{facts:?}");
912            assert!(facts.iter().any(|x| x.key == "laptop"), "{facts:?}");
913            assert!(f.notes.entries(&f.project).is_empty());
914        }
915
916        #[tokio::test]
917        async fn project_notes_are_deleted_by_key_and_bad_scopes_store_nothing() {
918            let f = fixture().await;
919            call_in(
920                &f.tool,
921                Some(&f.project),
922                json!({"category": "pitfall", "key": "migrations", "value": "Run migrations before seeding."}),
923            )
924            .await;
925            assert!(
926                f.notes
927                    .read(&f.project, NoteKind::Pitfall, "migrations")
928                    .is_some()
929            );
930            let out = call_in(
931                &f.tool,
932                Some(&f.project),
933                json!({"category": "pitfall", "key": "migrations", "delete": true}),
934            )
935            .await;
936            assert!(out.starts_with("Deleted from project"), "{out}");
937            assert!(f.notes.entries(&f.project).is_empty());
938            let out = call_in(
939                &f.tool,
940                Some(&f.project),
941                json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "team"}),
942            )
943            .await;
944            assert!(out.contains("scope must be"), "{out}");
945            assert!(f.notes.entries(&f.project).is_empty());
946            assert!(f.state.get_facts(None).await.unwrap().is_empty());
947        }
948
949        #[tokio::test]
950        async fn a_tool_without_notes_keeps_todays_behaviour_in_a_project() {
951            let state = memory().await;
952            let tool = RememberFactTool::new(state.clone());
953            let project = ProjectRef::new("project-x", "X", None).unwrap();
954            let out = call_in(
955                &tool,
956                Some(&project),
957                json!({"category": "technical", "key": "db", "value": "Postgres"}),
958            )
959            .await;
960            assert_eq!(out, "Remembered: [technical] db = Postgres");
961        }
962    }
963}