Agent memory: MEMORY.md index in prompt, lazy topic files, memory_write/memory_forget

This commit is contained in:
hermes committed 2026-10-06 12:52:02 +00:00
1 parent 19dc1563f4
commit 316ac55656
7 files changed
+228 -2

No files matched your search

+3
View File
@@ -27,3 +27,6 @@ devenv.local.yaml
# pre-commit
.pre-commit-config.yaml
# hx agent memory
.hx/memory/
+7
View File
@@ -91,6 +91,13 @@ the system prompt every turn) or `manual` (only via `/<name>`, never mentioned t
Each skill is also a command: `/<name> [args]` sends the skill file plus `args` as the prompt. Builtin
commands win when names collide.
## Memory
The agent keeps notes across sessions with `memory_write` / `memory_forget`. `MEMORY.md` (one hook line per
topic, max 50) is in the system prompt; the full text lives in `topics/<slug>.md` and is read on demand.
Global: `~/.hx/memory/`, project: `.hx/memory/` (add it to `.gitignore`). The index is read at session
start, so new entries show up next session. `hx prefix` shows its size.
## Lens
After every tool round, hx asks the language server about files the agent wrote or edited and appends
+3 -1
View File
@@ -389,14 +389,16 @@ async fn main() -> Result<()> {
})
.collect();
skill_rows.sort_by_key(|r| std::cmp::Reverse(r.1));
let mem = hx_core::memory::prompt_section(&home, &cwd).len();
let other = full.len().saturating_sub(
base.len() + files + always + skill_rows.iter().map(|r| r.1).sum::<usize>(),
base.len() + files + always + mem + skill_rows.iter().map(|r| r.1).sum::<usize>(),
);
let mut rows: Vec<(String, usize)> = vec![
("system: base prompt".into(), base.len()),
("system: AGENTS.md/CLAUDE.md files".into(), files),
("system: always-skill bodies".into(), always),
("system: cwd line + headings".into(), other),
("system: memory index".into(), mem),
("system: MCP index".into(), idx.len()),
];
rows.extend(skill_rows);
+1
View File
@@ -182,6 +182,7 @@ pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String {
for (p, c) in context_files(home, cwd) {
s.push_str(&format!("\n\n# {}\n{}", p.display(), c.trim()));
}
s.push_str(&crate::memory::prompt_section(home, cwd));
s
}
+1
View File
@@ -7,6 +7,7 @@ pub mod context;
pub mod ext;
pub mod hook;
mod mask;
pub mod memory;
pub mod permit;
pub mod session;
pub mod stats;
+140
View File
@@ -0,0 +1,140 @@
//! 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
}
}
+73 -1
View File
@@ -57,7 +57,13 @@ fn tail(s: &str, max: usize) -> &str {
pub fn registry() -> Registry {
let mut r = Registry::default();
r.add(Read).add(Write).add(Edit).add(Bash).add(AskUser);
r.add(Read)
.add(Write)
.add(Edit)
.add(Bash)
.add(AskUser)
.add(MemoryWrite)
.add(MemoryForget);
r
}
@@ -377,6 +383,60 @@ impl Tool for Bash {
}
}
fn memory_dir(a: &Value, cx: &ToolCtx) -> PathBuf {
hx_core::memory::dir(
a["scope"].as_str() == Some("project"),
&hx_core::context::hx_home(),
&cx.cwd,
)
}
pub struct MemoryWrite;
#[async_trait]
impl Tool for MemoryWrite {
fn spec(&self) -> ToolSpec {
spec(
"memory_write",
"Save or replace a persistent memory topic (durable facts only, not task progress). `hook` is the one-line index entry shown in every future session; `body` is the full text, read on demand. Appears in the prompt from the next session.",
json!({"type":"object","properties":{
"scope":{"type":"string","enum":["global","project"],"description":"global: about the user/environment; project: this repo"},
"slug":{"type":"string","description":"a-z 0-9 - _"},
"hook":{"type":"string","description":"one line, max 100 chars"},
"body":{"type":"string"}},
"required":["scope","slug","hook","body"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let g = |k: &str| a[k].as_str().unwrap_or_default();
match hx_core::memory::write(&memory_dir(&a, cx), g("slug"), g("hook"), g("body")) {
Ok(()) => ToolResult::ok(format!("saved memory '{}'", g("slug"))),
Err(e) => ToolResult::err(e),
}
}
}
pub struct MemoryForget;
#[async_trait]
impl Tool for MemoryForget {
fn spec(&self) -> ToolSpec {
spec(
"memory_forget",
"Delete a memory topic and its index line.",
json!({"type":"object","properties":{
"scope":{"type":"string","enum":["global","project"]},
"slug":{"type":"string"}},
"required":["scope","slug"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let slug = a["slug"].as_str().unwrap_or_default();
match hx_core::memory::forget(&memory_dir(&a, cx), slug) {
Ok(()) => ToolResult::ok(format!("forgot memory '{slug}'")),
Err(e) => ToolResult::err(e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -389,6 +449,18 @@ mod tests {
}
}
#[tokio::test]
async fn memory_tools_write_and_forget() {
let t = tempfile::tempdir().unwrap();
let c = cx(t.path());
let a = json!({"scope":"project","slug":"x","hook":"h","body":"b"});
assert!(!MemoryWrite.call(a, &c).await.is_error);
assert!(t.path().join(".hx/memory/topics/x.md").exists());
let f = json!({"scope":"project","slug":"x"});
assert!(!MemoryForget.call(f.clone(), &c).await.is_error);
assert!(MemoryForget.call(f, &c).await.is_error);
}
#[tokio::test]
async fn ask_user_paths() {
let d = tempfile::tempdir().unwrap();