use std::fs;
use std::path::Path;
use agent_base::{AgentError, AgentResult};
use super::atomic_write;
use super::frontmatter::parse_memory_file;
fn index_line_desc(desc: &str) -> String {
desc.replace(['\n', '\r', '\u{2028}', '\u{2029}', '\u{85}'], " ")
.trim()
.to_string()
}
fn row_link_name(line: &str) -> Option<&str> {
let rest = line.strip_prefix("- [")?;
let close = rest.find("](")?;
let target = rest[close + 2..].split(')').next()?;
target.strip_suffix(".md")
}
fn row_head<'a>(line: &'a str, name: &str) -> Option<&'a str> {
if row_link_name(line) != Some(name) {
return None;
}
let close = line.find("](")?;
line.get(..close + 2 + name.len() + ".md)".len())
}
fn render_index_row(name: &str, desc: &str) -> String {
format!("- [{name}]({name}.md) — {}", index_line_desc(desc))
}
pub(crate) fn index_add(
memory_root: &Path,
index_filename: &str,
name: &str,
desc: &str,
) -> AgentResult<()> {
fs::create_dir_all(memory_root).map_err(|e| {
AgentError::internal(format!(
"failed to create memory dir {}: {e}",
memory_root.display()
))
})?;
let index_path = memory_root.join(index_filename);
let content = match fs::read_to_string(&index_path) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => {
return Err(AgentError::internal(format!(
"failed to read index {}: {e}",
index_path.display()
)));
}
};
let desc_line = index_line_desc(desc);
let updated = if content.lines().any(|line| row_head(line, name).is_some()) {
let mut out = content
.lines()
.map(|line| match row_head(line, name) {
Some(head) => format!("{head} — {desc_line}"),
None => line.to_string(),
})
.collect::<Vec<_>>()
.join("\n");
if content.ends_with('\n') {
out.push('\n');
}
out
} else {
let trimmed = content.trim_end();
let mut out = String::new();
if !trimmed.is_empty() {
out.push_str(trimmed);
out.push('\n');
}
out.push_str(&render_index_row(name, desc));
out.push('\n');
out
};
atomic_write(&index_path, &updated)
}
pub(crate) fn index_remove(
memory_root: &Path,
index_filename: &str,
name: &str,
) -> AgentResult<()> {
fs::create_dir_all(memory_root).map_err(|e| {
AgentError::internal(format!(
"failed to create memory dir {}: {e}",
memory_root.display()
))
})?;
let index_path = memory_root.join(index_filename);
let content = match fs::read_to_string(&index_path) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => {
return Err(AgentError::internal(format!(
"failed to read index {}: {e}",
index_path.display()
)));
}
};
let mut updated = content
.lines()
.filter(|line| row_link_name(line) != Some(name))
.collect::<Vec<_>>()
.join("\n");
if !updated.is_empty() && content.ends_with('\n') {
updated.push('\n');
}
atomic_write(&index_path, &updated)
}
fn find_row(index: &str, name: &str) -> Option<String> {
index
.lines()
.find(|line| row_head(line, name).is_some())
.map(str::to_string)
}
pub fn rebuild_index(memory_root: &Path, index_filename: &str) -> AgentResult<()> {
fs::create_dir_all(memory_root).map_err(|e| {
AgentError::internal(format!(
"failed to create memory dir {}: {e}",
memory_root.display()
))
})?;
let old_index = match fs::read_to_string(memory_root.join(index_filename)) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => {
return Err(AgentError::internal(format!(
"failed to read index {}: {e}",
memory_root.join(index_filename).display()
)));
}
};
let old_pos: Vec<&str> = old_index.lines().filter_map(row_link_name).collect();
let mut entries: Vec<(usize, String, String)> = Vec::new(); for entry in fs::read_dir(memory_root)? {
let path = entry?.path();
if path.extension() != Some("md".as_ref())
|| path.file_name() == Some(index_filename.as_ref())
{
continue;
}
let Some(name) = path.file_stem().map(|s| s.to_string_lossy().to_string()) else {
continue;
};
let regenerated = parse_memory_file(&path)
.ok()
.filter(|doc| doc.name == name)
.map(|doc| render_index_row(&doc.name, &doc.description));
let existing = find_row(&old_index, &name).map(|row| {
let order = old_pos
.iter()
.position(|n| *n == name)
.unwrap_or(usize::MAX);
(order, row)
});
match existing.or_else(|| regenerated.map(|row| (usize::MAX, row))) {
Some((order, row)) => entries.push((order, name, row)),
None => tracing::warn!(
file = %path.display(),
"skipping unindexable memory file with no existing index row"
),
}
}
entries.sort();
let content = if entries.is_empty() {
String::new()
} else {
entries
.into_iter()
.map(|(_, _, row)| row)
.collect::<Vec<_>>()
.join("\n")
+ "\n"
};
atomic_write(&memory_root.join(index_filename), &content)
}