Memory: /memory list+forget, /remember, memory counts in hx stats

This commit is contained in:
hermes committed 2026-11-30 12:56:25 +00:00
1 parent 8705b128ea
commit 45d296d911
8 files changed
+127 -7

No files matched your search

+1 -1
View File
@@ -146,7 +146,7 @@ The agent keeps notes across sessions with `memory_write` / `memory_forget` / `m
project (`.hx/memory/`, add it to `.gitignore`); global is `~/.hx/memory/`. `MEMORY.md` holds one hook line per project (`.hx/memory/`, add it to `.gitignore`); global is `~/.hx/memory/`. `MEMORY.md` holds one hook line per
topic, the full text lives in `topics/<slug>.md`. No entry cap: the system prompt shows the most recently topic, the full text lives in `topics/<slug>.md`. No entry cap: the system prompt shows the most recently
used/written hooks up to 2 KB per scope plus "+N more"; `memory_search` (BM25 over all topics) finds the rest and used/written hooks up to 2 KB per scope plus "+N more"; `memory_search` (BM25 over all topics) finds the rest and
refreshes recency. The prompt tells the agent to save decisions, conventions and corrections immediately. On refreshes recency. `/memory` lists entries (`/memory forget <scope/slug>` deletes), `/remember <text>` saves a note (`global:` prefix for global scope), `hx stats` shows memory writes, auto-extractions and searches. The prompt tells the agent to save decisions, conventions and corrections immediately. On
compaction and on exit, one extra model call extracts up to 5 durable facts from the transcript and saves them compaction and on exit, one extra model call extracts up to 5 durable facts from the transcript and saves them
automatically. The index is read at session start. `hx prefix` shows its size. automatically. The index is read at session start. `hx prefix` shows its size.
+4
View File
@@ -689,6 +689,10 @@ async fn main() -> Result<()> {
hx_core::stats::model_report(&Session::open(&session)?) hx_core::stats::model_report(&Session::open(&session)?)
); );
print!("{}", hx_core::stats::task_report(&Session::open(&session)?)); print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
print!(
"{}",
hx_core::stats::memory_report(&Session::open(&session)?)
);
print!("{}", hx_core::stats::route_report(&session)); print!("{}", hx_core::stats::route_report(&session));
print!("{}", hx_core::stats::claude_report(&session)); print!("{}", hx_core::stats::claude_report(&session));
print!("{}", hx_core::stats::sub_report(&session)); print!("{}", hx_core::stats::sub_report(&session));
+5 -1
View File
@@ -326,7 +326,11 @@ impl Agent {
reply = message.text(); reply = message.text();
} }
} }
crate::memory::apply_extracted(&reply, &home, &self.cx.cwd) let saved = crate::memory::apply_extracted(&reply, &home, &self.cx.cwd);
if !saved.is_empty() {
crate::stats::log_memory_saved(self.session.path(), saved.len());
}
saved
} }
pub async fn extract_memory_now(&mut self) -> Vec<String> { pub async fn extract_memory_now(&mut self) -> Vec<String> {
+11 -1
View File
@@ -106,6 +106,16 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
None, None,
), ),
b("btw", "side question; no tools, not saved", Free), b("btw", "side question; no tools, not saved", Free),
b(
"memory",
"list memory; `/memory forget <scope/slug>` deletes",
Free,
),
b(
"remember",
"save a note to project memory (`global:` prefix for global)",
Free,
),
b("skills", "list skills and where they load from", None), b("skills", "list skills and where they load from", None),
b( b(
"reload", "reload",
@@ -422,7 +432,7 @@ mod tests {
let c = |l: &str| complete(l, l.len(), &specs, &files); let c = |l: &str| complete(l, l.len(), &specs, &files);
assert_eq!(c("/").items.len(), MAX_ITEMS); assert_eq!(c("/").items.len(), MAX_ITEMS);
assert_eq!(labels(&c("/mo")), ["/model"]); assert_eq!(labels(&c("/mod")), ["/model"]);
assert_eq!(labels(&c("/co")), ["/copy", "/compact"]); assert_eq!(labels(&c("/co")), ["/copy", "/compact"]);
let r = c("/rev"); let r = c("/rev");
assert_eq!(labels(&r), ["/review"]); assert_eq!(labels(&r), ["/review"]);
+16 -4
View File
@@ -316,14 +316,21 @@ mod tests {
let cx = cx(); let cx = cx();
for _ in 0..2 { for _ in 0..2 {
let r = t.call(json!({"question": "q"}), &cx).await; let r = t.call(json!({"question": "q"}), &cx).await;
assert!(!r.is_error && r.content.contains("use a trait"), "{}", r.content); assert!(
!r.is_error && r.content.contains("use a trait"),
"{}",
r.content
);
} }
let r = t.call(json!({"question": "q"}), &cx).await; let r = t.call(json!({"question": "q"}), &cx).await;
assert!(r.is_error && r.content.contains("limit reached (2/2)")); assert!(r.is_error && r.content.contains("limit reached (2/2)"));
assert_eq!(p.0.load(Ordering::Relaxed), 2); assert_eq!(p.0.load(Ordering::Relaxed), 2);
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 20); assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 20);
let snap = st.snapshot(); let snap = st.snapshot();
assert_eq!((snap.count, snap.advising, snap.last.is_some()), (2, false, true)); assert_eq!(
(snap.count, snap.advising, snap.last.is_some()),
(2, false, true)
);
st.reset(); st.reset();
assert_eq!(st.snapshot().count, 0); assert_eq!(st.snapshot().count, 0);
} }
@@ -345,13 +352,18 @@ mod tests {
is_error: e, is_error: e,
}; };
assert_eq!(h.on(&call("edit")).await, HookAction::Continue); assert_eq!(h.on(&call("edit")).await, HookAction::Continue);
assert!(matches!(h.on(&Event::AgentEnd).await, HookAction::Inject(m) if m.contains("2 calls"))); assert!(
matches!(h.on(&Event::AgentEnd).await, HookAction::Inject(m) if m.contains("2 calls"))
);
assert!(st.snapshot().triggers.iter().any(|t| t.0 == DONE && t.1)); assert!(st.snapshot().triggers.iter().any(|t| t.0 == DONE && t.1));
assert_eq!(h.on(&Event::AgentEnd).await, HookAction::Continue); assert_eq!(h.on(&Event::AgentEnd).await, HookAction::Continue);
h.on(&res(true)).await; h.on(&res(true)).await;
h.on(&res(true)).await; h.on(&res(true)).await;
assert!(matches!(h.on(&res(true)).await, HookAction::Inject(_))); assert!(matches!(h.on(&res(true)).await, HookAction::Inject(_)));
assert!(matches!(h.on(&call("exit_plan")).await, HookAction::Inject(_))); assert!(matches!(
h.on(&call("exit_plan")).await,
HookAction::Inject(_)
));
st.begin().unwrap(); st.begin().unwrap();
st.begin().unwrap(); st.begin().unwrap();
assert_eq!(h.on(&call("exit_plan")).await, HookAction::Continue); assert_eq!(h.on(&call("exit_plan")).await, HookAction::Continue);
+22
View File
@@ -109,6 +109,22 @@ fn index(dir: &Path) -> (Vec<String>, usize) {
(l, hidden) (l, hidden)
} }
pub fn list(dir: &Path) -> Vec<(String, String)> {
lines(dir)
.iter()
.filter_map(|l| Some((slug_of(l)?.to_string(), l.split_once(") – ")?.1.to_string())))
.collect()
}
pub fn remember(dir: &Path, text: &str) -> Result<String, String> {
let words: Vec<String> = tokens(text).into_iter().take(4).collect();
let slug = words.join("-").chars().take(48).collect::<String>();
if slug.is_empty() {
return Err("nothing to remember".into());
}
write(dir, &slug, text, text).map(|_| slug)
}
pub struct Hit { pub struct Hit {
pub slug: String, pub slug: String,
pub hook: String, pub hook: String,
@@ -308,6 +324,12 @@ mod tests {
assert!(search(&d, "zzzz", 3).is_empty()); 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"}]"#; 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_eq!(apply_extracted(r, &home, &cwd), ["project/ex"]);
assert_eq!(
remember(&d, "Use tabs, not spaces!").unwrap(),
"use-tabs-not-spaces"
);
assert!(remember(&d, "!!!").is_err());
assert!(list(&d).iter().any(|(s, h)| s == "ex" && h == "h"));
assert!(apply_extracted("no json", &home, &cwd).is_empty()); assert!(apply_extracted("no json", &home, &cwd).is_empty());
} }
} }
+35
View File
@@ -41,6 +41,41 @@ pub fn task_report(s: &Session) -> String {
) )
} }
pub fn log_memory_saved(session: &std::path::Path, n: usize) {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(session.with_extension("mem"))
{
let _ = writeln!(f, "{n}");
}
}
pub fn memory_report(s: &Session) -> String {
let (mut w, mut r) = (0, 0);
for m in s.messages() {
for b in &m.content {
if let ContentBlock::ToolUse { name, .. } = b {
match name.as_str() {
"memory_write" => w += 1,
"memory_search" => r += 1,
_ => {}
}
}
}
}
let auto: usize = std::fs::read_to_string(s.path().with_extension("mem"))
.unwrap_or_default()
.lines()
.filter_map(|l| l.parse::<usize>().ok())
.sum();
if w + r + auto == 0 {
return String::new();
}
format!("memory: {w} agent writes, {auto} auto-extracted, {r} searches\n")
}
pub fn log_claude_tool( pub fn log_claude_tool(
session: &std::path::Path, session: &std::path::Path,
name: &str, name: &str,
+33
View File
@@ -1480,6 +1480,39 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
))); )));
} }
}, },
"memory" => {
let home = hx_core::context::hx_home();
let dir = |p: &str| hx_core::memory::dir(p == "project", &home, cwd);
if let Some(t) = arg.strip_prefix("forget ") {
let (sc, slug) = t.trim().split_once('/').unwrap_or(("project", t.trim()));
app.t.push(match hx_core::memory::forget(&dir(sc), slug) {
Ok(()) => Item::Info(format!("forgot {sc}/{slug}")),
Err(e) => Item::Error(e),
});
} else {
let mut l = String::new();
for sc in ["project", "global"] {
for (slug, hook) in hx_core::memory::list(&dir(sc)) {
l.push_str(&format!("{sc}/{slug} – {hook}\n"));
}
}
if l.is_empty() {
l = "no memory yet".into();
}
show(app, "memory", l);
}
}
"remember" => {
let (sc, text) = match arg.strip_prefix("global:") {
Some(t) => ("global", t.trim()),
None => ("project", arg),
};
let d = hx_core::memory::dir(sc == "project", &hx_core::context::hx_home(), cwd);
app.t.push(match hx_core::memory::remember(&d, text) {
Ok(slug) => Item::Info(format!("memory saved: {sc}/{slug}")),
Err(e) => Item::Error(e),
});
}
"skills" => { "skills" => {
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd); let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
let mut l = skills_list(&app.specs, &dirs); let mut l = skills_list(&app.specs, &dirs);