Memory: byte-budgeted index, memory_search (BM25), auto extraction on compaction/exit
This commit is contained in:
1 parent
59bf45f41d
commit
8705b128ea
8 files changed
+311
-39
No files matched your search
+195
-14
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user