141 lines
5.0 KiB
Rust
141 lines
5.0 KiB
Rust
//! Agent memory: `MEMORY.md` index (in the system prompt) + `topics/<slug>.md` (read on demand).
|
||
//! Scopes: global `<hx home>/memory`, project `<cwd>/.hx/memory`.
|
||
|
||
use std::path::{Path, PathBuf};
|
||
|
||
/// Index size cap per scope. A full index makes `write` fail so the agent consolidates or forgets.
|
||
// ponytail: line count, not tokens; one index line is capped at ~100 chars so 50 lines ≈ 1.5k tokens.
|
||
pub const MAX_LINES: usize = 50;
|
||
const HOOK_CHARS: usize = 100;
|
||
|
||
pub fn dir(project: bool, home: &Path, cwd: &Path) -> PathBuf {
|
||
if project {
|
||
cwd.join(".hx/memory")
|
||
} else {
|
||
home.join("memory")
|
||
}
|
||
}
|
||
|
||
fn valid_slug(s: &str) -> bool {
|
||
!s.is_empty()
|
||
&& s.len() <= 64
|
||
&& s.chars()
|
||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
|
||
}
|
||
|
||
fn prefix(slug: &str) -> String {
|
||
format!("- [{slug}](")
|
||
}
|
||
|
||
fn lines(dir: &Path) -> Vec<String> {
|
||
std::fs::read_to_string(dir.join("MEMORY.md"))
|
||
.unwrap_or_default()
|
||
.lines()
|
||
.filter(|l| !l.trim().is_empty())
|
||
.map(String::from)
|
||
.collect()
|
||
}
|
||
|
||
fn save(dir: &Path, l: &[String]) -> Result<(), String> {
|
||
let mut s = l.join("\n");
|
||
s.push('\n');
|
||
std::fs::write(dir.join("MEMORY.md"), s).map_err(|e| e.to_string())
|
||
}
|
||
|
||
/// Create or replace topic `slug`; upserts its index line.
|
||
pub fn write(dir: &Path, slug: &str, hook: &str, body: &str) -> Result<(), String> {
|
||
if !valid_slug(slug) {
|
||
return Err("slug must be 1-64 chars of a-z 0-9 - _".into());
|
||
}
|
||
let hook: String = hook.split_whitespace().collect::<Vec<_>>().join(" ");
|
||
if hook.is_empty() {
|
||
return Err("hook (one-line summary) is required".into());
|
||
}
|
||
let hook = match hook.char_indices().nth(HOOK_CHARS) {
|
||
Some((i, _)) => format!("{}…", hook[..i].trim_end()),
|
||
None => hook,
|
||
};
|
||
let mut l = lines(dir);
|
||
let line = format!("- [{slug}](topics/{slug}.md) – {hook}");
|
||
match l.iter().position(|x| x.starts_with(&prefix(slug))) {
|
||
Some(i) => l[i] = line,
|
||
None if l.len() >= MAX_LINES => {
|
||
return Err(format!(
|
||
"memory index full ({MAX_LINES} entries): merge related topics or memory_forget stale ones first"
|
||
));
|
||
}
|
||
None => l.push(line),
|
||
}
|
||
std::fs::create_dir_all(dir.join("topics")).map_err(|e| e.to_string())?;
|
||
std::fs::write(dir.join(format!("topics/{slug}.md")), body).map_err(|e| e.to_string())?;
|
||
save(dir, &l)
|
||
}
|
||
|
||
/// Delete topic `slug` and its index line.
|
||
pub fn forget(dir: &Path, slug: &str) -> Result<(), String> {
|
||
if !valid_slug(slug) {
|
||
return Err("invalid slug".into());
|
||
}
|
||
let mut l = lines(dir);
|
||
let n = l.len();
|
||
l.retain(|x| !x.starts_with(&prefix(slug)));
|
||
if l.len() == n {
|
||
return Err(format!("no memory '{slug}'"));
|
||
}
|
||
let _ = std::fs::remove_file(dir.join(format!("topics/{slug}.md")));
|
||
save(dir, &l)
|
||
}
|
||
|
||
/// System-prompt section. Always present (tells the model it can remember); indexes only if non-empty.
|
||
pub fn prompt_section(home: &Path, cwd: &Path) -> String {
|
||
let mut s = String::from(
|
||
"\n\n# Memory\nPersistent notes across sessions. `memory_write` only durable facts (user preferences, \
|
||
corrections, project conventions, environment quirks), never task progress. Entries below are \
|
||
one-line hooks; `read` the topic file when relevant. This index is fixed per session.\n",
|
||
);
|
||
for (name, project) in [("global", false), ("project", true)] {
|
||
let d = dir(project, home, cwd);
|
||
let l = lines(&d);
|
||
if !l.is_empty() {
|
||
s.push_str(&format!(
|
||
"{name} memory ({}):\n{}\n",
|
||
d.display(),
|
||
l.join("\n")
|
||
));
|
||
}
|
||
}
|
||
s
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn roundtrip_upsert_forget_and_cap() {
|
||
let t = tempfile::tempdir().unwrap();
|
||
let (home, cwd) = (t.path().join("h"), t.path().join("p"));
|
||
let d = dir(true, &home, &cwd);
|
||
assert_eq!(d, cwd.join(".hx/memory"));
|
||
write(&d, "a", "first\nhook", "BODY1").unwrap();
|
||
write(&d, "a", "second", "BODY2").unwrap();
|
||
assert_eq!(
|
||
std::fs::read_to_string(d.join("topics/a.md")).unwrap(),
|
||
"BODY2"
|
||
);
|
||
assert_eq!(lines(&d), ["- [a](topics/a.md) – second"]);
|
||
assert!(prompt_section(&home, &cwd).contains("project memory"));
|
||
assert!(!prompt_section(&home, &cwd).contains("global memory"));
|
||
assert!(write(&d, "../x", "h", "b").is_err());
|
||
assert!(write(&d, "b", " ", "b").is_err());
|
||
forget(&d, "a").unwrap();
|
||
assert!(forget(&d, "a").is_err());
|
||
assert!(!d.join("topics/a.md").exists() && lines(&d).is_empty());
|
||
for i in 0..MAX_LINES {
|
||
write(&d, &format!("t{i}"), "h", "b").unwrap();
|
||
}
|
||
assert!(write(&d, "over", "h", "b").unwrap_err().contains("full"));
|
||
write(&d, "t0", "updated", "b").unwrap(); // upsert still works when full
|
||
}
|
||
}
|