314 lines
11 KiB
Rust
314 lines
11 KiB
Rust
use std::path::{Path, PathBuf};
|
||
|
||
pub const INDEX_BYTES: usize = 2000;
|
||
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())
|
||
}
|
||
|
||
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 => 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)
|
||
}
|
||
|
||
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)
|
||
}
|
||
|
||
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 (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, 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::*;
|
||
|
||
#[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..200 {
|
||
write(
|
||
&d,
|
||
&format!("t{i}"),
|
||
"filler hook for padding the index out",
|
||
"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());
|
||
}
|
||
}
|