use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use agent_base::{AgentError, AgentResult};
use super::frontmatter::{EntryFields, parse_memory_file, render_memory_file_merged};
use super::{
DEFAULT_INDEX_FILENAME, atomic_write, index_remove, now_iso8601, project_slug,
render_index_from_disk, validate_memory_name, validate_memory_type,
};
#[derive(Debug, Clone, PartialEq)]
pub struct MemoryLimits {
pub enabled: bool,
pub hook_max_chars: usize,
pub body_max_chars: usize,
pub index_max_bytes: usize,
pub index_warn_bytes: usize,
pub store_max_bytes: usize,
pub store_soft_entries: usize,
pub store_hard_entries: usize,
}
impl Default for MemoryLimits {
fn default() -> Self {
Self {
enabled: true,
hook_max_chars: 80,
body_max_chars: 3000,
index_max_bytes: 10_240,
index_warn_bytes: 8192,
store_max_bytes: 2_097_152,
store_soft_entries: 300,
store_hard_entries: 500,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LimitRejection {
pub rule: String,
pub limit: usize,
pub actual: usize,
pub name: String,
pub fix: String,
pub candidate: String,
}
impl LimitRejection {
pub fn to_wire(&self) -> String {
serde_json::json!({
"ok": false,
"rule": self.rule,
"limit": self.limit,
"actual": self.actual,
"name": self.name,
"fix": self.fix,
"candidate": self.candidate,
})
.to_string()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum WriteOutcome {
Written { created: bool },
Rejected(LimitRejection),
}
fn trim_to_chars(s: &str, max: usize) -> String {
s.chars().take(max).collect()
}
#[derive(Debug, Clone)]
pub struct MemoryConfig {
pub memory_root: PathBuf,
pub index_filename: String,
pub prompt_template: String,
pub limits: MemoryLimits,
}
pub const CLAUDE_COMPATIBLE_TEMPLATE: &str = r#"## Memory
You have a persistent memory directory at `{memory_root}`. Memories survive across sessions and are shared with Claude Code (same directory, same format — what you write here, Claude Code reads, and vice versa).
### Current memory index
The snapshot below was taken at startup and may be stale — call `memory_list` to refresh whenever unsure.
{index_content}
### Tools
{tools_description}
### How to remember
- `memory_write` stores one memory as `<name>.md` and syncs the index automatically. `name` must match `^[a-z0-9][a-z0-9-]*$`; writing to an existing `name` overwrites it in place (update instead of duplicating; prefer overwriting rolling `project` memories like status notes over creating new ones).
- The `description` is the recall key — one line (no newlines) that lets you tell at a glance whether the memory matters for the current task.
- Types: `user` (who the user is: role, preferences, working style), `feedback` (rules and corrections the user gave you), `project` (ongoing work, decisions, status), `reference` (pointers to external resources).
- Link related memories with `[[memory-name]]` in the body.
### When to use memory
- The user explicitly asks to remember something ("remember this", "save that").
- You learn a durable preference, correction, or project fact worth carrying into future sessions.
### When NOT to use memory
- Transient details that only matter within this session.
- Facts already recorded in the codebase (code structure, git history, config files).
### How to recall
Scan the index above by `description` and open only the relevant ones — the index row names the file, and it lives beside `MEMORY.md` in the memory directory. Recall is selective by design — do not read everything."#;
impl MemoryConfig {
pub fn claude_compatible(workspace: &Path) -> Self {
let home = dirs::home_dir().unwrap_or_else(|| {
tracing::warn!("home directory not found; memory root falls back to temp dir");
std::env::temp_dir()
});
Self::custom(
home.join(".claude")
.join("projects")
.join(project_slug(workspace))
.join("memory"),
CLAUDE_COMPATIBLE_TEMPLATE.to_string(),
)
}
pub fn custom(memory_root: PathBuf, prompt_template: String) -> Self {
Self {
memory_root,
index_filename: DEFAULT_INDEX_FILENAME.to_string(),
prompt_template,
limits: MemoryLimits::default(),
}
}
}
pub struct MemoryStore {
memory_root: PathBuf,
index_filename: String,
limits: MemoryLimits,
index_lock: Mutex<()>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MemoryListEntry {
pub name: String,
pub description: String,
pub memory_type: Option<String>,
pub modified: Option<String>,
}
impl MemoryStore {
pub fn new(memory_root: PathBuf, index_filename: impl Into<String>) -> Self {
Self::with_limits(memory_root, index_filename, MemoryLimits::default())
}
pub fn with_limits(
memory_root: PathBuf,
index_filename: impl Into<String>,
limits: MemoryLimits,
) -> Self {
Self {
memory_root,
index_filename: index_filename.into(),
limits,
index_lock: Mutex::new(()),
}
}
pub fn memory_root(&self) -> &Path {
&self.memory_root
}
pub fn index_filename(&self) -> &str {
&self.index_filename
}
pub fn limits(&self) -> &MemoryLimits {
&self.limits
}
pub fn index_path(&self) -> PathBuf {
self.memory_root.join(&self.index_filename)
}
fn memory_path(&self, name: &str) -> PathBuf {
self.memory_root.join(format!("{name}.md"))
}
pub fn read_index(&self) -> String {
fs::read_to_string(self.index_path()).unwrap_or_default()
}
pub fn render_index(&self) -> AgentResult<String> {
render_index_from_disk(&self.memory_root, &self.index_filename)
}
pub fn ensure_dir(&self) -> AgentResult<()> {
fs::create_dir_all(&self.memory_root).map_err(|e| {
AgentError::internal(format!(
"failed to create memory dir {}: {e}",
self.memory_root.display()
))
})
}
pub fn write_memory(
&self,
name: &str,
description: &str,
memory_type: &str,
body: &str,
origin_session_id: Option<&str>,
) -> AgentResult<WriteOutcome> {
self.write_memory_entry(
name,
description,
memory_type,
body,
origin_session_id,
&EntryFields::default(),
)
}
pub fn write_memory_entry(
&self,
name: &str,
description: &str,
memory_type: &str,
body: &str,
origin_session_id: Option<&str>,
entry: &EntryFields,
) -> AgentResult<WriteOutcome> {
validate_memory_name(name)?;
validate_memory_type(memory_type)?;
if description
.chars()
.any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}' | '\u{85}'))
{
return Err(AgentError::internal(
"invalid memory description: must be a single line (no newlines)",
));
}
self.ensure_dir()?;
if let Some(rej) = self.check_entry_limits(name, description, body) {
return Ok(WriteOutcome::Rejected(rej));
}
let _guard = self.index_lock.lock().unwrap();
let file_path = self.memory_path(name);
let original = fs::read_to_string(&file_path).ok();
let file = render_memory_file_merged(
original.as_deref(),
name,
description,
memory_type,
origin_session_id,
Some(&now_iso8601()),
entry,
body,
)?;
if let Some(rej) = self.check_store_limits(name, original.as_deref(), &file) {
return Ok(WriteOutcome::Rejected(rej));
}
let created = original.is_none();
atomic_write(&file_path, &file)?;
let index_content = render_index_from_disk(&self.memory_root, &self.index_filename)?;
if self.limits.enabled && index_content.len() > self.limits.index_max_bytes {
self.restore_pre_write(&file_path, original.as_deref());
return Ok(WriteOutcome::Rejected(LimitRejection {
rule: "index_max_bytes".to_string(),
limit: self.limits.index_max_bytes,
actual: index_content.len(),
name: name.to_string(),
fix: format!(
"the index is {}/{} bytes — run `memory_tidy` or archive \
entries to shrink it, then retry",
index_content.len(),
self.limits.index_max_bytes
),
candidate: String::new(),
}));
}
if let Err(e) = atomic_write(&self.index_path(), &index_content) {
self.restore_pre_write(&file_path, original.as_deref());
tracing::warn!(
error = %e,
name,
"index write failed after body write; body restored (best-effort)"
);
return Err(e);
}
Ok(WriteOutcome::Written { created })
}
fn check_entry_limits(
&self,
name: &str,
description: &str,
body: &str,
) -> Option<LimitRejection> {
if !self.limits.enabled {
return None;
}
let hook_chars = description.chars().count();
if hook_chars > self.limits.hook_max_chars {
return Some(LimitRejection {
rule: "hook_max_chars".to_string(),
limit: self.limits.hook_max_chars,
actual: hook_chars,
name: name.to_string(),
fix: format!(
"compress the hook to <={} chars; move the detail into the body",
self.limits.hook_max_chars
),
candidate: trim_to_chars(description, self.limits.hook_max_chars),
});
}
let body_chars = body.chars().count();
if body_chars > self.limits.body_max_chars {
return Some(LimitRejection {
rule: "body_max_chars".to_string(),
limit: self.limits.body_max_chars,
actual: body_chars,
name: name.to_string(),
fix: format!(
"the body is {body_chars} chars — one fact per memory; trim \
it to <={} chars or split the memory",
self.limits.body_max_chars
),
candidate: trim_to_chars(body, self.limits.body_max_chars),
});
}
None
}
fn check_store_limits(
&self,
name: &str,
original: Option<&str>,
new_file: &str,
) -> Option<LimitRejection> {
if !self.limits.enabled {
return None;
}
let (count, total_bytes) = self.store_stats();
if original.is_none() && count + 1 > self.limits.store_hard_entries {
return Some(LimitRejection {
rule: "store_hard_entries".to_string(),
limit: self.limits.store_hard_entries,
actual: count + 1,
name: name.to_string(),
fix: format!(
"the store already holds {count} entries (limit {}) — \
archive or delete some (`memory_tidy` / `memory_delete`), then retry",
self.limits.store_hard_entries
),
candidate: String::new(),
});
}
let old_bytes = original.map(str::len).unwrap_or(0);
let projected = total_bytes - old_bytes + new_file.len();
if projected > self.limits.store_max_bytes {
return Some(LimitRejection {
rule: "store_max_bytes".to_string(),
limit: self.limits.store_max_bytes,
actual: projected,
name: name.to_string(),
fix: format!(
"the store would reach {projected} bytes (limit {}) — \
archive or delete entries (`memory_tidy`), then retry",
self.limits.store_max_bytes
),
candidate: String::new(),
});
}
None
}
fn store_stats(&self) -> (usize, usize) {
let mut count = 0usize;
let mut total = 0usize;
let Ok(dir) = fs::read_dir(&self.memory_root) else {
return (0, 0);
};
for entry in dir.flatten() {
let path = entry.path();
if path.extension() != Some("md".as_ref())
|| path.file_name() == Some(self.index_filename.as_ref())
{
continue;
}
count += 1;
total += entry.metadata().map(|m| m.len() as usize).unwrap_or(0);
}
(count, total)
}
fn restore_pre_write(&self, path: &Path, original: Option<&str>) {
let result = match original {
Some(content) => fs::write(path, content),
None => fs::remove_file(path),
};
if let Err(e) = result {
tracing::warn!(
error = %e,
path = %path.display(),
"write rollback failed; leaving an orphan file"
);
}
}
pub fn read_memory(&self, name: &str) -> AgentResult<String> {
validate_memory_name(name)?;
let path = self.memory_path(name);
fs::read_to_string(&path).map_err(|_| {
AgentError::internal(format!(
"memory `{name}` not found (looked at {})",
path.display()
))
})
}
pub fn delete_memory(&self, name: &str) -> AgentResult<()> {
validate_memory_name(name)?;
let path = self.memory_path(name);
if !path.exists() {
return Err(AgentError::internal(format!(
"memory `{name}` not found (looked at {})",
path.display()
)));
}
{
let _guard = self.index_lock.lock().unwrap();
index_remove(&self.memory_root, &self.index_filename, name)?;
}
fs::remove_file(&path)
.map_err(|e| AgentError::internal(format!("failed to delete memory `{name}`: {e}")))
}
pub fn list_memories(&self) -> Vec<MemoryListEntry> {
let mut entries = Vec::new();
let Ok(dir) = fs::read_dir(&self.memory_root) else {
return entries; };
for entry in dir.flatten() {
let path = entry.path();
if path.extension() != Some("md".as_ref())
|| path.file_name() == Some(self.index_filename.as_ref())
{
continue;
}
if let Ok(doc) = parse_memory_file(&path) {
entries.push(MemoryListEntry {
name: doc.name,
description: doc.description,
memory_type: doc.metadata.as_ref().map(|m| m.memory_type.clone()),
modified: doc.metadata.as_ref().and_then(|m| m.modified.clone()),
});
}
}
entries.sort_by(|a, b| a.name.cmp(&b.name));
entries
}
}