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 {
591            read_only: false,
592            external_side_effect: false,
593            needs_approval: false,
594            idempotent: true,
595            high_impact_write: false,
596        }
597    }
598
599    /// Only the agent's own memory store changes, so a decline earlier in
600    /// the run never puts a fact to the owner.
601    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
602        aidaemon_core::CallEffects::none()
603    }
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609    use crate::full::tools::test_support::{ToolCalls as _, memory};
610    use crate::sqlite::SqliteMemory;
611    use aidaemon_tools::semantics::ToolSemantics;
612
613    async fn setup() -> (RememberFactTool, Arc<SqliteMemory>, ()) {
614        let state = memory().await;
615        (RememberFactTool::new(state.clone()), state, ())
616    }
617
618    #[tokio::test]
619    async fn empty_personal_memory_block_does_not_drop_batch_facts() {
620        let (tool, state, _db) = setup().await;
621        // Shape a live model sent: every schema section filled in, with the
622        // real content only in the top-level `facts` array.
623        let args = json!({
624            "category": "preference",
625            "key": "",
626            "value": "",
627            "facts": [
628                {"category": "personal", "key": "qa_codename", "value": "SYNTH-CODE-7"},
629                {"category": "preference", "key": "favorite_test_number", "value": "1729"}
630            ],
631            "personal_memory": {
632                "aliases": [], "entities": [], "facts": [], "relationships": [],
633                "correction": false, "direct_user_statement": true
634            }
635        });
636        let out = tool.call(&args.to_string()).await.unwrap();
637        assert!(!out.contains("already current"), "{out}");
638        assert!(out.contains("qa_codename = SYNTH-CODE-7"), "{out}");
639
640        let facts = state.get_facts(None).await.unwrap();
641        assert!(
642            facts
643                .iter()
644                .any(|f| f.key == "qa_codename" && f.value == "SYNTH-CODE-7")
645        );
646        assert!(
647            facts
648                .iter()
649                .any(|f| f.key == "favorite_test_number" && f.value == "1729")
650        );
651    }
652
653    #[tokio::test]
654    async fn empty_personal_memory_and_no_facts_is_an_error_not_a_noop() {
655        let (tool, _state, _db) = setup().await;
656        let args = json!({
657            "key": "",
658            "value": "",
659            "personal_memory": {"entities": [], "aliases": [], "facts": [], "relationships": []}
660        });
661        assert!(tool.call(&args.to_string()).await.is_err());
662    }
663
664    /// People moved to manage_people: a call that still sends them stores
665    /// nothing (not even the facts beside them) and says where they went.
666    #[tokio::test]
667    async fn a_call_with_people_names_manage_people_and_stores_nothing() {
668        let (tool, state, _db) = setup().await;
669        let args = json!({
670            "facts": [{"category": "preference", "key": "editor", "value": "synthetic-editor"}],
671            "personal_memory": {
672                "entities": [{"local_id": "zoe", "entity_type": "person", "canonical_name": "Zoe"}]
673            }
674        });
675        let outcome = tool
676            .execute(&args.to_string(), &Default::default())
677            .await
678            .unwrap();
679        assert!(
680            outcome.output.contains("manage_people"),
681            "{}",
682            outcome.output
683        );
684        assert_eq!(
685            outcome.metadata.outcome_status,
686            Some(aidaemon_tools::semantics::ToolOutcomeStatus::FailedPermanent)
687        );
688        assert!(state.get_facts(None).await.unwrap().is_empty());
689        assert!(state.get_canonical_memory_facts().await.unwrap().is_empty());
690    }
691
692    /// The owner's own profile keys still land in structured memory.
693    #[tokio::test]
694    async fn owner_profile_keys_still_reach_structured_memory() {
695        let (tool, state, _db) = setup().await;
696        let out = tool
697            .call(
698                &json!({"category": "user", "key": "birthday", "value": "1990-01-02"}).to_string(),
699            )
700            .await
701            .unwrap();
702        assert!(out.contains("(canonical)"), "{out}");
703        assert!(
704            state
705                .get_canonical_memory_facts()
706                .await
707                .unwrap()
708                .iter()
709                .any(|fact| fact.category == "user" && fact.value == "1990-01-02")
710        );
711    }
712
713    /// A value is stored as written: "none" is an answer, and wording such
714    /// as "from now on" is not an attack. Forgetting is the typed flag.
715    #[tokio::test]
716    async fn values_are_stored_as_written_and_delete_is_typed() {
717        let (tool, state, _db) = setup().await;
718        let stored = |key: &'static str| {
719            let state = state.clone();
720            async move {
721                state
722                    .get_facts(None)
723                    .await
724                    .unwrap()
725                    .into_iter()
726                    .find(|f| f.key == key)
727                    .map(|f| f.value)
728            }
729        };
730        for (key, value) in [
731            ("allergies", "none"),
732            ("middle_name", "N/A"),
733            ("work_schedule", "From now on I work remote Fridays"),
734            ("quarter_goal", "my goal is to ship the synthetic widget"),
735        ] {
736            let out = tool
737                .call(&json!({"category": "user", "key": key, "value": value}).to_string())
738                .await
739                .unwrap();
740            assert!(out.contains("Remembered"), "{out}");
741            assert_eq!(stored(key).await.as_deref(), Some(value));
742        }
743
744        let out = tool
745            .call(&json!({"category": "user", "key": "allergies", "delete": true}).to_string())
746            .await
747            .unwrap();
748        assert!(out.contains("Deleted"), "{out}");
749        assert_eq!(stored("allergies").await, None);
750
751        let out = tool
752            .call(&json!({"category": "user", "key": "middle_name", "value": ""}).to_string())
753            .await
754            .unwrap();
755        assert!(out.contains("Not stored"), "{out}");
756        assert_eq!(stored("middle_name").await.as_deref(), Some("N/A"));
757    }
758
759    #[tokio::test]
760    async fn memory_receipts_are_typed_for_checklist_credit() {
761        let (tool, _state, _db) = setup().await;
762        let effects = |args: Value| tool.call_semantics(&args.to_string()).mutation_effects;
763
764        let batch_delete = effects(json!({
765            "facts": [{"category": "user", "key": "qa_codename", "delete": true}],
766            "key": "", "value": ""
767        }));
768        assert!(batch_delete.satisfies(ToolMutationEffects::DESTRUCTIVE));
769        assert!(batch_delete.satisfies(ToolMutationEffects::CONFIGURATION));
770        assert!(
771            effects(json!({"category": "user", "key": "qa_codename", "delete": true}))
772                .satisfies(ToolMutationEffects::DESTRUCTIVE)
773        );
774        // A value that reads like a forget is a value.
775        assert!(
776            !effects(json!({"category": "user", "key": "qa_codename", "value": "delete"}))
777                .satisfies(ToolMutationEffects::DESTRUCTIVE)
778        );
779
780        let store = effects(json!({
781            "facts": [{"category": "user", "key": "qa_codename", "value": "SYNTH-CODE-7"}],
782            "key": "", "value": ""
783        }));
784        assert!(store.satisfies(ToolMutationEffects::CONFIGURATION));
785        assert!(!store.satisfies(ToolMutationEffects::DESTRUCTIVE));
786        // A plan that calls saving a fact a derived write can close, but a
787        // saved fact is never a workspace file, and a config change alone is
788        // not a saved fact.
789        assert!(store.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE));
790        assert!(!store.satisfies(ToolMutationEffects::LOCAL_WORKSPACE_WRITE));
791        assert!(
792            !ToolMutationEffects::CONFIGURATION.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE)
793        );
794        // An empty key names nothing to delete.
795        assert!(
796            !effects(json!({"key": "", "delete": true}))
797                .satisfies(ToolMutationEffects::DESTRUCTIVE)
798        );
799    }
800
801    #[test]
802    fn stored_privacy_follows_the_channel() {
803        use aidaemon_core::ChannelVisibility;
804        use aidaemon_tools::semantics::ToolCallContext;
805        let ctx = |visibility, channel: Option<&str>| ToolCallContext {
806            channel_visibility: visibility,
807            channel_id: channel.map(str::to_string),
808            ..Default::default()
809        };
810        assert_eq!(
811            write_access(&ctx(Some(ChannelVisibility::Private), None), None).0,
812            FactPrivacy::Global
813        );
814        assert_eq!(
815            write_access(
816                &ctx(
817                    Some(ChannelVisibility::PrivateGroup),
818                    Some("slack:C-synthetic")
819                ),
820                None
821            ),
822            (FactPrivacy::Channel, Some("slack:C-synthetic".to_string()))
823        );
824        // A shared channel without an id, or no channel facts at all, keeps
825        // the fact private rather than general.
826        assert_eq!(
827            write_access(&ctx(Some(ChannelVisibility::Public), None), None).0,
828            FactPrivacy::Private
829        );
830        assert_eq!(write_access(&ctx(None, None), None).0, FactPrivacy::Private);
831    }
832
833    mod project_scope {
834        use super::*;
835        use crate::project::{NoteKind, ProjectNotes};
836        use aidaemon_tools::semantics::ToolCallContext;
837
838        struct Fixture {
839            tool: RememberFactTool,
840            state: Arc<SqliteMemory>,
841            notes: Arc<ProjectNotes>,
842            project: ProjectRef,
843            _dir: tempfile::TempDir,
844        }
845
846        async fn fixture() -> Fixture {
847            let state = memory().await;
848            let dir = tempfile::tempdir().unwrap();
849            let notes = Arc::new(ProjectNotes::new(dir.path()));
850            let tool = RememberFactTool::new(state.clone()).with_project_notes(notes.clone());
851            let project = ProjectRef::new(
852                "project-00000000-0000-4000-8000-000000000001",
853                "Acme Site",
854                None,
855            )
856            .unwrap();
857            Fixture {
858                tool,
859                state,
860                notes,
861                project,
862                _dir: dir,
863            }
864        }
865
866        async fn call_in(
867            tool: &RememberFactTool,
868            project: Option<&ProjectRef>,
869            args: Value,
870        ) -> String {
871            let facts = ToolCallContext {
872                project: project.cloned(),
873                ..Default::default()
874            };
875            tool.execute(&args.to_string(), &facts)
876                .await
877                .unwrap()
878                .output
879        }
880
881        #[tokio::test]
882        async fn a_project_fact_never_touches_personal_memory() {
883            let f = fixture().await;
884            for (category, key, value) in [
885                ("user", "name", "Alice Rivera"),
886                ("preference", "editor", "vim"),
887                ("technical", "test_command", "pytest -q"),
888            ] {
889                f.state
890                    .upsert_fact(category, key, value, "user", None, FactPrivacy::Global)
891                    .await
892                    .unwrap();
893            }
894            let before = f.state.get_facts(None).await.unwrap();
895            // Same key as a personal fact, and a near-synonym of another.
896            let out = call_in(
897                &f.tool,
898                Some(&f.project),
899                json!({"facts": [
900                    {"category": "technical", "key": "test_command", "value": "make test"},
901                    {"category": "technical", "key": "editor_config", "value": "vim modelines are off here"}
902                ]}),
903            )
904            .await;
905            assert!(out.contains("Remembered for project Acme Site"), "{out}");
906            let after = f.state.get_facts(None).await.unwrap();
907            let ids = |facts: &[crate::records::Fact]| {
908                let mut v: Vec<_> = facts.iter().map(|x| (x.id, x.value.clone())).collect();
909                v.sort();
910                v
911            };
912            assert_eq!(ids(&before), ids(&after));
913            assert!(
914                f.notes
915                    .read(&f.project, NoteKind::Fact, "test_command")
916                    .unwrap()
917                    .contains("make test")
918            );
919            assert_eq!(f.notes.entries(&f.project).len(), 2);
920        }
921
922        #[tokio::test]
923        async fn without_a_project_nothing_changes() {
924            let f = fixture().await;
925            let out = call_in(
926                &f.tool,
927                None,
928                json!({"category": "technical", "key": "test_command", "value": "make test"}),
929            )
930            .await;
931            assert_eq!(out, "Remembered: [technical] test_command = make test");
932            assert!(f.notes.entries(&f.project).is_empty());
933            let out = call_in(
934                &f.tool,
935                None,
936                json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "project"}),
937            )
938            .await;
939            assert!(out.contains("project memory is not available"), "{out}");
940            assert!(
941                f.state
942                    .get_facts(None)
943                    .await
944                    .unwrap()
945                    .iter()
946                    .all(|x| x.key != "db")
947            );
948        }
949
950        #[tokio::test]
951        async fn the_owner_stays_personal_in_a_project() {
952            let f = fixture().await;
953            let out = call_in(
954                &f.tool,
955                Some(&f.project),
956                json!({"facts": [
957                    {"category": "user", "key": "residence", "value": "Springfield", "scope": "project"},
958                    {"category": "preference", "key": "indentation", "value": "tabs"},
959                    {"category": "technical", "key": "laptop", "value": "a synthetic laptop", "scope": "personal"}
960                ]}),
961            )
962            .await;
963            assert!(out.contains("canonical"), "{out}");
964            let facts = f.state.get_facts(None).await.unwrap();
965            assert!(facts.iter().any(|x| x.key == "indentation"), "{facts:?}");
966            assert!(facts.iter().any(|x| x.key == "laptop"), "{facts:?}");
967            assert!(f.notes.entries(&f.project).is_empty());
968        }
969
970        #[tokio::test]
971        async fn project_notes_are_deleted_by_key_and_bad_scopes_store_nothing() {
972            let f = fixture().await;
973            call_in(
974                &f.tool,
975                Some(&f.project),
976                json!({"category": "pitfall", "key": "migrations", "value": "Run migrations before seeding."}),
977            )
978            .await;
979            assert!(
980                f.notes
981                    .read(&f.project, NoteKind::Pitfall, "migrations")
982                    .is_some()
983            );
984            let out = call_in(
985                &f.tool,
986                Some(&f.project),
987                json!({"category": "pitfall", "key": "migrations", "delete": true}),
988            )
989            .await;
990            assert!(out.starts_with("Deleted from project"), "{out}");
991            assert!(f.notes.entries(&f.project).is_empty());
992            let out = call_in(
993                &f.tool,
994                Some(&f.project),
995                json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "team"}),
996            )
997            .await;
998            assert!(out.contains("scope must be"), "{out}");
999            assert!(f.notes.entries(&f.project).is_empty());
1000            assert!(f.state.get_facts(None).await.unwrap().is_empty());
1001        }
1002
1003        #[tokio::test]
1004        async fn a_tool_without_notes_keeps_todays_behaviour_in_a_project() {
1005            let state = memory().await;
1006            let tool = RememberFactTool::new(state.clone());
1007            let project = ProjectRef::new("project-x", "X", None).unwrap();
1008            let out = call_in(
1009                &tool,
1010                Some(&project),
1011                json!({"category": "technical", "key": "db", "value": "Postgres"}),
1012            )
1013            .await;
1014            assert_eq!(out, "Remembered: [technical] db = Postgres");
1015        }
1016    }
1017}