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, schedules, or a rule the owner limits to this chat or task (it already applies here). 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        call: &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 set_channel = self.current_channel_id.read().await.clone();
217            let (fact_privacy, channel_id) = write_access(call, set_channel);
218
219            let mut results = Vec::new();
220
221            // An empty personal_memory block (models often send every schema
222            // section) carries nothing; one with people is answered with
223            // where people went, and nothing in the call is stored.
224            if call_carries_people(arguments) {
225                return Ok(PEOPLE_MOVED.to_string());
226            }
227            let facts = args.facts.filter(|facts| !facts.is_empty());
228            let single_key = args.key.filter(|key| !key.trim().is_empty());
229
230            // Build the list of facts to store (batch or single)
231            let entries: Vec<FactEntry> = if let Some(facts) = facts {
232                facts
233            } else {
234                // Single-fact mode: require all three fields
235                let category = args.category.ok_or_else(|| {
236                    anyhow::anyhow!("'category' is required (or use 'facts' array)")
237                })?;
238                let key = single_key
239                    .ok_or_else(|| anyhow::anyhow!("'key' is required (or use 'facts' array)"))?;
240                let value = args.value.unwrap_or_default();
241                vec![FactEntry {
242                    category,
243                    key,
244                    value,
245                    delete: args.delete,
246                    scope: None,
247                }]
248            };
249            // Each entry's own scope, else the call's.
250            let call_scope = args.scope.clone();
251            let entries: Vec<FactEntry> = entries
252                .into_iter()
253                .map(|mut entry| {
254                    if entry.scope.is_none() {
255                        entry.scope = call_scope.clone();
256                    }
257                    entry
258                })
259                .collect();
260
261            // On a turn in a project, what belongs to the project becomes
262            // its notes and never reaches the fact store, so it cannot
263            // replace or merge with any of the owner's facts.
264            let project = self.project(call);
265            let mut project_indices = std::collections::BTreeSet::new();
266            for (index, entry) in entries.iter().enumerate() {
267                let requested = match entry.scope.as_deref() {
268                    None => None,
269                    Some(raw) => match MemoryScope::parse(raw) {
270                        Some(scope) => Some(scope),
271                        None => {
272                            results.push(format!(
273                                "Not stored [{}] {}: scope must be \"project\" or \"personal\"",
274                                entry.category, entry.key
275                            ));
276                            project_indices.insert(index);
277                            continue;
278                        }
279                    },
280                };
281                let in_project = project.is_some();
282                if requested == Some(MemoryScope::Project) && !in_project {
283                    results.push(format!(
284                        "Not stored [{}] {}: project memory is not available in this conversation; leave scope out to remember it for the owner",
285                        entry.category, entry.key
286                    ));
287                    project_indices.insert(index);
288                    continue;
289                }
290                if crate::project::route(&entry.category, requested, in_project)
291                    != MemoryScope::Project
292                {
293                    continue;
294                }
295                project_indices.insert(index);
296                let Some((notes, project)) = project.clone() else {
297                    continue;
298                };
299                results.push(project_note(notes, project, entry).await);
300            }
301
302            let mut structured = PersonalMemoryWrite {
303                direct_user_statement: true,
304                ..Default::default()
305            };
306            let mut owner_added = false;
307            let mut structured_indices = std::collections::BTreeSet::new();
308            for (index, entry) in entries.iter().enumerate() {
309                if project_indices.contains(&index)
310                    || !matches!(
311                        entry.category.trim().to_ascii_lowercase().as_str(),
312                        "user" | "personal" | "profile"
313                    )
314                {
315                    continue;
316                }
317                let key = entry.key.trim().to_ascii_lowercase();
318                let supported = matches!(
319                    key.as_str(),
320                    "name"
321                        | "full_name"
322                        | "preferred_name"
323                        | "nickname"
324                        | "username"
325                        | "online_nickname"
326                        | "online_handle"
327                        | "handle"
328                        | "birthday"
329                        | "birth_date"
330                        | "date_of_birth"
331                        | "residence"
332                        | "current_residence"
333                        | "birthplace"
334                        | "place_of_birth"
335                );
336                // A forget takes the delete path below, which also retracts
337                // the canonical record. An empty value is reported there.
338                if !supported || entry.delete || entry.value.trim().is_empty() {
339                    continue;
340                }
341                if !owner_added {
342                    structured.entities.push(PersonalEntityCandidate {
343                        local_id: "owner".to_string(),
344                        entity_type: "person".to_string(),
345                        canonical_name: if matches!(key.as_str(), "name" | "full_name") {
346                            entry.value.clone()
347                        } else {
348                            "Owner".to_string()
349                        },
350                        is_reference: false,
351                        canonical_name_confirmed: matches!(key.as_str(), "name" | "full_name"),
352                    });
353                    owner_added = true;
354                } else if matches!(key.as_str(), "name" | "full_name")
355                    && let Some(owner) = structured.entities.first_mut()
356                {
357                    owner.canonical_name = entry.value.clone();
358                    owner.canonical_name_confirmed = true;
359                }
360                match key.as_str() {
361                    "name" | "full_name" => structured.aliases.push(PersonalAliasCandidate {
362                        entity_local_id: "owner".to_string(),
363                        value: entry.value.clone(),
364                        alias_type: "legal_name_variant".to_string(),
365                    }),
366                    "preferred_name" | "nickname" => {
367                        structured.aliases.push(PersonalAliasCandidate {
368                            entity_local_id: "owner".to_string(),
369                            value: entry.value.clone(),
370                            alias_type: key,
371                        })
372                    }
373                    "username" | "online_nickname" | "online_handle" | "handle" => {
374                        structured.aliases.push(PersonalAliasCandidate {
375                            entity_local_id: "owner".to_string(),
376                            value: entry.value.clone(),
377                            alias_type: "online_handle".to_string(),
378                        })
379                    }
380                    _ => structured.facts.push(PersonalFactCandidate {
381                        subject_local_id: "owner".to_string(),
382                        predicate: key,
383                        value: entry.value.clone(),
384                        display_value: None,
385                        valid_from: None,
386                        valid_to: None,
387                        retract: false,
388                    }),
389                }
390                structured_indices.insert(index);
391            }
392
393            if !structured.entities.is_empty() {
394                let result = self
395                    .state
396                    .reconcile_personal_memory(
397                        &structured,
398                        "agent",
399                        None,
400                        channel_id.as_deref(),
401                        FactPrivacy::Private,
402                    )
403                    .await?;
404                results.push(format!("Personal memory: {}", result.concise_summary()));
405                for index in &structured_indices {
406                    let entry = &entries[*index];
407                    results.push(format!(
408                        "Remembered: [{}] {} = {} (canonical)",
409                        entry.category, entry.key, entry.value
410                    ));
411                }
412            }
413
414            for (index, entry) in entries.iter().enumerate() {
415                if structured_indices.contains(&index) || project_indices.contains(&index) {
416                    continue;
417                }
418                if entry.delete {
419                    let deleted = self
420                        .state
421                        .delete_fact_by_key(&entry.category, &entry.key)
422                        .await?;
423                    if deleted {
424                        results.push(format!("Deleted: [{}] {}", entry.category, entry.key));
425                    } else {
426                        results.push(format!(
427                            "Not found (nothing to delete): [{}] {}",
428                            entry.category, entry.key
429                        ));
430                    }
431                    continue;
432                }
433                if entry.value.trim().is_empty() {
434                    results.push(format!(
435                        "Not stored [{}] {}: value is empty (set delete: true to forget it)",
436                        entry.category, entry.key
437                    ));
438                    continue;
439                }
440
441                self.state
442                    .upsert_fact(
443                        &entry.category,
444                        &entry.key,
445                        &entry.value,
446                        "agent",
447                        channel_id.as_deref(),
448                        fact_privacy,
449                    )
450                    .await?;
451                results.push(format!(
452                    "Remembered: [{}] {} = {}",
453                    entry.category, entry.key, entry.value
454                ));
455            }
456
457            Ok(results.join("\n"))
458        }
459        .await;
460        let people_moved = call_carries_people(arguments);
461        output.map(|output| {
462            let mut outcome = aidaemon_tools::semantics::ToolCallOutcome::from_output(output);
463            if people_moved {
464                outcome.metadata.outcome_status =
465                    Some(aidaemon_tools::semantics::ToolOutcomeStatus::FailedPermanent);
466            }
467            outcome
468        })
469    }
470}
471
472/// Writes or deletes one entry in `project`'s notes, as a result line.
473async fn project_note(notes: Arc<ProjectNotes>, project: ProjectRef, entry: &FactEntry) -> String {
474    let kind = crate::project::kind_for_category(&entry.category);
475    let label = format!("[{}] {}", entry.category, entry.key);
476    let name = project.name.clone();
477    let category = entry.category.clone();
478    let key = entry.key.clone();
479    if entry.delete {
480        let deleted = tokio::task::spawn_blocking(move || notes.delete(&project, Some(kind), &key))
481            .await
482            .map_err(|error| error.to_string())
483            .and_then(|result| result.map_err(|error| error.to_string()));
484        return match deleted {
485            Ok(true) => format!("Deleted from project {name}: {label}"),
486            Ok(false) => format!("Not found in project {name} (nothing to delete): {label}"),
487            Err(error) => format!("Not deleted {label}: {error}"),
488        };
489    }
490    if entry.value.trim().is_empty() {
491        return format!("Not stored {label}: value is empty (set delete: true to forget it)");
492    }
493    let value = entry.value.clone();
494    let write = NoteWrite {
495        kind,
496        key,
497        category: Some(category),
498        description: None,
499        body: value.clone(),
500        source: NoteSource::Agent,
501    };
502    let written = tokio::task::spawn_blocking(move || notes.write(&project, &write))
503        .await
504        .map_err(|error| error.to_string())
505        .and_then(|result| result.map_err(|error| error.to_string()));
506    match written {
507        Ok(_) => {
508            let kind = if kind == NoteKind::Fact {
509                String::new()
510            } else {
511                format!(" ({})", kind.as_str())
512            };
513            format!("Remembered for project {name}{kind}: {label} = {value}")
514        }
515        Err(error) => format!("Not stored {label}: {error}"),
516    }
517}
518
519/// Whether the call still sends people (a non-empty `personal_memory`).
520/// Who may later see a fact this call stores, from the dispatcher's typed
521/// channel facts: the owner's direct or internal conversation keeps it
522/// general (only the owner's own turns see `Global`), a shared channel keeps
523/// it in that channel, and a call with no known channel keeps it private.
524fn write_access(
525    facts: &aidaemon_tools::semantics::ToolCallContext,
526    set_channel: Option<String>,
527) -> (FactPrivacy, Option<String>) {
528    use aidaemon_core::ChannelVisibility;
529    let channel_id = facts.channel_id.clone().or(set_channel);
530    match (facts.channel_visibility, channel_id) {
531        (Some(ChannelVisibility::Private | ChannelVisibility::Internal), channel_id) => {
532            (FactPrivacy::Global, channel_id)
533        }
534        (Some(ChannelVisibility::PrivateGroup | ChannelVisibility::Public), Some(channel_id)) => {
535            (FactPrivacy::Channel, Some(channel_id))
536        }
537        (_, channel_id) => (FactPrivacy::Private, channel_id),
538    }
539}
540
541fn call_carries_people(arguments: &str) -> bool {
542    serde_json::from_str::<RememberArgs>(arguments)
543        .ok()
544        .and_then(|args| args.personal_memory)
545        .is_some_and(|personal| {
546            !(personal.entities.is_empty()
547                && personal.aliases.is_empty()
548                && personal.facts.is_empty()
549                && personal.relationships.is_empty())
550        })
551}
552
553impl aidaemon_tools::semantics::ToolSemantics for RememberFactTool {
554    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
555        aidaemon_tools::semantics::ToolDispatchFacts {
556            offering: aidaemon_tools::semantics::Offering::Core,
557            activity: aidaemon_tools::semantics::ToolActivity::Fixed(
558                aidaemon_core::card::ActivityKind::Remember,
559            ),
560            channel_reach: aidaemon_tools::semantics::ChannelReach::Public,
561            status_label: Some("updating memory"),
562            ..Default::default()
563        }
564    }
565
566    fn tool_role(&self) -> ToolRole {
567        ToolRole::Universal
568    }
569
570    /// Memory is persistent agent state: a write is typed `configuration`
571    /// and a deletion is also `destructive`, so the receipt can prove a
572    /// checklist step declared with either label. An untyped receipt could
573    /// not, which made the model report a deletion it had just performed as
574    /// "already deleted".
575    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
576        if call_deletes_facts(arguments) {
577            ToolCallSemantics::mutation_with(
578                ToolMutationEffects::CONFIGURATION
579                    .union(ToolMutationEffects::MEMORY_WRITE)
580                    .union(ToolMutationEffects::DESTRUCTIVE),
581            )
582        } else {
583            ToolCallSemantics::mutation_with(
584                ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::MEMORY_WRITE),
585            )
586        }
587    }
588
589    fn capabilities(&self) -> ToolCapabilities {
590        ToolCapabilities::IDEMPOTENT_LOCAL_WRITE
591    }
592
593    /// Only the agent's own memory store changes, so a decline earlier in
594    /// the run never puts a fact to the owner.
595    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
596        aidaemon_core::CallEffects::none()
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use crate::full::tools::test_support::{ToolCalls as _, memory};
604    use crate::sqlite::SqliteMemory;
605    use aidaemon_tools::semantics::ToolSemantics;
606
607    async fn setup() -> (RememberFactTool, Arc<SqliteMemory>, ()) {
608        let state = memory().await;
609        (RememberFactTool::new(state.clone()), state, ())
610    }
611
612    #[tokio::test]
613    async fn empty_personal_memory_block_does_not_drop_batch_facts() {
614        let (tool, state, _db) = setup().await;
615        // Shape a live model sent: every schema section filled in, with the
616        // real content only in the top-level `facts` array.
617        let args = json!({
618            "category": "preference",
619            "key": "",
620            "value": "",
621            "facts": [
622                {"category": "personal", "key": "qa_codename", "value": "SYNTH-CODE-7"},
623                {"category": "preference", "key": "favorite_test_number", "value": "1729"}
624            ],
625            "personal_memory": {
626                "aliases": [], "entities": [], "facts": [], "relationships": [],
627                "correction": false, "direct_user_statement": true
628            }
629        });
630        let out = tool.call(&args.to_string()).await.unwrap();
631        assert!(!out.contains("already current"), "{out}");
632        assert!(out.contains("qa_codename = SYNTH-CODE-7"), "{out}");
633
634        let facts = state.get_facts(None).await.unwrap();
635        assert!(
636            facts
637                .iter()
638                .any(|f| f.key == "qa_codename" && f.value == "SYNTH-CODE-7")
639        );
640        assert!(
641            facts
642                .iter()
643                .any(|f| f.key == "favorite_test_number" && f.value == "1729")
644        );
645    }
646
647    #[tokio::test]
648    async fn empty_personal_memory_and_no_facts_is_an_error_not_a_noop() {
649        let (tool, _state, _db) = setup().await;
650        let args = json!({
651            "key": "",
652            "value": "",
653            "personal_memory": {"entities": [], "aliases": [], "facts": [], "relationships": []}
654        });
655        assert!(tool.call(&args.to_string()).await.is_err());
656    }
657
658    /// People moved to manage_people: a call that still sends them stores
659    /// nothing (not even the facts beside them) and says where they went.
660    #[tokio::test]
661    async fn a_call_with_people_names_manage_people_and_stores_nothing() {
662        let (tool, state, _db) = setup().await;
663        let args = json!({
664            "facts": [{"category": "preference", "key": "editor", "value": "synthetic-editor"}],
665            "personal_memory": {
666                "entities": [{"local_id": "zoe", "entity_type": "person", "canonical_name": "Zoe"}]
667            }
668        });
669        let outcome = tool
670            .execute(&args.to_string(), &Default::default())
671            .await
672            .unwrap();
673        assert!(
674            outcome.output.contains("manage_people"),
675            "{}",
676            outcome.output
677        );
678        assert_eq!(
679            outcome.metadata.outcome_status,
680            Some(aidaemon_tools::semantics::ToolOutcomeStatus::FailedPermanent)
681        );
682        assert!(state.get_facts(None).await.unwrap().is_empty());
683        assert!(state.get_canonical_memory_facts().await.unwrap().is_empty());
684    }
685
686    /// The owner's own profile keys still land in structured memory.
687    #[tokio::test]
688    async fn owner_profile_keys_still_reach_structured_memory() {
689        let (tool, state, _db) = setup().await;
690        let out = tool
691            .call(
692                &json!({"category": "user", "key": "birthday", "value": "1990-01-02"}).to_string(),
693            )
694            .await
695            .unwrap();
696        assert!(out.contains("(canonical)"), "{out}");
697        assert!(
698            state
699                .get_canonical_memory_facts()
700                .await
701                .unwrap()
702                .iter()
703                .any(|fact| fact.category == "user" && fact.value == "1990-01-02")
704        );
705    }
706
707    /// A value is stored as written: "none" is an answer, and wording such
708    /// as "from now on" is not an attack. Forgetting is the typed flag.
709    #[tokio::test]
710    async fn values_are_stored_as_written_and_delete_is_typed() {
711        let (tool, state, _db) = setup().await;
712        let stored = |key: &'static str| {
713            let state = state.clone();
714            async move {
715                state
716                    .get_facts(None)
717                    .await
718                    .unwrap()
719                    .into_iter()
720                    .find(|f| f.key == key)
721                    .map(|f| f.value)
722            }
723        };
724        for (key, value) in [
725            ("allergies", "none"),
726            ("middle_name", "N/A"),
727            ("work_schedule", "From now on I work remote Fridays"),
728            ("quarter_goal", "my goal is to ship the synthetic widget"),
729        ] {
730            let out = tool
731                .call(&json!({"category": "user", "key": key, "value": value}).to_string())
732                .await
733                .unwrap();
734            assert!(out.contains("Remembered"), "{out}");
735            assert_eq!(stored(key).await.as_deref(), Some(value));
736        }
737
738        let out = tool
739            .call(&json!({"category": "user", "key": "allergies", "delete": true}).to_string())
740            .await
741            .unwrap();
742        assert!(out.contains("Deleted"), "{out}");
743        assert_eq!(stored("allergies").await, None);
744
745        let out = tool
746            .call(&json!({"category": "user", "key": "middle_name", "value": ""}).to_string())
747            .await
748            .unwrap();
749        assert!(out.contains("Not stored"), "{out}");
750        assert_eq!(stored("middle_name").await.as_deref(), Some("N/A"));
751    }
752
753    #[tokio::test]
754    async fn memory_receipts_are_typed_for_checklist_credit() {
755        let (tool, _state, _db) = setup().await;
756        let effects = |args: Value| tool.call_semantics(&args.to_string()).mutation_effects;
757
758        let batch_delete = effects(json!({
759            "facts": [{"category": "user", "key": "qa_codename", "delete": true}],
760            "key": "", "value": ""
761        }));
762        assert!(batch_delete.satisfies(ToolMutationEffects::DESTRUCTIVE));
763        assert!(batch_delete.satisfies(ToolMutationEffects::CONFIGURATION));
764        assert!(
765            effects(json!({"category": "user", "key": "qa_codename", "delete": true}))
766                .satisfies(ToolMutationEffects::DESTRUCTIVE)
767        );
768        // A value that reads like a forget is a value.
769        assert!(
770            !effects(json!({"category": "user", "key": "qa_codename", "value": "delete"}))
771                .satisfies(ToolMutationEffects::DESTRUCTIVE)
772        );
773
774        let store = effects(json!({
775            "facts": [{"category": "user", "key": "qa_codename", "value": "SYNTH-CODE-7"}],
776            "key": "", "value": ""
777        }));
778        assert!(store.satisfies(ToolMutationEffects::CONFIGURATION));
779        assert!(!store.satisfies(ToolMutationEffects::DESTRUCTIVE));
780        // A plan that calls saving a fact a derived write can close, but a
781        // saved fact is never a workspace file, and a config change alone is
782        // not a saved fact.
783        assert!(store.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE));
784        assert!(!store.satisfies(ToolMutationEffects::LOCAL_WORKSPACE_WRITE));
785        assert!(
786            !ToolMutationEffects::CONFIGURATION.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE)
787        );
788        // An empty key names nothing to delete.
789        assert!(
790            !effects(json!({"key": "", "delete": true}))
791                .satisfies(ToolMutationEffects::DESTRUCTIVE)
792        );
793    }
794
795    #[test]
796    fn stored_privacy_follows_the_channel() {
797        use aidaemon_core::ChannelVisibility;
798        use aidaemon_tools::semantics::ToolCallContext;
799        let ctx = |visibility, channel: Option<&str>| ToolCallContext {
800            channel_visibility: visibility,
801            channel_id: channel.map(str::to_string),
802            ..Default::default()
803        };
804        assert_eq!(
805            write_access(&ctx(Some(ChannelVisibility::Private), None), None).0,
806            FactPrivacy::Global
807        );
808        assert_eq!(
809            write_access(
810                &ctx(
811                    Some(ChannelVisibility::PrivateGroup),
812                    Some("slack:C-synthetic")
813                ),
814                None
815            ),
816            (FactPrivacy::Channel, Some("slack:C-synthetic".to_string()))
817        );
818        // A shared channel without an id, or no channel facts at all, keeps
819        // the fact private rather than general.
820        assert_eq!(
821            write_access(&ctx(Some(ChannelVisibility::Public), None), None).0,
822            FactPrivacy::Private
823        );
824        assert_eq!(write_access(&ctx(None, None), None).0, FactPrivacy::Private);
825    }
826
827    mod project_scope {
828        use super::*;
829        use crate::project::{NoteKind, ProjectNotes};
830        use aidaemon_tools::semantics::ToolCallContext;
831
832        struct Fixture {
833            tool: RememberFactTool,
834            state: Arc<SqliteMemory>,
835            notes: Arc<ProjectNotes>,
836            project: ProjectRef,
837            _dir: tempfile::TempDir,
838        }
839
840        async fn fixture() -> Fixture {
841            let state = memory().await;
842            let dir = tempfile::tempdir().unwrap();
843            let notes = Arc::new(ProjectNotes::new(dir.path()));
844            let tool = RememberFactTool::new(state.clone()).with_project_notes(notes.clone());
845            let project = ProjectRef::new(
846                "project-00000000-0000-4000-8000-000000000001",
847                "Acme Site",
848                None,
849            )
850            .unwrap();
851            Fixture {
852                tool,
853                state,
854                notes,
855                project,
856                _dir: dir,
857            }
858        }
859
860        async fn call_in(
861            tool: &RememberFactTool,
862            project: Option<&ProjectRef>,
863            args: Value,
864        ) -> String {
865            let facts = ToolCallContext {
866                project: project.cloned(),
867                ..Default::default()
868            };
869            tool.execute(&args.to_string(), &facts)
870                .await
871                .unwrap()
872                .output
873        }
874
875        #[tokio::test]
876        async fn a_project_fact_never_touches_personal_memory() {
877            let f = fixture().await;
878            for (category, key, value) in [
879                ("user", "name", "Alice Rivera"),
880                ("preference", "editor", "vim"),
881                ("technical", "test_command", "pytest -q"),
882            ] {
883                f.state
884                    .upsert_fact(category, key, value, "user", None, FactPrivacy::Global)
885                    .await
886                    .unwrap();
887            }
888            let before = f.state.get_facts(None).await.unwrap();
889            // Same key as a personal fact, and a near-synonym of another.
890            let out = call_in(
891                &f.tool,
892                Some(&f.project),
893                json!({"facts": [
894                    {"category": "technical", "key": "test_command", "value": "make test"},
895                    {"category": "technical", "key": "editor_config", "value": "vim modelines are off here"}
896                ]}),
897            )
898            .await;
899            assert!(out.contains("Remembered for project Acme Site"), "{out}");
900            let after = f.state.get_facts(None).await.unwrap();
901            let ids = |facts: &[crate::records::Fact]| {
902                let mut v: Vec<_> = facts.iter().map(|x| (x.id, x.value.clone())).collect();
903                v.sort();
904                v
905            };
906            assert_eq!(ids(&before), ids(&after));
907            assert!(
908                f.notes
909                    .read(&f.project, NoteKind::Fact, "test_command")
910                    .unwrap()
911                    .contains("make test")
912            );
913            assert_eq!(f.notes.entries(&f.project).len(), 2);
914        }
915
916        #[tokio::test]
917        async fn without_a_project_nothing_changes() {
918            let f = fixture().await;
919            let out = call_in(
920                &f.tool,
921                None,
922                json!({"category": "technical", "key": "test_command", "value": "make test"}),
923            )
924            .await;
925            assert_eq!(out, "Remembered: [technical] test_command = make test");
926            assert!(f.notes.entries(&f.project).is_empty());
927            let out = call_in(
928                &f.tool,
929                None,
930                json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "project"}),
931            )
932            .await;
933            assert!(out.contains("project memory is not available"), "{out}");
934            assert!(
935                f.state
936                    .get_facts(None)
937                    .await
938                    .unwrap()
939                    .iter()
940                    .all(|x| x.key != "db")
941            );
942        }
943
944        #[tokio::test]
945        async fn the_owner_stays_personal_in_a_project() {
946            let f = fixture().await;
947            let out = call_in(
948                &f.tool,
949                Some(&f.project),
950                json!({"facts": [
951                    {"category": "user", "key": "residence", "value": "Springfield", "scope": "project"},
952                    {"category": "preference", "key": "indentation", "value": "tabs"},
953                    {"category": "technical", "key": "laptop", "value": "a synthetic laptop", "scope": "personal"}
954                ]}),
955            )
956            .await;
957            assert!(out.contains("canonical"), "{out}");
958            let facts = f.state.get_facts(None).await.unwrap();
959            assert!(facts.iter().any(|x| x.key == "indentation"), "{facts:?}");
960            assert!(facts.iter().any(|x| x.key == "laptop"), "{facts:?}");
961            assert!(f.notes.entries(&f.project).is_empty());
962        }
963
964        #[tokio::test]
965        async fn project_notes_are_deleted_by_key_and_bad_scopes_store_nothing() {
966            let f = fixture().await;
967            call_in(
968                &f.tool,
969                Some(&f.project),
970                json!({"category": "pitfall", "key": "migrations", "value": "Run migrations before seeding."}),
971            )
972            .await;
973            assert!(
974                f.notes
975                    .read(&f.project, NoteKind::Pitfall, "migrations")
976                    .is_some()
977            );
978            let out = call_in(
979                &f.tool,
980                Some(&f.project),
981                json!({"category": "pitfall", "key": "migrations", "delete": true}),
982            )
983            .await;
984            assert!(out.starts_with("Deleted from project"), "{out}");
985            assert!(f.notes.entries(&f.project).is_empty());
986            let out = call_in(
987                &f.tool,
988                Some(&f.project),
989                json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "team"}),
990            )
991            .await;
992            assert!(out.contains("scope must be"), "{out}");
993            assert!(f.notes.entries(&f.project).is_empty());
994            assert!(f.state.get_facts(None).await.unwrap().is_empty());
995        }
996
997        #[tokio::test]
998        async fn a_tool_without_notes_keeps_todays_behaviour_in_a_project() {
999            let state = memory().await;
1000            let tool = RememberFactTool::new(state.clone());
1001            let project = ProjectRef::new("project-x", "X", None).unwrap();
1002            let out = call_in(
1003                &tool,
1004                Some(&project),
1005                json!({"category": "technical", "key": "db", "value": "Postgres"}),
1006            )
1007            .await;
1008            assert_eq!(out, "Remembered: [technical] db = Postgres");
1009        }
1010    }
1011}