1use crate::MemoryStore;
2
3#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
9#[serde(default)]
10pub struct MemoryPromptConfig {
11 pub enabled: bool,
13 pub max_items: usize,
15 pub max_chars: usize,
17}
18
19impl Default for MemoryPromptConfig {
20 fn default() -> Self {
21 Self {
22 enabled: false,
23 max_items: 5,
24 max_chars: 2000,
25 }
26 }
27}
28
29const HIDDEN_OUTPUT_PATTERNS: &[&str] = &[
33 "<tool_result>",
35 "</tool_result>",
36 "Tool output:",
37 "is_error:",
38 "tool_call",
39 "tool_result",
40 "\"type\": \"tool_result\"",
42 "\"type\":\"tool_result\"",
43 "\"role\": \"tool\"",
44 "\"role\":\"tool\"",
45 "tool_use",
47 "tool_use_id",
48 "function_call",
49 "< tool_result",
52 "tool_result >",
53 "<tool_result ",
54 "<system>",
56 "</system>",
57 "<system-reminder",
58 "system-reminder",
59];
60
61pub(crate) fn is_hidden_output(content: &str) -> bool {
67 let normalized = collapse_whitespace(content.trim());
68 let lower = normalized.to_lowercase();
69 HIDDEN_OUTPUT_PATTERNS.iter().any(|pat| lower.contains(pat))
70}
71
72fn collapse_whitespace(s: &str) -> std::borrow::Cow<'_, str> {
73 if !s.contains(" ") {
74 return std::borrow::Cow::Borrowed(s);
75 }
76 std::borrow::Cow::Owned(s.replace(" ", " "))
77}
78
79pub fn format_memory_prompt(
85 store: &MemoryStore,
86 query: &str,
87 config: &MemoryPromptConfig,
88) -> Option<String> {
89 if !config.enabled || query.trim().is_empty() {
90 return None;
91 }
92
93 let results = store.retrieve(query, config.max_items).ok()?;
94 if results.is_empty() {
95 return None;
96 }
97
98 let mut items = Vec::new();
99 let header = "## Relevant Memory\n";
100 let mut total_len = header.len();
101
102 for result in &results {
103 if is_hidden_output(&result.item.content) {
105 continue;
106 }
107
108 let source_ref = result
109 .evidence
110 .first()
111 .map(|e| e.source_ref.as_str())
112 .unwrap_or("unknown");
113
114 let reinforced = result.item.last_reinforced.format("%Y-%m-%d");
115
116 let line = if result.item.contradiction_ref.is_some() {
117 format!(
118 "- ⚠ CONTRADICTION: [confidence={:.1}] {} (source: {}, reinforced: {})\n",
119 result.item.confidence, result.item.content, source_ref, reinforced,
120 )
121 } else {
122 format!(
123 "- [confidence={:.1}] {} (source: {}, reinforced: {})\n",
124 result.item.confidence, result.item.content, source_ref, reinforced,
125 )
126 };
127
128 let line_len = line.len();
130 if total_len + line_len > config.max_chars {
131 let truncation_notice = "... (memory section truncated)";
133 if total_len + truncation_notice.len() <= config.max_chars {
135 items.push(truncation_notice.to_string());
136 }
137 break;
138 }
139
140 items.push(line);
141 total_len += line_len;
142 }
143
144 if items.is_empty() {
145 return None;
147 }
148
149 let mut output = String::with_capacity(config.max_chars);
150 output.push_str(header);
151 for item in &items {
152 output.push_str(item);
153 }
154
155 Some(output)
156}