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 pub current_channel_id: Arc<RwLock<Option<String>>>,
25 project_notes: Option<Arc<ProjectNotes>>,
28 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 pub fn with_project_notes(mut self, notes: Arc<ProjectNotes>) -> Self {
45 self.project_notes = Some(notes);
46 self
47 }
48
49 pub fn for_project(mut self, project: Option<ProjectRef>) -> Self {
51 self.turn_project = project;
52 self
53 }
54
55 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 #[serde(default)]
76 delete: bool,
77 #[serde(default)]
78 facts: Option<Vec<FactEntry>>,
79 #[serde(default)]
82 personal_memory: Option<PersonalMemoryWrite>,
83 #[serde(default)]
86 scope: Option<String>,
87 #[serde(default)]
89 evidence: Option<String>,
90}
91
92static SCOPE_SCHEMA: std::sync::LazyLock<Value> = std::sync::LazyLock::new(|| {
94 json!({
95 "type": "string",
96 "enum": ["project", "personal"],
97 "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."
98 })
99});
100
101static EVIDENCE_SCHEMA: std::sync::LazyLock<Value> = std::sync::LazyLock::new(|| {
106 json!({
107 "type": "string",
108 "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)."
109 })
110});
111
112static ENTRY_EVIDENCE_SCHEMA: std::sync::LazyLock<Value> =
114 std::sync::LazyLock::new(|| json!({"type": "string"}));
115
116static ENTRY_SCOPE_SCHEMA: std::sync::LazyLock<Value> =
118 std::sync::LazyLock::new(|| json!({"type": "string", "enum": ["project", "personal"]}));
119
120pub 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.";
122
123#[derive(Deserialize)]
124struct FactEntry {
125 category: String,
126 key: String,
127 #[serde(default)]
128 value: String,
129 #[serde(default)]
130 delete: bool,
131 #[serde(default)]
132 scope: Option<String>,
133 #[serde(default)]
134 evidence: Option<String>,
135}
136
137pub fn call_deletes_facts(arguments: &str) -> bool {
141 let Ok(args) = serde_json::from_str::<RememberArgs>(arguments) else {
142 return false;
143 };
144 match args.facts.filter(|facts| !facts.is_empty()) {
145 Some(facts) => facts.iter().any(|entry| entry.delete),
146 None => args.delete && args.key.is_some_and(|key| !key.trim().is_empty()),
147 }
148}
149
150#[async_trait]
151impl Tool for RememberFactTool {
152 fn name(&self) -> &str {
153 "remember_fact"
154 }
155
156 fn description(&self) -> &str {
157 "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."
158 }
159
160 fn schema(&self) -> Value {
161 json!({
162 "name": "remember_fact",
163 "description": self.description(),
164 "parameters": {
165 "type": "object",
166 "properties": {
167 "category": {
168 "type": "string",
169 "description": "Canonical categories: user (owner identity, name, addressing, location, birthday), preference (likes, style, communication), project (project details), technical (environment, tools)."
170 },
171 "key": {
172 "type": "string"
173 },
174 "value": {
175 "type": "string",
176 "description": "Stored as written, including \"none\"."
177 },
178 "delete": {
179 "type": "boolean",
180 "description": "Forget category/key; value is ignored."
181 },
182 "scope": SCOPE_SCHEMA.clone(),
183 "evidence": EVIDENCE_SCHEMA.clone(),
184 "facts": {
185 "type": "array",
186 "items": {
187 "type": "object",
188 "properties": {
189 "category": {
190 "type": "string"
191 },
192 "key": {
193 "type": "string"
194 },
195 "value": {
196 "type": "string",
197 "description": "Stored as written, including \"none\"."
198 },
199 "delete": {
200 "type": "boolean",
201 "description": "Forget this fact; value is ignored."
202 },
203 "scope": ENTRY_SCOPE_SCHEMA.clone(),
204 "evidence": ENTRY_EVIDENCE_SCHEMA.clone()
205 },
206 "required": ["category", "key"]
207 }
208 }
209 },
210 "additionalProperties": false
211 }
212 })
213 }
214
215 async fn execute(
216 &self,
217 arguments: &str,
218 call: &aidaemon_tools::semantics::ToolCallContext,
219 ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
220 let output: anyhow::Result<String> = async move {
221 let args: RememberArgs = serde_json::from_str(arguments)?;
222 let set_channel = self.current_channel_id.read().await.clone();
223 let (fact_privacy, channel_id) = write_access(call, set_channel);
224
225 let mut results = Vec::new();
226
227 if call_carries_people(arguments) {
231 return Ok(PEOPLE_MOVED.to_string());
232 }
233 let facts = args.facts.filter(|facts| !facts.is_empty());
234 let single_key = args.key.filter(|key| !key.trim().is_empty());
235
236 let entries: Vec<FactEntry> = if let Some(facts) = facts {
238 facts
239 } else {
240 let category = args.category.ok_or_else(|| {
242 anyhow::anyhow!("'category' is required (or use 'facts' array)")
243 })?;
244 let key = single_key
245 .ok_or_else(|| anyhow::anyhow!("'key' is required (or use 'facts' array)"))?;
246 let value = args.value.unwrap_or_default();
247 vec![FactEntry {
248 category,
249 key,
250 value,
251 delete: args.delete,
252 scope: None,
253 evidence: args.evidence.clone(),
254 }]
255 };
256 let call_scope = args.scope.clone();
258 let call_evidence = args.evidence.clone();
259 let entries: Vec<FactEntry> = entries
260 .into_iter()
261 .map(|mut entry| {
262 if entry.scope.is_none() {
263 entry.scope = call_scope.clone();
264 }
265 if entry.evidence.is_none() {
266 entry.evidence = call_evidence.clone();
267 }
268 entry
269 })
270 .collect();
271
272 let project = self.project(call);
276 let mut project_indices = std::collections::BTreeSet::new();
277 for (index, entry) in entries.iter().enumerate() {
278 let requested = match entry.scope.as_deref() {
279 None => None,
280 Some(raw) => match MemoryScope::parse(raw) {
281 Some(scope) => Some(scope),
282 None => {
283 results.push(format!(
284 "Not stored [{}] {}: scope must be \"project\" or \"personal\"",
285 entry.category, entry.key
286 ));
287 project_indices.insert(index);
288 continue;
289 }
290 },
291 };
292 let in_project = project.is_some();
293 if requested == Some(MemoryScope::Project) && !in_project {
294 results.push(format!(
295 "Not stored [{}] {}: project memory is not available in this conversation; leave scope out to remember it for the owner",
296 entry.category, entry.key
297 ));
298 project_indices.insert(index);
299 continue;
300 }
301 if crate::project::route(&entry.category, requested, in_project)
302 != MemoryScope::Project
303 {
304 continue;
305 }
306 project_indices.insert(index);
307 let Some((notes, project)) = project.clone() else {
308 continue;
309 };
310 results.push(project_note(notes, project, entry).await);
311 }
312
313 let mut structured_indices = std::collections::BTreeSet::new();
314 for (index, entry) in entries.iter().enumerate() {
315 if project_indices.contains(&index) {
316 continue;
317 }
318 let cat = entry.category.trim().to_ascii_lowercase();
319 let key = entry.key.trim().to_ascii_lowercase();
320 let canonical_key = crate::text::canonical_personal_key(&key);
321 let is_profile_cat = matches!(cat.as_str(), "user" | "personal" | "profile");
322 let is_pref_name =
323 cat == "preference" && crate::text::is_owner_name_key(&canonical_key);
324 let supported = (is_profile_cat && crate::text::is_owner_profile_key(&canonical_key))
325 || is_pref_name;
326 if !supported || entry.delete || entry.value.trim().is_empty() {
329 continue;
330 }
331 let (structured_source, structured_excerpt) =
335 structured_provenance(call, entry.evidence.as_deref());
336 let mut structured = PersonalMemoryWrite {
337 entities: vec![PersonalEntityCandidate {
338 local_id: "owner".to_string(),
339 entity_type: "person".to_string(),
340 canonical_name: if matches!(canonical_key.as_str(), "name" | "full_name") {
341 entry.value.clone()
342 } else {
343 "Owner".to_string()
344 },
345 is_reference: false,
346 canonical_name_confirmed: structured_source != "derived"
347 && matches!(canonical_key.as_str(), "name" | "full_name"),
348 }],
349 direct_user_statement: structured_source != "derived",
350 ..Default::default()
351 };
352 match canonical_key.as_str() {
353 "name" | "full_name" => structured.aliases.push(PersonalAliasCandidate {
354 entity_local_id: "owner".to_string(),
355 value: entry.value.clone(),
356 alias_type: "legal_name_variant".to_string(),
357 }),
358 "preferred_name" | "nickname" | "rejected_alias" => {
359 structured.aliases.push(PersonalAliasCandidate {
360 entity_local_id: "owner".to_string(),
361 value: entry.value.clone(),
362 alias_type: canonical_key,
363 })
364 }
365 "username" | "online_nickname" | "online_handle" | "handle" => {
366 structured.aliases.push(PersonalAliasCandidate {
367 entity_local_id: "owner".to_string(),
368 value: entry.value.clone(),
369 alias_type: "online_handle".to_string(),
370 })
371 }
372 _ => structured.facts.push(PersonalFactCandidate {
373 subject_local_id: "owner".to_string(),
374 predicate: canonical_key,
375 value: entry.value.clone(),
376 display_value: None,
377 valid_from: None,
378 valid_to: None,
379 retract: false,
380 }),
381 }
382 let result = self
383 .state
384 .reconcile_personal_memory(
385 &structured,
386 structured_source,
387 structured_excerpt.as_deref(),
388 channel_id.as_deref(),
389 FactPrivacy::Private,
390 )
391 .await?;
392 results.push(format!("Personal memory: {}", result.concise_summary()));
393 results.push(format!(
394 "Remembered: [{}] {} = {} (canonical)",
395 entry.category, entry.key, entry.value
396 ));
397 structured_indices.insert(index);
398 }
399
400 for (index, entry) in entries.iter().enumerate() {
401 if structured_indices.contains(&index) || project_indices.contains(&index) {
402 continue;
403 }
404 if entry.delete {
405 let deleted = self
406 .state
407 .delete_fact_by_key(&entry.category, &entry.key)
408 .await?;
409 if deleted {
410 results.push(format!("Deleted: [{}] {}", entry.category, entry.key));
411 } else {
412 results.push(format!(
413 "Not found (nothing to delete): [{}] {}",
414 entry.category, entry.key
415 ));
416 }
417 continue;
418 }
419 if entry.value.trim().is_empty() {
420 results.push(format!(
421 "Not stored [{}] {}: value is empty (set delete: true to forget it)",
422 entry.category, entry.key
423 ));
424 continue;
425 }
426
427 let (source, first_seen_at, source_excerpt) =
428 entry_provenance(call, entry.evidence.as_deref());
429 self.state
430 .upsert_fact_with_provenance(
431 &entry.category,
432 &entry.key,
433 &entry.value,
434 source,
435 channel_id.as_deref(),
436 fact_privacy,
437 first_seen_at,
438 source_excerpt.as_deref(),
439 )
440 .await?;
441 results.push(format!(
442 "Remembered: [{}] {} = {}",
443 entry.category, entry.key, entry.value
444 ));
445 }
446
447 Ok(results.join("\n"))
448 }
449 .await;
450 let people_moved = call_carries_people(arguments);
451 output.map(|output| {
452 let mut outcome = aidaemon_tools::semantics::ToolCallOutcome::from_output(output);
453 if people_moved {
454 outcome.metadata.outcome_status =
455 Some(aidaemon_tools::semantics::ToolOutcomeStatus::FailedPermanent);
456 }
457 outcome
458 })
459 }
460}
461
462async fn project_note(notes: Arc<ProjectNotes>, project: ProjectRef, entry: &FactEntry) -> String {
464 let kind = crate::project::kind_for_category(&entry.category);
465 let label = format!("[{}] {}", entry.category, entry.key);
466 let name = project.name.clone();
467 let category = entry.category.clone();
468 let key = entry.key.clone();
469 if entry.delete {
470 let deleted = tokio::task::spawn_blocking(move || notes.delete(&project, Some(kind), &key))
471 .await
472 .map_err(|error| error.to_string())
473 .and_then(|result| result.map_err(|error| error.to_string()));
474 return match deleted {
475 Ok(true) => format!("Deleted from project {name}: {label}"),
476 Ok(false) => format!("Not found in project {name} (nothing to delete): {label}"),
477 Err(error) => format!("Not deleted {label}: {error}"),
478 };
479 }
480 if entry.value.trim().is_empty() {
481 return format!("Not stored {label}: value is empty (set delete: true to forget it)");
482 }
483 let value = entry.value.clone();
484 let write = NoteWrite {
485 kind,
486 key,
487 category: Some(category),
488 description: None,
489 body: value.clone(),
490 source: NoteSource::Agent,
491 };
492 let written = tokio::task::spawn_blocking(move || notes.write(&project, &write))
493 .await
494 .map_err(|error| error.to_string())
495 .and_then(|result| result.map_err(|error| error.to_string()));
496 match written {
497 Ok(_) => {
498 let kind = if kind == NoteKind::Fact {
499 String::new()
500 } else {
501 format!(" ({})", kind.as_str())
502 };
503 format!("Remembered for project {name}{kind}: {label} = {value}")
504 }
505 Err(error) => format!("Not stored {label}: {error}"),
506 }
507}
508
509fn write_access(
515 facts: &aidaemon_tools::semantics::ToolCallContext,
516 set_channel: Option<String>,
517) -> (FactPrivacy, Option<String>) {
518 use aidaemon_core::ChannelVisibility;
519 let channel_id = facts.channel_id.clone().or(set_channel);
520 match (facts.channel_visibility, channel_id) {
521 (Some(ChannelVisibility::Private | ChannelVisibility::Internal), channel_id) => {
522 (FactPrivacy::Global, channel_id)
523 }
524 (Some(ChannelVisibility::PrivateGroup | ChannelVisibility::Public), Some(channel_id)) => {
525 (FactPrivacy::Channel, Some(channel_id))
526 }
527 (_, channel_id) => (FactPrivacy::Private, channel_id),
528 }
529}
530
531fn entry_provenance(
540 call: &aidaemon_tools::semantics::ToolCallContext,
541 evidence: Option<&str>,
542) -> (
543 &'static str,
544 Option<chrono::DateTime<chrono::Utc>>,
545 Option<String>,
546) {
547 let Some(user_message) = call.user_message.as_deref() else {
548 let excerpt = evidence
549 .map(str::trim)
550 .filter(|e| !e.is_empty())
551 .map(|e| crate::text::truncate_chars(e, 200));
552 return ("agent", None, excerpt);
553 };
554 let owner_authored =
555 matches!(call.user_role, Some(aidaemon_core::UserRole::Owner)) && !call.untrusted_source;
556 let quoted = owner_authored
557 && evidence.is_some_and(|quote| crate::progressive::quote_occurs_in(quote, user_message));
558 let source = if quoted { "user_stated" } else { "derived" };
559 let excerpt = if quoted {
560 evidence.map(|e| crate::text::truncate_chars(e.trim(), 200))
561 } else {
562 let trimmed = user_message.trim();
563 (!trimmed.is_empty()).then(|| crate::text::truncate_chars(trimmed, 200))
564 };
565 (source, Some(chrono::Utc::now()), excerpt)
566}
567
568fn structured_provenance(
569 call: &aidaemon_tools::semantics::ToolCallContext,
570 evidence: Option<&str>,
571) -> (&'static str, Option<String>) {
572 let (source, _, excerpt) = entry_provenance(call, evidence);
573 (source, excerpt)
574}
575
576fn call_carries_people(arguments: &str) -> bool {
577 serde_json::from_str::<RememberArgs>(arguments)
578 .ok()
579 .and_then(|args| args.personal_memory)
580 .is_some_and(|personal| {
581 !(personal.entities.is_empty()
582 && personal.aliases.is_empty()
583 && personal.facts.is_empty()
584 && personal.relationships.is_empty())
585 })
586}
587
588impl aidaemon_tools::semantics::ToolSemantics for RememberFactTool {
589 fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
590 aidaemon_tools::semantics::ToolDispatchFacts {
591 offering: aidaemon_tools::semantics::Offering::Core,
592 activity: aidaemon_tools::semantics::ToolActivity::Fixed(
593 aidaemon_core::card::ActivityKind::Remember,
594 ),
595 channel_reach: aidaemon_tools::semantics::ChannelReach::Public,
596 status_label: Some("updating memory"),
597 ..Default::default()
598 }
599 }
600
601 fn tool_role(&self) -> ToolRole {
602 ToolRole::Universal
603 }
604
605 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
611 if call_deletes_facts(arguments) {
612 ToolCallSemantics::mutation_with(
613 ToolMutationEffects::CONFIGURATION
614 .union(ToolMutationEffects::MEMORY_WRITE)
615 .union(ToolMutationEffects::DESTRUCTIVE),
616 )
617 } else {
618 ToolCallSemantics::mutation_with(
619 ToolMutationEffects::CONFIGURATION.union(ToolMutationEffects::MEMORY_WRITE),
620 )
621 }
622 }
623
624 fn capabilities(&self) -> ToolCapabilities {
625 ToolCapabilities::IDEMPOTENT_LOCAL_WRITE
626 }
627
628 fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
631 aidaemon_core::CallEffects::none()
632 }
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638 use crate::full::tools::test_support::{ToolCalls as _, memory};
639 use crate::sqlite::SqliteMemory;
640 use aidaemon_tools::semantics::ToolSemantics;
641
642 async fn setup() -> (RememberFactTool, Arc<SqliteMemory>, ()) {
643 let state = memory().await;
644 (RememberFactTool::new(state.clone()), state, ())
645 }
646
647 #[tokio::test]
648 async fn empty_personal_memory_block_does_not_drop_batch_facts() {
649 let (tool, state, _db) = setup().await;
650 let args = json!({
653 "category": "preference",
654 "key": "",
655 "value": "",
656 "facts": [
657 {"category": "personal", "key": "qa_codename", "value": "SYNTH-CODE-7"},
658 {"category": "preference", "key": "favorite_test_number", "value": "1729"}
659 ],
660 "personal_memory": {
661 "aliases": [], "entities": [], "facts": [], "relationships": [],
662 "correction": false, "direct_user_statement": true
663 }
664 });
665 let out = tool.call(&args.to_string()).await.unwrap();
666 assert!(!out.contains("already current"), "{out}");
667 assert!(out.contains("qa_codename = SYNTH-CODE-7"), "{out}");
668
669 let facts = state.get_facts(None).await.unwrap();
670 assert!(
671 facts
672 .iter()
673 .any(|f| f.key == "qa_codename" && f.value == "SYNTH-CODE-7")
674 );
675 assert!(
676 facts
677 .iter()
678 .any(|f| f.key == "favorite_test_number" && f.value == "1729")
679 );
680 }
681
682 #[tokio::test]
683 async fn empty_personal_memory_and_no_facts_is_an_error_not_a_noop() {
684 let (tool, _state, _db) = setup().await;
685 let args = json!({
686 "key": "",
687 "value": "",
688 "personal_memory": {"entities": [], "aliases": [], "facts": [], "relationships": []}
689 });
690 assert!(tool.call(&args.to_string()).await.is_err());
691 }
692
693 #[tokio::test]
696 async fn a_call_with_people_names_manage_people_and_stores_nothing() {
697 let (tool, state, _db) = setup().await;
698 let args = json!({
699 "facts": [{"category": "preference", "key": "editor", "value": "synthetic-editor"}],
700 "personal_memory": {
701 "entities": [{"local_id": "zoe", "entity_type": "person", "canonical_name": "Zoe"}]
702 }
703 });
704 let outcome = tool
705 .execute(&args.to_string(), &Default::default())
706 .await
707 .unwrap();
708 assert!(
709 outcome.output.contains("manage_people"),
710 "{}",
711 outcome.output
712 );
713 assert_eq!(
714 outcome.metadata.outcome_status,
715 Some(aidaemon_tools::semantics::ToolOutcomeStatus::FailedPermanent)
716 );
717 assert!(state.get_facts(None).await.unwrap().is_empty());
718 assert!(state.get_canonical_memory_facts().await.unwrap().is_empty());
719 }
720
721 #[tokio::test]
723 async fn owner_profile_keys_still_reach_structured_memory() {
724 let (tool, state, _db) = setup().await;
725 let out = tool
726 .call(
727 &json!({"category": "user", "key": "birthday", "value": "1990-01-02"}).to_string(),
728 )
729 .await
730 .unwrap();
731 assert!(out.contains("(canonical)"), "{out}");
732 assert!(
733 state
734 .get_canonical_memory_facts()
735 .await
736 .unwrap()
737 .iter()
738 .any(|fact| fact.category == "user" && fact.value == "1990-01-02")
739 );
740 }
741
742 #[tokio::test]
745 async fn values_are_stored_as_written_and_delete_is_typed() {
746 let (tool, state, _db) = setup().await;
747 let stored = |key: &'static str| {
748 let state = state.clone();
749 async move {
750 state
751 .get_facts(None)
752 .await
753 .unwrap()
754 .into_iter()
755 .find(|f| f.key == key)
756 .map(|f| f.value)
757 }
758 };
759 for (key, value) in [
760 ("allergies", "none"),
761 ("middle_name", "N/A"),
762 ("work_schedule", "From now on I work remote Fridays"),
763 ("quarter_goal", "my goal is to ship the synthetic widget"),
764 ] {
765 let out = tool
766 .call(&json!({"category": "user", "key": key, "value": value}).to_string())
767 .await
768 .unwrap();
769 assert!(out.contains("Remembered"), "{out}");
770 assert_eq!(stored(key).await.as_deref(), Some(value));
771 }
772
773 let out = tool
774 .call(&json!({"category": "user", "key": "allergies", "delete": true}).to_string())
775 .await
776 .unwrap();
777 assert!(out.contains("Deleted"), "{out}");
778 assert_eq!(stored("allergies").await, None);
779
780 let out = tool
781 .call(&json!({"category": "user", "key": "middle_name", "value": ""}).to_string())
782 .await
783 .unwrap();
784 assert!(out.contains("Not stored"), "{out}");
785 assert_eq!(stored("middle_name").await.as_deref(), Some("N/A"));
786 }
787
788 #[tokio::test]
789 async fn memory_receipts_are_typed_for_checklist_credit() {
790 let (tool, _state, _db) = setup().await;
791 let effects = |args: Value| tool.call_semantics(&args.to_string()).mutation_effects;
792
793 let batch_delete = effects(json!({
794 "facts": [{"category": "user", "key": "qa_codename", "delete": true}],
795 "key": "", "value": ""
796 }));
797 assert!(batch_delete.satisfies(ToolMutationEffects::DESTRUCTIVE));
798 assert!(batch_delete.satisfies(ToolMutationEffects::CONFIGURATION));
799 assert!(
800 effects(json!({"category": "user", "key": "qa_codename", "delete": true}))
801 .satisfies(ToolMutationEffects::DESTRUCTIVE)
802 );
803 assert!(
805 !effects(json!({"category": "user", "key": "qa_codename", "value": "delete"}))
806 .satisfies(ToolMutationEffects::DESTRUCTIVE)
807 );
808
809 let store = effects(json!({
810 "facts": [{"category": "user", "key": "qa_codename", "value": "SYNTH-CODE-7"}],
811 "key": "", "value": ""
812 }));
813 assert!(store.satisfies(ToolMutationEffects::CONFIGURATION));
814 assert!(!store.satisfies(ToolMutationEffects::DESTRUCTIVE));
815 assert!(store.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE));
819 assert!(!store.satisfies(ToolMutationEffects::LOCAL_WORKSPACE_WRITE));
820 assert!(
821 !ToolMutationEffects::CONFIGURATION.satisfies(ToolMutationEffects::LOCAL_DERIVED_WRITE)
822 );
823 assert!(
825 !effects(json!({"key": "", "delete": true}))
826 .satisfies(ToolMutationEffects::DESTRUCTIVE)
827 );
828 }
829
830 #[test]
831 fn stored_privacy_follows_the_channel() {
832 use aidaemon_core::ChannelVisibility;
833 use aidaemon_tools::semantics::ToolCallContext;
834 let ctx = |visibility, channel: Option<&str>| ToolCallContext {
835 channel_visibility: visibility,
836 channel_id: channel.map(str::to_string),
837 ..Default::default()
838 };
839 assert_eq!(
840 write_access(&ctx(Some(ChannelVisibility::Private), None), None).0,
841 FactPrivacy::Global
842 );
843 assert_eq!(
844 write_access(
845 &ctx(
846 Some(ChannelVisibility::PrivateGroup),
847 Some("slack:C-synthetic")
848 ),
849 None
850 ),
851 (FactPrivacy::Channel, Some("slack:C-synthetic".to_string()))
852 );
853 assert_eq!(
856 write_access(&ctx(Some(ChannelVisibility::Public), None), None).0,
857 FactPrivacy::Private
858 );
859 assert_eq!(write_access(&ctx(None, None), None).0, FactPrivacy::Private);
860 }
861
862 mod project_scope {
863 use super::*;
864 use crate::project::{NoteKind, ProjectNotes};
865 use aidaemon_tools::semantics::ToolCallContext;
866
867 struct Fixture {
868 tool: RememberFactTool,
869 state: Arc<SqliteMemory>,
870 notes: Arc<ProjectNotes>,
871 project: ProjectRef,
872 _dir: tempfile::TempDir,
873 }
874
875 async fn fixture() -> Fixture {
876 let state = memory().await;
877 let dir = tempfile::tempdir().unwrap();
878 let notes = Arc::new(ProjectNotes::new(dir.path()));
879 let tool = RememberFactTool::new(state.clone()).with_project_notes(notes.clone());
880 let project = ProjectRef::new(
881 "project-00000000-0000-4000-8000-000000000001",
882 "Acme Site",
883 None,
884 )
885 .unwrap();
886 Fixture {
887 tool,
888 state,
889 notes,
890 project,
891 _dir: dir,
892 }
893 }
894
895 async fn call_in(
896 tool: &RememberFactTool,
897 project: Option<&ProjectRef>,
898 args: Value,
899 ) -> String {
900 let facts = ToolCallContext {
901 project: project.cloned(),
902 ..Default::default()
903 };
904 tool.execute(&args.to_string(), &facts)
905 .await
906 .unwrap()
907 .output
908 }
909
910 #[tokio::test]
911 async fn a_project_fact_never_touches_personal_memory() {
912 let f = fixture().await;
913 for (category, key, value) in [
914 ("user", "name", "Alice Rivera"),
915 ("preference", "editor", "vim"),
916 ("technical", "test_command", "pytest -q"),
917 ] {
918 f.state
919 .upsert_fact(category, key, value, "user", None, FactPrivacy::Global)
920 .await
921 .unwrap();
922 }
923 let before = f.state.get_facts(None).await.unwrap();
924 let out = call_in(
926 &f.tool,
927 Some(&f.project),
928 json!({"facts": [
929 {"category": "technical", "key": "test_command", "value": "make test"},
930 {"category": "technical", "key": "editor_config", "value": "vim modelines are off here"}
931 ]}),
932 )
933 .await;
934 assert!(out.contains("Remembered for project Acme Site"), "{out}");
935 let after = f.state.get_facts(None).await.unwrap();
936 let ids = |facts: &[crate::records::Fact]| {
937 let mut v: Vec<_> = facts.iter().map(|x| (x.id, x.value.clone())).collect();
938 v.sort();
939 v
940 };
941 assert_eq!(ids(&before), ids(&after));
942 assert!(
943 f.notes
944 .read(&f.project, NoteKind::Fact, "test_command")
945 .unwrap()
946 .contains("make test")
947 );
948 assert_eq!(f.notes.entries(&f.project).len(), 2);
949 }
950
951 #[tokio::test]
952 async fn without_a_project_nothing_changes() {
953 let f = fixture().await;
954 let out = call_in(
955 &f.tool,
956 None,
957 json!({"category": "technical", "key": "test_command", "value": "make test"}),
958 )
959 .await;
960 assert_eq!(out, "Remembered: [technical] test_command = make test");
961 assert!(f.notes.entries(&f.project).is_empty());
962 let out = call_in(
963 &f.tool,
964 None,
965 json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "project"}),
966 )
967 .await;
968 assert!(out.contains("project memory is not available"), "{out}");
969 assert!(
970 f.state
971 .get_facts(None)
972 .await
973 .unwrap()
974 .iter()
975 .all(|x| x.key != "db")
976 );
977 }
978
979 #[tokio::test]
980 async fn the_owner_stays_personal_in_a_project() {
981 let f = fixture().await;
982 let out = call_in(
983 &f.tool,
984 Some(&f.project),
985 json!({"facts": [
986 {"category": "user", "key": "residence", "value": "Springfield", "scope": "project"},
987 {"category": "preference", "key": "indentation", "value": "tabs"},
988 {"category": "technical", "key": "laptop", "value": "a synthetic laptop", "scope": "personal"}
989 ]}),
990 )
991 .await;
992 assert!(out.contains("canonical"), "{out}");
993 let facts = f.state.get_facts(None).await.unwrap();
994 assert!(facts.iter().any(|x| x.key == "indentation"), "{facts:?}");
995 assert!(facts.iter().any(|x| x.key == "laptop"), "{facts:?}");
996 assert!(f.notes.entries(&f.project).is_empty());
997 }
998
999 #[tokio::test]
1000 async fn project_notes_are_deleted_by_key_and_bad_scopes_store_nothing() {
1001 let f = fixture().await;
1002 call_in(
1003 &f.tool,
1004 Some(&f.project),
1005 json!({"category": "pitfall", "key": "migrations", "value": "Run migrations before seeding."}),
1006 )
1007 .await;
1008 assert!(
1009 f.notes
1010 .read(&f.project, NoteKind::Pitfall, "migrations")
1011 .is_some()
1012 );
1013 let out = call_in(
1014 &f.tool,
1015 Some(&f.project),
1016 json!({"category": "pitfall", "key": "migrations", "delete": true}),
1017 )
1018 .await;
1019 assert!(out.starts_with("Deleted from project"), "{out}");
1020 assert!(f.notes.entries(&f.project).is_empty());
1021 let out = call_in(
1022 &f.tool,
1023 Some(&f.project),
1024 json!({"category": "technical", "key": "db", "value": "Postgres", "scope": "team"}),
1025 )
1026 .await;
1027 assert!(out.contains("scope must be"), "{out}");
1028 assert!(f.notes.entries(&f.project).is_empty());
1029 assert!(f.state.get_facts(None).await.unwrap().is_empty());
1030 }
1031
1032 #[tokio::test]
1033 async fn a_tool_without_notes_keeps_todays_behaviour_in_a_project() {
1034 let state = memory().await;
1035 let tool = RememberFactTool::new(state.clone());
1036 let project = ProjectRef::new("project-x", "X", None).unwrap();
1037 let out = call_in(
1038 &tool,
1039 Some(&project),
1040 json!({"category": "technical", "key": "db", "value": "Postgres"}),
1041 )
1042 .await;
1043 assert_eq!(out, "Remembered: [technical] db = Postgres");
1044 }
1045 }
1046
1047 #[tokio::test]
1048 async fn synchronous_provenance_distinguishes_quoted_from_derived() {
1049 let (tool, state, _db) = setup().await;
1050 let owner_ctx = aidaemon_tools::semantics::ToolCallContext {
1051 user_role: Some(aidaemon_core::UserRole::Owner),
1052 channel_visibility: Some(aidaemon_core::ChannelVisibility::Private),
1053 user_message: Some("My favorite tea is sencha green tea.".to_string()),
1054 ..Default::default()
1055 };
1056 tool.execute(
1058 &json!({
1059 "category": "preference",
1060 "key": "favorite_tea",
1061 "value": "sencha green tea",
1062 "evidence": "My favorite tea is sencha green tea"
1063 })
1064 .to_string(),
1065 &owner_ctx,
1066 )
1067 .await
1068 .unwrap();
1069 tool.execute(
1071 &json!({
1072 "category": "preference",
1073 "key": "inferred_habit",
1074 "value": "Drinks tea every morning"
1075 })
1076 .to_string(),
1077 &owner_ctx,
1078 )
1079 .await
1080 .unwrap();
1081
1082 let facts = state.get_facts(Some("preference")).await.unwrap();
1083 let tea = facts.iter().find(|f| f.key == "favorite_tea").unwrap();
1084 assert_eq!(tea.source, "user_stated");
1085 let habit = facts.iter().find(|f| f.key == "inferred_habit").unwrap();
1086 assert_eq!(habit.source, "derived");
1087 }
1088
1089 #[tokio::test]
1090 async fn preference_owner_name_and_addressing_promote_to_canonical() {
1091 let (tool, state, _db) = setup().await;
1092 let owner_ctx = aidaemon_tools::semantics::ToolCallContext {
1093 user_role: Some(aidaemon_core::UserRole::Owner),
1094 channel_visibility: Some(aidaemon_core::ChannelVisibility::Private),
1095 user_message: Some("Call me Alice, not Ally.".to_string()),
1096 ..Default::default()
1097 };
1098 let out = tool
1099 .execute(
1100 &json!({
1101 "facts": [
1102 {
1103 "category": "preference",
1104 "key": "preferred_name",
1105 "value": "Alice",
1106 "evidence": "Call me Alice"
1107 },
1108 {
1109 "category": "preference",
1110 "key": "address_as",
1111 "value": "Call the owner Alice. Don't call her Ally.",
1112 "evidence": "Call me Alice, not Ally"
1113 }
1114 ]
1115 })
1116 .to_string(),
1117 &owner_ctx,
1118 )
1119 .await
1120 .unwrap()
1121 .output;
1122 assert!(out.contains("(canonical)"), "{out}");
1123 assert!(
1124 state
1125 .get_facts(Some("preference"))
1126 .await
1127 .unwrap()
1128 .is_empty(),
1129 "owner name/addressing must promote to canonical memory instead of duplicating in flat preference"
1130 );
1131 let canonical = state.get_canonical_memory_facts().await.unwrap();
1132 assert!(
1133 canonical
1134 .iter()
1135 .any(|f| f.category == "user" && f.key == "preferred_name" && f.value == "Alice"),
1136 "{canonical:?}"
1137 );
1138 assert!(
1139 canonical
1140 .iter()
1141 .any(|f| f.category == "user" && f.key == "addressing" && f.value.contains("Ally")),
1142 "{canonical:?}"
1143 );
1144 }
1145
1146 #[tokio::test]
1147 async fn structured_batch_verifies_evidence_per_entry_without_sharing_authority() {
1148 let (tool, state, _db) = setup().await;
1149 let owner_ctx = aidaemon_tools::semantics::ToolCallContext {
1150 user_role: Some(aidaemon_core::UserRole::Owner),
1151 channel_visibility: Some(aidaemon_core::ChannelVisibility::Private),
1152 user_message: Some("Call me Alice.".to_string()),
1153 ..Default::default()
1154 };
1155 tool.execute(
1156 &json!({
1157 "facts": [
1158 {
1159 "category": "user",
1160 "key": "preferred_name",
1161 "value": "Alice",
1162 "evidence": "Call me Alice"
1163 },
1164 {
1165 "category": "user",
1166 "key": "residence",
1167 "value": "Seattle"
1168 }
1169 ]
1170 })
1171 .to_string(),
1172 &owner_ctx,
1173 )
1174 .await
1175 .unwrap();
1176 let canonical = state.get_canonical_memory_facts().await.unwrap();
1177 let name = canonical
1178 .iter()
1179 .find(|f| f.key == "preferred_name")
1180 .expect("preferred_name stored");
1181 let residence = canonical
1182 .iter()
1183 .find(|f| f.key == "residence")
1184 .expect("residence stored");
1185 assert_eq!(name.source, "canonical:user_stated");
1186 assert_eq!(residence.source, "canonical:derived");
1187 }
1188}