From 45d296d9116bca9937dd523905b67b0bed7a8f87 Mon Sep 17 00:00:00 2001 From: hermes Date: Mon, 30 Nov 2026 12:56:25 +0000 Subject: [PATCH] Memory: /memory list+forget, /remember, memory counts in hx stats --- README.md | 2 +- crates/hx-cli/src/main.rs | 4 ++++ crates/hx-core/src/agent.rs | 6 +++++- crates/hx-core/src/command.rs | 12 +++++++++++- crates/hx-core/src/consult.rs | 20 ++++++++++++++++---- crates/hx-core/src/memory.rs | 22 ++++++++++++++++++++++ crates/hx-core/src/stats.rs | 35 +++++++++++++++++++++++++++++++++++ crates/hx-tui/src/lib.rs | 33 +++++++++++++++++++++++++++++++++ 8 files changed, 127 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 75b5892..7e16b18 100644 --- a/README.md +++ b/README.md @@ -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 topic, the full text lives in `topics/.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 -refreshes recency. The prompt tells the agent to save decisions, conventions and corrections immediately. On +refreshes recency. `/memory` lists entries (`/memory forget ` deletes), `/remember ` 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 automatically. The index is read at session start. `hx prefix` shows its size. diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index b14ba0e..e3d0a54 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -689,6 +689,10 @@ async fn main() -> Result<()> { hx_core::stats::model_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::claude_report(&session)); print!("{}", hx_core::stats::sub_report(&session)); diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 966985f..2243527 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -326,7 +326,11 @@ impl Agent { 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 { diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index c9e1d1f..a3b1af7 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -106,6 +106,16 @@ pub fn builtins(models: &[&str]) -> Vec { None, ), b("btw", "side question; no tools, not saved", Free), + b( + "memory", + "list memory; `/memory forget ` 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( "reload", @@ -422,7 +432,7 @@ mod tests { let c = |l: &str| complete(l, l.len(), &specs, &files); 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"]); let r = c("/rev"); assert_eq!(labels(&r), ["/review"]); diff --git a/crates/hx-core/src/consult.rs b/crates/hx-core/src/consult.rs index 943bc35..1da9128 100644 --- a/crates/hx-core/src/consult.rs +++ b/crates/hx-core/src/consult.rs @@ -316,14 +316,21 @@ mod tests { let cx = cx(); for _ in 0..2 { 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; assert!(r.is_error && r.content.contains("limit reached (2/2)")); assert_eq!(p.0.load(Ordering::Relaxed), 2); assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 20); 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(); assert_eq!(st.snapshot().count, 0); } @@ -345,13 +352,18 @@ mod tests { is_error: e, }; 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_eq!(h.on(&Event::AgentEnd).await, HookAction::Continue); h.on(&res(true)).await; h.on(&res(true)).await; 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(); assert_eq!(h.on(&call("exit_plan")).await, HookAction::Continue); diff --git a/crates/hx-core/src/memory.rs b/crates/hx-core/src/memory.rs index 8b7499c..f1ddf9e 100644 --- a/crates/hx-core/src/memory.rs +++ b/crates/hx-core/src/memory.rs @@ -109,6 +109,22 @@ fn index(dir: &Path) -> (Vec, usize) { (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 { + let words: Vec = tokens(text).into_iter().take(4).collect(); + let slug = words.join("-").chars().take(48).collect::(); + if slug.is_empty() { + return Err("nothing to remember".into()); + } + write(dir, &slug, text, text).map(|_| slug) +} + pub struct Hit { pub slug: String, pub hook: String, @@ -308,6 +324,12 @@ mod tests { 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_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()); } } diff --git a/crates/hx-core/src/stats.rs b/crates/hx-core/src/stats.rs index 7547a93..b42c99b 100644 --- a/crates/hx-core/src/stats.rs +++ b/crates/hx-core/src/stats.rs @@ -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::().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( session: &std::path::Path, name: &str, diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 29e8a06..1326a31 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -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" => { let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd); let mut l = skills_list(&app.specs, &dirs);