use crate::MemoryStore;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(default)]
pub struct MemoryPromptConfig {
pub enabled: bool,
pub max_items: usize,
pub max_chars: usize,
}
impl Default for MemoryPromptConfig {
fn default() -> Self {
Self {
enabled: false,
max_items: 5,
max_chars: 2000,
}
}
}
const HIDDEN_OUTPUT_PATTERNS: &[&str] = &[
"<tool_result>",
"</tool_result>",
"Tool output:",
"is_error:",
"tool_call",
"tool_result",
"\"type\": \"tool_result\"",
"\"type\":\"tool_result\"",
"\"role\": \"tool\"",
"\"role\":\"tool\"",
"tool_use",
"tool_use_id",
"function_call",
"< tool_result",
"tool_result >",
"<tool_result ",
"<system>",
"</system>",
"<system-reminder",
"system-reminder",
];
pub(crate) fn is_hidden_output(content: &str) -> bool {
let normalized = collapse_whitespace(content.trim());
let lower = normalized.to_lowercase();
HIDDEN_OUTPUT_PATTERNS.iter().any(|pat| lower.contains(pat))
}
fn collapse_whitespace(s: &str) -> std::borrow::Cow<'_, str> {
if !s.contains(" ") {
return std::borrow::Cow::Borrowed(s);
}
std::borrow::Cow::Owned(s.replace(" ", " "))
}
pub fn format_memory_prompt(
store: &MemoryStore,
query: &str,
config: &MemoryPromptConfig,
) -> Option<String> {
if !config.enabled || query.trim().is_empty() {
return None;
}
let results = store.retrieve(query, config.max_items).ok()?;
if results.is_empty() {
return None;
}
let mut items = Vec::new();
let header = "## Relevant Memory\n";
let mut total_len = header.len();
for result in &results {
if is_hidden_output(&result.item.content) {
continue;
}
let source_ref = result
.evidence
.first()
.map(|e| e.source_ref.as_str())
.unwrap_or("unknown");
let reinforced = result.item.last_reinforced.format("%Y-%m-%d");
let line = if result.item.contradiction_ref.is_some() {
format!(
"- ⚠ CONTRADICTION: [confidence={:.1}] {} (source: {}, reinforced: {})\n",
result.item.confidence, result.item.content, source_ref, reinforced,
)
} else {
format!(
"- [confidence={:.1}] {} (source: {}, reinforced: {})\n",
result.item.confidence, result.item.content, source_ref, reinforced,
)
};
let line_len = line.len();
if total_len + line_len > config.max_chars {
let truncation_notice = "... (memory section truncated)";
if total_len + truncation_notice.len() <= config.max_chars {
items.push(truncation_notice.to_string());
}
break;
}
items.push(line);
total_len += line_len;
}
if items.is_empty() {
return None;
}
let mut output = String::with_capacity(config.max_chars);
output.push_str(header);
for item in &items {
output.push_str(item);
}
Some(output)
}