Memory: byte-budgeted index, memory_search (BM25), auto extraction on compaction/exit

This commit is contained in:
hermes committed 2026-11-30 12:46:16 +00:00
1 parent 59bf45f41d
commit 8705b128ea
8 files changed
+311 -39

No files matched your search

+39 -2
View File
@@ -313,6 +313,31 @@ impl Agent {
self.compact(KEEP_MESSAGES).await
}
pub async fn extract_memory(&mut self, transcript: &str) -> Vec<String> {
let home = crate::context::hx_home();
let req = crate::memory::extract_request(&self.model, transcript, &home, &self.cx.cwd);
let Ok(mut s) = self.provider.stream(req).await else {
return vec![];
};
let mut reply = String::new();
while let Some(Ok(ev)) = s.next().await {
if let StreamEvent::Done { message, usage, .. } = ev {
self.usage.add(&usage);
reply = message.text();
}
}
crate::memory::apply_extracted(&reply, &home, &self.cx.cwd)
}
pub async fn extract_memory_now(&mut self) -> Vec<String> {
let msgs = self.session.messages();
if msgs.len() < 4 {
return vec![];
}
self.extract_memory(&crate::compact::transcript(&msgs))
.await
}
pub async fn compact(&mut self, keep: usize) -> Result<bool, Error> {
let Some(plan) = compact::plan(&self.session.messages(), keep) else {
return Ok(false);
@@ -326,6 +351,11 @@ impl Agent {
}
}
let summary = summary.ok_or(Error::Truncated)?;
let saved = self.extract_memory(plan.transcript()).await;
if !saved.is_empty() {
self.emit(Event::Info(format!("memory saved: {}", saved.join(", "))))
.await;
}
self.session.rebase(plan.apply(&summary))?;
self.window.reset();
self.publish();
@@ -1263,6 +1293,7 @@ mod tests {
asst(vec![tu("2", "b")]),
text("fin"),
text("SUMMARY"),
text("[]"),
text("next"),
]),
Mutex::new(vec![]),
@@ -1358,7 +1389,13 @@ mod tests {
async fn compaction() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
let script = Arc::new(Script(
Mutex::new(vec![text("r1"), text("r2"), text("SUMMARY"), text("r3")]),
Mutex::new(vec![
text("r1"),
text("r2"),
text("SUMMARY"),
text("[]"),
text("r3"),
]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
@@ -1393,7 +1430,7 @@ mod tests {
async fn replacing_the_session_drops_stale_context_usage() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
let script = Arc::new(Script(
Mutex::new(vec![text("r1"), text("SUMMARY"), text("r2")]),
Mutex::new(vec![text("r1"), text("SUMMARY"), text("[]"), text("r2")]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
+5 -1
View File
@@ -22,6 +22,10 @@ pub fn plan(msgs: &[Message], keep: usize) -> Option<Plan> {
}
impl Plan {
pub fn transcript(&self) -> &str {
&self.transcript
}
pub fn request(&self, model: &str) -> Request {
Request {
model: model.into(),
@@ -53,7 +57,7 @@ fn is_prompt(m: &Message) -> bool {
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
}
fn transcript(msgs: &[Message]) -> String {
pub fn transcript(msgs: &[Message]) -> String {
let cut = |s: &str| -> String {
if s.len() > 800 {
format!("{}…", s.chars().take(800).collect::<String>())
+195 -14
View File
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};
pub const MAX_LINES: usize = 50;
pub const INDEX_BYTES: usize = 2000;
const HOOK_CHARS: usize = 100;
pub fn dir(project: bool, home: &Path, cwd: &Path) -> PathBuf {
@@ -53,11 +53,6 @@ pub fn write(dir: &Path, slug: &str, hook: &str, body: &str) -> Result<(), Strin
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())?;
@@ -79,26 +74,191 @@ pub fn forget(dir: &Path, slug: &str) -> Result<(), String> {
save(dir, &l)
}
fn mtime(dir: &Path, slug: &str) -> std::time::SystemTime {
std::fs::metadata(dir.join(format!("topics/{slug}.md")))
.and_then(|m| m.modified())
.unwrap_or(std::time::UNIX_EPOCH)
}
fn slug_of(line: &str) -> Option<&str> {
line.strip_prefix("- [")?.split_once("](").map(|x| x.0)
}
fn touch(dir: &Path, slug: &str) {
if let Ok(f) = std::fs::File::options()
.write(true)
.open(dir.join(format!("topics/{slug}.md")))
{
let _ = f.set_modified(std::time::SystemTime::now());
}
}
fn index(dir: &Path) -> (Vec<String>, usize) {
let mut l = lines(dir);
l.sort_by_key(|x| std::cmp::Reverse(slug_of(x).map(|s| mtime(dir, s))));
let (mut used, mut keep) = (0, 0);
for x in &l {
used += x.len() + 1;
if used > INDEX_BYTES && keep > 0 {
break;
}
keep += 1;
}
let hidden = l.len() - keep;
l.truncate(keep);
(l, hidden)
}
pub struct Hit {
pub slug: String,
pub hook: String,
pub snippet: String,
pub score: f64,
}
fn tokens(s: &str) -> Vec<String> {
s.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty())
.map(str::to_lowercase)
.collect()
}
pub fn search(dir: &Path, query: &str, k: usize) -> Vec<Hit> {
let q = tokens(query);
let docs: Vec<(String, String, String, Vec<String>)> = lines(dir)
.iter()
.filter_map(|l| {
let slug = slug_of(l)?.to_string();
let hook = l.split_once(") – ").map_or("", |x| x.1).to_string();
let body =
std::fs::read_to_string(dir.join(format!("topics/{slug}.md"))).unwrap_or_default();
let t = tokens(&format!("{slug} {hook} {hook} {body}"));
Some((slug, hook, body, t))
})
.collect();
if q.is_empty() || docs.is_empty() {
return vec![];
}
let n = docs.len() as f64;
let avg = docs.iter().map(|d| d.3.len()).sum::<usize>() as f64 / n;
let mut hits: Vec<Hit> = docs
.iter()
.filter_map(|(slug, hook, body, t)| {
let mut score = 0.0;
for w in &q {
let tf = t.iter().filter(|x| *x == w).count() as f64;
if tf == 0.0 {
continue;
}
let df = docs.iter().filter(|d| d.3.contains(w)).count() as f64;
let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
score += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * t.len() as f64 / avg));
}
(score > 0.0).then(|| Hit {
slug: slug.clone(),
hook: hook.clone(),
snippet: snippet(body, &q),
score,
})
})
.collect();
hits.sort_by(|a, b| b.score.total_cmp(&a.score));
hits.truncate(k);
for h in &hits {
touch(dir, &h.slug);
}
hits
}
fn snippet(body: &str, q: &[String]) -> String {
let line = body
.lines()
.find(|l| tokens(l).iter().any(|w| q.contains(w)))
.or_else(|| body.lines().next())
.unwrap_or_default();
match line.char_indices().nth(200) {
Some((i, _)) => format!("{}…", &line[..i]),
None => line.to_string(),
}
}
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",
"\n\n# Memory\nPersistent notes across sessions (project scope is the default; the other scope is only for facts about the user or machine). \
Call `memory_write` IMMEDIATELY, without asking, when: the user states a convention or decision, the user corrects you, \
you learn a non-obvious build/test/environment quirk, or a design choice is settled after discussion. \
Never save task progress. Keep one topic per subject and update the slug instead of adding duplicates. \
Before asking the user about conventions or assuming one, call `memory_search`; the index below is only the most recently used part. \
`read` a topic file when a hook is 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);
let (l, hidden) = index(&d);
if !l.is_empty() {
s.push_str(&format!(
"{name} memory ({}):\n{}\n",
d.display(),
l.join("\n")
));
if hidden > 0 {
s.push_str(&format!("(+{hidden} more, use `memory_search`)\n"));
}
}
}
s
}
const EXTRACT_PROMPT: &str = "You maintain long-term memory for a coding agent. From the conversation, extract at most 5 DURABLE facts worth remembering in future sessions: \
project decisions and their reasons, conventions, user corrections/preferences, non-obvious build/test/environment quirks. Skip task progress, anything derivable from the code, and anything already in the existing index (reuse its slug to update an entry). \
Output ONLY a JSON array (possibly empty) of {\"scope\":\"project\"|\"global\",\"slug\":\"a-z0-9-_\",\"hook\":\"one line <=100 chars\",\"body\":\"full text\"}. Scope is project unless the fact is about the user or machine.";
pub const EXTRACT_MAX: usize = 5;
pub fn extract_request(model: &str, transcript: &str, home: &Path, cwd: &Path) -> hx_ai::Request {
let mut idx = String::new();
for (name, project) in [("global", false), ("project", true)] {
for l in lines(&dir(project, home, cwd)) {
idx.push_str(&format!("[{name}] {l}\n"));
}
}
let tail: String = {
let n = transcript.chars().count();
transcript.chars().skip(n.saturating_sub(60_000)).collect()
};
hx_ai::Request {
model: model.into(),
system: EXTRACT_PROMPT.into(),
messages: vec![hx_ai::Message::user(format!(
"Existing index:\n{idx}\nConversation:\n{tail}"
))],
tools: vec![],
max_tokens: 4096,
effort: hx_ai::Effort::Off,
}
}
pub fn apply_extracted(reply: &str, home: &Path, cwd: &Path) -> Vec<String> {
let (Some(a), Some(b)) = (reply.find('['), reply.rfind(']')) else {
return vec![];
};
let Ok(v) = serde_json::from_str::<Vec<serde_json::Value>>(&reply[a..=b]) else {
return vec![];
};
let mut saved = vec![];
for e in v.iter().take(EXTRACT_MAX) {
let g = |k: &str| e[k].as_str().unwrap_or_default();
let project = g("scope") != "global";
if write(&dir(project, home, cwd), g("slug"), g("hook"), g("body")).is_ok() {
saved.push(format!(
"{}/{}",
if project { "project" } else { "global" },
g("slug")
));
}
}
saved
}
#[cfg(test)]
mod tests {
use super::*;
@@ -123,10 +283,31 @@ mod tests {
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();
for i in 0..200 {
write(
&d,
&format!("t{i}"),
"filler hook for padding the index out",
"b",
)
.unwrap();
}
assert!(write(&d, "over", "h", "b").unwrap_err().contains("full"));
write(&d, "t0", "updated", "b").unwrap();
write(
&d,
"db",
"database",
"Use sqlite WAL mode; migrations in db/migrate.sql",
)
.unwrap();
let p = prompt_section(&home, &cwd);
assert!(p.contains("more, use `memory_search`") && p.len() < INDEX_BYTES + 2000);
assert!(p.contains("[db]"), "newest topic stays in prompt");
let h = search(&d, "how do migrations work", 3);
assert_eq!(h[0].slug, "db");
assert!(h[0].snippet.contains("migrate.sql"));
assert!(search(&d, "zzzz", 3).is_empty());
let r = r#"sure: [{"scope":"project","slug":"ex","hook":"h","body":"b"},{"slug":"../bad","hook":"h","body":"b"}]"#;
assert_eq!(apply_extracted(r, &home, &cwd), ["project/ex"]);
assert!(apply_extracted("no json", &home, &cwd).is_empty());
}
}
+46 -4
View File
@@ -64,6 +64,7 @@ pub fn registry() -> Registry {
.add(ExitPlan)
.add(MemoryWrite)
.add(MemoryForget)
.add(MemorySearch)
.add(skill::Skill);
r
}
@@ -483,7 +484,7 @@ impl Tool for Bash {
fn memory_dir(a: &Value, cx: &ToolCtx) -> PathBuf {
hx_core::memory::dir(
a["scope"].as_str() == Some("project"),
a["scope"].as_str() != Some("global"),
&hx_core::context::hx_home(),
&cx.cwd,
)
@@ -495,13 +496,13 @@ 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.",
"Save or replace a persistent memory topic (durable facts only, not task progress). Default scope is project. `hook` is the one-line index entry; `body` is the full text, found via memory_search or read on demand. Appears in the prompt index from the next session, searchable immediately.",
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"]}),
"required":["slug","hook","body"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
@@ -518,6 +519,47 @@ impl Tool for MemoryWrite {
}
}
pub struct MemorySearch;
#[async_trait]
impl Tool for MemorySearch {
fn spec(&self) -> ToolSpec {
spec(
"memory_search",
"Search persistent memory (all topics, not just those in the prompt index). Use before asking the user about conventions/decisions or assuming them. Searches both scopes unless `scope` is given.",
json!({"type":"object","properties":{
"query":{"type":"string"},
"scope":{"type":"string","enum":["global","project"]}},
"required":["query"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let q = a["query"].as_str().unwrap_or_default();
let home = hx_core::context::hx_home();
let mut out = String::new();
for (name, project) in [("project", true), ("global", false)] {
if a["scope"].as_str().is_some_and(|s| s != name) {
continue;
}
let d = hx_core::memory::dir(project, &home, &cx.cwd);
for h in hx_core::memory::search(&d, q, 5) {
out.push_str(&format!(
"[{name}] {} – {}\n {}\n file: {}/topics/{}.md\n",
h.slug,
h.hook,
h.snippet,
d.display(),
h.slug
));
}
}
if out.is_empty() {
ToolResult::ok("no matching memory")
} else {
ToolResult::ok(out)
}
}
}
pub struct MemoryForget;
#[async_trait]
impl Tool for MemoryForget {
@@ -528,7 +570,7 @@ impl Tool for MemoryForget {
json!({"type":"object","properties":{
"scope":{"type":"string","enum":["global","project"]},
"slug":{"type":"string"}},
"required":["scope","slug"]}),
"required":["slug"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
+5
View File
@@ -712,6 +712,11 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
);
}
ratatui::restore();
eprintln!("[saving memory…]");
let saved = agent.lock().await.extract_memory_now().await;
if !saved.is_empty() {
eprintln!("[memory saved: {}]", saved.join(", "));
}
let a = agent.lock().await;
let cost = pricing(a.model())
.map(|p| format!(" ${:.4}", app.st.usage.cost(&p)))