Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76253d237a | ||
|
|
45d296d911 | ||
|
|
8705b128ea | ||
|
|
59bf45f41d |
No files matched your search
@@ -142,10 +142,13 @@ Builtin commands win when names collide.
|
|||||||
|
|
||||||
## Memory
|
## Memory
|
||||||
|
|
||||||
The agent keeps notes across sessions with `memory_write` / `memory_forget`. `MEMORY.md` (one hook line per
|
The agent keeps notes across sessions with `memory_write` / `memory_forget` / `memory_search`. Default scope is
|
||||||
topic, max 50) is in the system prompt; the full text lives in `topics/<slug>.md` and is read on demand.
|
project (`.hx/memory/`, add it to `.gitignore`); global is `~/.hx/memory/`. `MEMORY.md` holds one hook line per
|
||||||
Global: `~/.hx/memory/`, project: `.hx/memory/` (add it to `.gitignore`). The index is read at session
|
topic, the full text lives in `topics/<slug>.md`. No entry cap: the system prompt shows the most recently
|
||||||
start, so new entries show up next session. `hx prefix` shows its size.
|
used/written hooks up to 2 KB per scope plus "+N more"; `memory_search` (BM25 over all topics) finds the rest and
|
||||||
|
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
|
||||||
|
automatically. The index is read at session start. `hx prefix` shows its size.
|
||||||
|
|
||||||
## Lens
|
## Lens
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"version": "0.2.8",
|
"version": "0.2.9",
|
||||||
"sha256": {
|
"sha256": {
|
||||||
"aarch64-apple-darwin": "d4dde1d06dcaf1638cb5a20e4ff15633f5a049893ba4b210e498e4be9425a8c6",
|
"aarch64-apple-darwin": "5718f60493a45c6b6d81540df1c9a3048c6b21445e133c13feec7cf8dbe77ede",
|
||||||
"x86_64-unknown-linux-musl": "a4c68e37d4f4f2f66847ade82ea940cf5c81f6bfbbd827a5ef777723f775fe02"
|
"x86_64-unknown-linux-musl": "d5708ccf61308145fb0b4b528294e7f72b572b88228dc3fa2c060d0d0b08a8f8"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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));
|
||||||
|
|||||||
@@ -313,6 +313,35 @@ impl Agent {
|
|||||||
self.compact(KEEP_MESSAGES).await
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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> {
|
||||||
|
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> {
|
pub async fn compact(&mut self, keep: usize) -> Result<bool, Error> {
|
||||||
let Some(plan) = compact::plan(&self.session.messages(), keep) else {
|
let Some(plan) = compact::plan(&self.session.messages(), keep) else {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
@@ -326,6 +355,11 @@ impl Agent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let summary = summary.ok_or(Error::Truncated)?;
|
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.session.rebase(plan.apply(&summary))?;
|
||||||
self.window.reset();
|
self.window.reset();
|
||||||
self.publish();
|
self.publish();
|
||||||
@@ -1263,6 +1297,7 @@ mod tests {
|
|||||||
asst(vec![tu("2", "b")]),
|
asst(vec![tu("2", "b")]),
|
||||||
text("fin"),
|
text("fin"),
|
||||||
text("SUMMARY"),
|
text("SUMMARY"),
|
||||||
|
text("[]"),
|
||||||
text("next"),
|
text("next"),
|
||||||
]),
|
]),
|
||||||
Mutex::new(vec![]),
|
Mutex::new(vec![]),
|
||||||
@@ -1358,7 +1393,13 @@ mod tests {
|
|||||||
async fn compaction() {
|
async fn compaction() {
|
||||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||||
let script = Arc::new(Script(
|
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![]),
|
Mutex::new(vec![]),
|
||||||
));
|
));
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
@@ -1393,7 +1434,7 @@ mod tests {
|
|||||||
async fn replacing_the_session_drops_stale_context_usage() {
|
async fn replacing_the_session_drops_stale_context_usage() {
|
||||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||||
let script = Arc::new(Script(
|
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![]),
|
Mutex::new(vec![]),
|
||||||
));
|
));
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -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"]);
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ pub fn plan(msgs: &[Message], keep: usize) -> Option<Plan> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Plan {
|
impl Plan {
|
||||||
|
pub fn transcript(&self) -> &str {
|
||||||
|
&self.transcript
|
||||||
|
}
|
||||||
|
|
||||||
pub fn request(&self, model: &str) -> Request {
|
pub fn request(&self, model: &str) -> Request {
|
||||||
Request {
|
Request {
|
||||||
model: model.into(),
|
model: model.into(),
|
||||||
@@ -53,7 +57,7 @@ fn is_prompt(m: &Message) -> bool {
|
|||||||
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
|
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn transcript(msgs: &[Message]) -> String {
|
pub fn transcript(msgs: &[Message]) -> String {
|
||||||
let cut = |s: &str| -> String {
|
let cut = |s: &str| -> String {
|
||||||
if s.len() > 800 {
|
if s.len() > 800 {
|
||||||
format!("{}…", s.chars().take(800).collect::<String>())
|
format!("{}…", s.chars().take(800).collect::<String>())
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
+217
-14
@@ -1,6 +1,6 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
pub const MAX_LINES: usize = 50;
|
pub const INDEX_BYTES: usize = 2000;
|
||||||
const HOOK_CHARS: usize = 100;
|
const HOOK_CHARS: usize = 100;
|
||||||
|
|
||||||
pub fn dir(project: bool, home: &Path, cwd: &Path) -> PathBuf {
|
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}");
|
let line = format!("- [{slug}](topics/{slug}.md) – {hook}");
|
||||||
match l.iter().position(|x| x.starts_with(&prefix(slug))) {
|
match l.iter().position(|x| x.starts_with(&prefix(slug))) {
|
||||||
Some(i) => l[i] = line,
|
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),
|
None => l.push(line),
|
||||||
}
|
}
|
||||||
std::fs::create_dir_all(dir.join("topics")).map_err(|e| e.to_string())?;
|
std::fs::create_dir_all(dir.join("topics")).map_err(|e| e.to_string())?;
|
||||||
@@ -79,26 +74,207 @@ pub fn forget(dir: &Path, slug: &str) -> Result<(), String> {
|
|||||||
save(dir, &l)
|
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 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 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 {
|
pub fn prompt_section(home: &Path, cwd: &Path) -> String {
|
||||||
let mut s = String::from(
|
let mut s = String::from(
|
||||||
"\n\n# Memory\nPersistent notes across sessions. `memory_write` only durable facts (user preferences, \
|
"\n\n# Memory\nPersistent notes across sessions (project scope is the default; the other scope is only for facts about the user or machine). \
|
||||||
corrections, project conventions, environment quirks), never task progress. Entries below are \
|
Call `memory_write` IMMEDIATELY, without asking, when: the user states a convention or decision, the user corrects you, \
|
||||||
one-line hooks; `read` the topic file when relevant. This index is fixed per session.\n",
|
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)] {
|
for (name, project) in [("global", false), ("project", true)] {
|
||||||
let d = dir(project, home, cwd);
|
let d = dir(project, home, cwd);
|
||||||
let l = lines(&d);
|
let (l, hidden) = index(&d);
|
||||||
if !l.is_empty() {
|
if !l.is_empty() {
|
||||||
s.push_str(&format!(
|
s.push_str(&format!(
|
||||||
"{name} memory ({}):\n{}\n",
|
"{name} memory ({}):\n{}\n",
|
||||||
d.display(),
|
d.display(),
|
||||||
l.join("\n")
|
l.join("\n")
|
||||||
));
|
));
|
||||||
|
if hidden > 0 {
|
||||||
|
s.push_str(&format!("(+{hidden} more, use `memory_search`)\n"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
s
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -123,10 +299,37 @@ mod tests {
|
|||||||
forget(&d, "a").unwrap();
|
forget(&d, "a").unwrap();
|
||||||
assert!(forget(&d, "a").is_err());
|
assert!(forget(&d, "a").is_err());
|
||||||
assert!(!d.join("topics/a.md").exists() && lines(&d).is_empty());
|
assert!(!d.join("topics/a.md").exists() && lines(&d).is_empty());
|
||||||
for i in 0..MAX_LINES {
|
for i in 0..200 {
|
||||||
write(&d, &format!("t{i}"), "h", "b").unwrap();
|
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(
|
||||||
write(&d, "t0", "updated", "b").unwrap();
|
&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_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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ pub fn registry() -> Registry {
|
|||||||
.add(ExitPlan)
|
.add(ExitPlan)
|
||||||
.add(MemoryWrite)
|
.add(MemoryWrite)
|
||||||
.add(MemoryForget)
|
.add(MemoryForget)
|
||||||
|
.add(MemorySearch)
|
||||||
.add(skill::Skill);
|
.add(skill::Skill);
|
||||||
r
|
r
|
||||||
}
|
}
|
||||||
@@ -483,7 +484,7 @@ impl Tool for Bash {
|
|||||||
|
|
||||||
fn memory_dir(a: &Value, cx: &ToolCtx) -> PathBuf {
|
fn memory_dir(a: &Value, cx: &ToolCtx) -> PathBuf {
|
||||||
hx_core::memory::dir(
|
hx_core::memory::dir(
|
||||||
a["scope"].as_str() == Some("project"),
|
a["scope"].as_str() != Some("global"),
|
||||||
&hx_core::context::hx_home(),
|
&hx_core::context::hx_home(),
|
||||||
&cx.cwd,
|
&cx.cwd,
|
||||||
)
|
)
|
||||||
@@ -495,13 +496,13 @@ impl Tool for MemoryWrite {
|
|||||||
fn spec(&self) -> ToolSpec {
|
fn spec(&self) -> ToolSpec {
|
||||||
spec(
|
spec(
|
||||||
"memory_write",
|
"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":{
|
json!({"type":"object","properties":{
|
||||||
"scope":{"type":"string","enum":["global","project"],"description":"global: about the user/environment; project: this repo"},
|
"scope":{"type":"string","enum":["global","project"],"description":"global: about the user/environment; project: this repo"},
|
||||||
"slug":{"type":"string","description":"a-z 0-9 - _"},
|
"slug":{"type":"string","description":"a-z 0-9 - _"},
|
||||||
"hook":{"type":"string","description":"one line, max 100 chars"},
|
"hook":{"type":"string","description":"one line, max 100 chars"},
|
||||||
"body":{"type":"string"}},
|
"body":{"type":"string"}},
|
||||||
"required":["scope","slug","hook","body"]}),
|
"required":["slug","hook","body"]}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
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;
|
pub struct MemoryForget;
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Tool for MemoryForget {
|
impl Tool for MemoryForget {
|
||||||
@@ -528,7 +570,7 @@ impl Tool for MemoryForget {
|
|||||||
json!({"type":"object","properties":{
|
json!({"type":"object","properties":{
|
||||||
"scope":{"type":"string","enum":["global","project"]},
|
"scope":{"type":"string","enum":["global","project"]},
|
||||||
"slug":{"type":"string"}},
|
"slug":{"type":"string"}},
|
||||||
"required":["scope","slug"]}),
|
"required":["slug"]}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
|
|||||||
@@ -712,6 +712,11 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
ratatui::restore();
|
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 a = agent.lock().await;
|
||||||
let cost = pricing(a.model())
|
let cost = pricing(a.model())
|
||||||
.map(|p| format!(" ${:.4}", app.st.usage.cost(&p)))
|
.map(|p| format!(" ${:.4}", app.st.usage.cost(&p)))
|
||||||
@@ -1475,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);
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
# Memory index is capped and write fails when full
|
|
||||||
|
|
||||||
Status: accepted
|
|
||||||
|
|
||||||
## Context
|
|
||||||
The `MEMORY.md` index goes into every system prompt.
|
|
||||||
|
|
||||||
## Decision
|
|
||||||
A per-scope cap on index size makes `write` fail when full, so the agent must consolidate or forget entries instead of growing the prompt.
|
|
||||||
|
|
||||||
## Consequences
|
|
||||||
Upserts of existing lines still work when full.
|
|
||||||
|
|
||||||
Code: crates/hx-core/src/memory.rs (index cap, `write`)
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Memory: byte-budgeted index, BM25 search, automatic extraction
|
||||||
|
|
||||||
|
Status: accepted (supersedes 0013)
|
||||||
|
|
||||||
|
## Context
|
||||||
|
The 50-entry cap made `write` fail instead of letting memory grow, and the agent rarely wrote memory at all, so project decisions were lost between sessions.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
No entry cap. The prompt index shows the most recently used hooks up to 2 KB per scope; `memory_search` (BM25 over slug, hook and body, no dependency) reaches the rest and bumps recency (topic file mtime). The prompt lists concrete write triggers and defaults to project scope. Compaction and session exit run one extraction call (max 5 entries, written without asking).
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
Prompt cost stays flat as memory grows. Search scans all topic files per query. Embeddings can replace the ranking later without changing the tools.
|
||||||
|
|
||||||
|
Code: crates/hx-core/src/memory.rs
|
||||||
Reference in new issue
Block a user