1#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
15
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18
19use byob_plugins::native::{NativeBackend, NativeFactory, Outbox};
20use serde_json::{Value, json};
21
22pub const ID: &str = "memory";
24pub const TOOLS: [&str; 2] = ["remember", "forget"];
26pub const VIEW: &str = "memory";
28pub const PROMPT_CAP: usize = 4096;
30pub const MAX_FILE: usize = 64 * 1024;
32pub const MAX_NOTE_CHARS: usize = 500;
34pub const WORKSPACE_FILE: &str = ".byob/memory.md";
36
37const HEADING: &str = "# Memory";
38const INTRO: &str = "Notes byob keeps across chats. Edit freely: each \"- \" line is one note.";
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Scope {
43 Global,
45 Workspace,
47}
48
49impl Scope {
50 fn parse(s: Option<&str>) -> Result<Option<Self>, String> {
51 match s.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
52 None | Some("") => Ok(None),
53 Some("global" | "user" | "me" | "everywhere" | "all") => Ok(Some(Self::Global)),
54 Some("workspace" | "project" | "local" | "here") => Ok(Some(Self::Workspace)),
55 Some(other) => Err(format!("scope must be \"global\" or \"workspace\", not {other:?}")),
56 }
57 }
58
59 fn label(self) -> &'static str {
60 match self {
61 Self::Global => "global",
62 Self::Workspace => "workspace",
63 }
64 }
65}
66
67#[derive(Debug, Clone, Default)]
69pub struct Files {
70 pub config: Option<PathBuf>,
72 pub workspace: Option<PathBuf>,
74}
75
76impl Files {
77 pub fn path(&self, scope: Scope) -> Option<PathBuf> {
78 match scope {
79 Scope::Global => self.config.as_ref().map(|c| c.join("memory.md")),
80 Scope::Workspace => self.workspace.as_ref().map(|w| w.join(WORKSPACE_FILE)),
81 }
82 }
83
84 fn need(&self, scope: Scope) -> Result<PathBuf, String> {
85 self.path(scope).ok_or_else(|| match scope {
86 Scope::Global => "there is no config folder for global memory; use scope \"workspace\"".to_owned(),
87 Scope::Workspace => "this chat has no workspace; use scope \"global\"".to_owned(),
88 })
89 }
90}
91
92fn notes(text: &str) -> Vec<(usize, String)> {
94 text.lines()
95 .enumerate()
96 .filter_map(|(i, l)| {
97 let t = l.trim_start();
98 let rest = t.strip_prefix("- ").or_else(|| t.strip_prefix("* "))?;
99 let rest = rest.trim();
100 (!rest.is_empty()).then(|| (i, rest.to_owned()))
101 })
102 .collect()
103}
104
105fn read(path: &Path) -> String {
106 std::fs::read_to_string(path).unwrap_or_default()
107}
108
109fn write(path: &Path, text: &str) -> Result<(), String> {
111 if let Some(dir) = path.parent() {
112 std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?;
113 }
114 let tmp = path.with_extension("md.tmp");
115 std::fs::write(&tmp, text).map_err(|e| format!("can't write {}: {e}", tmp.display()))?;
116 std::fs::rename(&tmp, path).map_err(|e| format!("can't write {}: {e}", path.display()))
117}
118
119fn one_line(text: &str) -> String {
121 let joined = text.split_whitespace().collect::<Vec<_>>().join(" ");
122 let joined = joined.trim_start_matches(['-', '*', ' ']).to_owned();
123 match joined.char_indices().nth(MAX_NOTE_CHARS) {
124 Some((i, _)) => joined[..i].to_owned(),
125 None => joined,
126 }
127}
128
129fn norm(s: &str) -> String {
130 s.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase().trim_end_matches(['.', '!']).to_owned()
131}
132
133pub fn remember(files: &Files, scope: Scope, text: &str) -> Result<String, String> {
135 let note = one_line(text);
136 if note.is_empty() {
137 return Err("`text` is empty: say what to remember".into());
138 }
139 let path = files.need(scope)?;
140 let mut body = read(&path);
141 if notes(&body).iter().any(|(_, n)| norm(n) == norm(¬e)) {
142 return Ok(format!("Already remembered ({}).", scope.label()));
143 }
144 if body.len() > MAX_FILE {
145 return Err(format!("{} memory is full ({} KB); forget old notes first", scope.label(), MAX_FILE / 1024));
146 }
147 if body.trim().is_empty() {
148 body = format!("{HEADING}\n\n{INTRO}\n\n");
149 } else if !body.ends_with('\n') {
150 body.push('\n');
151 }
152 body.push_str("- ");
153 body.push_str(¬e);
154 body.push('\n');
155 write(&path, &body)?;
156 let mut msg = format!("Remembered ({}).", scope.label());
157 if body.len() > PROMPT_CAP {
158 msg.push_str(&format!(" That memory is over {} KB now, so only its start reaches the prompt: forget notes that no longer matter.", PROMPT_CAP / 1024));
159 }
160 Ok(msg)
161}
162
163fn drop_lines(path: &Path, lines: &[usize]) -> Result<(), String> {
165 let body = read(path);
166 let mut out: String = body.lines().enumerate().filter(|(i, _)| !lines.contains(i)).map(|(_, l)| format!("{l}\n")).collect();
167 if !body.ends_with('\n') && out.ends_with('\n') {
168 out.pop();
169 }
170 write(path, &out)
171}
172
173pub fn forget(files: &Files, scope: Option<Scope>, query: &str) -> Result<String, String> {
176 let q = query.trim();
177 if q.is_empty() {
178 return Err("`text` is empty: say which note to forget".into());
179 }
180 let scopes: Vec<Scope> = match scope {
181 Some(s) => {
182 files.need(s)?;
183 vec![s]
184 }
185 None => [Scope::Global, Scope::Workspace].into_iter().filter(|s| files.path(*s).is_some()).collect(),
186 };
187 if let Ok(n) = q.trim_start_matches('#').parse::<usize>() {
188 let [s] = scopes[..] else { return Err("give the scope with a note's number, or forget it by its text".into()) };
189 let path = files.need(s)?;
190 let all = notes(&read(&path));
191 let Some((line, text)) = n.checked_sub(1).and_then(|i| all.get(i)) else {
192 return Err(format!("{} memory has {} notes; there is no note {n}", s.label(), all.len()));
193 };
194 drop_lines(&path, &[*line])?;
195 return Ok(format!("Forgot ({}): {text}", s.label()));
196 }
197 let want = norm(q);
198 let mut exact: Vec<(Scope, usize, String)> = Vec::new();
199 let mut part: Vec<(Scope, usize, String)> = Vec::new();
200 for s in &scopes {
201 let Some(path) = files.path(*s) else { continue };
202 for (line, text) in notes(&read(&path)) {
203 let n = norm(&text);
204 if n == want {
205 exact.push((*s, line, text));
206 } else if n.contains(&want) {
207 part.push((*s, line, text));
208 }
209 }
210 }
211 let hits = if exact.is_empty() { part } else { exact };
212 match hits.len() {
213 0 => Err(format!("no note matches {q:?}")),
214 1 => {
215 let (s, line, text) = &hits[0];
216 drop_lines(&files.need(*s)?, &[*line])?;
217 Ok(format!("Forgot ({}): {text}", s.label()))
218 }
219 _ if hits.iter().all(|h| norm(&h.2) == norm(&hits[0].2)) => {
220 for s in [Scope::Global, Scope::Workspace] {
221 let lines: Vec<usize> = hits.iter().filter(|h| h.0 == s).map(|h| h.1).collect();
222 if !lines.is_empty() {
223 drop_lines(&files.need(s)?, &lines)?;
224 }
225 }
226 Ok(format!("Forgot: {}", hits[0].2))
227 }
228 n => {
229 let list: Vec<String> = hits.iter().take(5).map(|h| format!("- {} ({})", h.2, h.0.label())).collect();
230 Err(format!("{q:?} matches {n} notes; give more of the text:\n{}", list.join("\n")))
231 }
232 }
233}
234
235fn prompt_body(text: &str) -> String {
238 let mut body: Vec<&str> = text.lines().collect();
239 if body.first().is_some_and(|l| l.trim() == HEADING) {
240 body.remove(0);
241 }
242 body.retain(|l| l.trim() != INTRO);
243 let body = body.join("\n");
244 let body = body.trim();
245 if body.len() <= PROMPT_CAP {
246 return body.to_owned();
247 }
248 let mut cut = PROMPT_CAP;
249 while !body.is_char_boundary(cut) {
250 cut -= 1;
251 }
252 let head = &body[..cut];
253 let head = head.rfind('\n').map_or(head, |i| &head[..i]);
254 format!("{head}\n(… more notes not shown)")
255}
256
257pub fn prompt(files: &Files) -> String {
259 let mut out = String::from(
260 "Memory: notes kept across chats (the user can edit them too). When the user states a lasting preference or fact, save it with remember (scope \"workspace\" if it's only about this project); not task details or secrets. forget removes a wrong or outdated note.",
261 );
262 let global = files.path(Scope::Global).map(|p| prompt_body(&read(&p))).unwrap_or_default();
263 let ws = files.path(Scope::Workspace).map(|p| prompt_body(&read(&p))).unwrap_or_default();
264 if global.is_empty() && ws.is_empty() {
265 out.push_str(" Nothing is saved yet.");
266 }
267 if !global.is_empty() {
268 out.push_str("\nEverywhere:\n");
269 out.push_str(&global);
270 }
271 if !ws.is_empty() {
272 out.push_str("\nThis workspace:\n");
273 out.push_str(&ws);
274 }
275 out
276}
277
278fn card(files: &Files, scope: Scope) -> Value {
280 let (title, field) = match scope {
281 Scope::Global => ("Everywhere", "new_global"),
282 Scope::Workspace => ("This workspace", "new_workspace"),
283 };
284 let Some(path) = files.path(scope) else {
285 let why = match scope {
286 Scope::Global => "There is no config folder, so no global memory.",
287 Scope::Workspace => "Open a chat in a workspace to see its memory.",
288 };
289 return json!({"type": "card", "title": title, "children": [{"type": "text", "text": why, "tone": "dim"}]});
290 };
291 let text = read(&path);
292 let all = notes(&text);
293 let mut children = vec![json!({"type": "text", "text": path.display().to_string(), "style": "mono", "tone": "dim"})];
294 if all.is_empty() {
295 children.push(json!({"type": "text", "text": "Nothing saved yet.", "tone": "dim"}));
296 }
297 for (i, (_, note)) in all.iter().enumerate() {
298 children.push(json!({"type": "row", "children": [
299 {"type": "text", "text": note},
300 {"type": "button", "label": "Forget", "action": format!("forget:{}:{i}", scope.label())},
301 ]}));
302 }
303 let others = text.lines().filter(|l| !l.trim().is_empty()).count().saturating_sub(all.len());
304 if others > 2 {
305 children.push(json!({"type": "text", "text": "The file has other text too; it goes into the prompt as written.", "style": "small", "tone": "dim"}));
306 }
307 children.push(json!({"type": "row", "children": [
308 {"type": "input", "name": field, "placeholder": "Remember…", "submit": format!("add:{}", scope.label())},
309 {"type": "button", "label": "Add", "action": format!("add:{}", scope.label())},
310 ]}));
311 json!({"type": "card", "title": title, "children": children})
312}
313
314pub fn pane(files: &Files) -> Value {
316 json!({"type": "column", "children": [
317 {"type": "text", "text": "What byob remembers across chats. The files are plain Markdown: edit them in any editor too.", "style": "small", "tone": "dim"},
318 card(files, Scope::Global),
319 card(files, Scope::Workspace),
320 {"type": "button", "label": "Reload", "action": "reload"},
321 ]})
322}
323
324pub struct Memory {
326 config: Option<PathBuf>,
327 workspace: Option<PathBuf>,
329 drawn: bool,
331}
332
333pub fn factory(config: Option<PathBuf>) -> NativeFactory {
335 Arc::new(move || Box::new(Memory::new(config.clone())) as Box<dyn NativeBackend>)
336}
337
338fn workspace_of(v: &Value) -> Option<PathBuf> {
339 v.get("workspace").and_then(Value::as_str).filter(|w| !w.is_empty()).map(PathBuf::from)
340}
341
342impl Memory {
343 pub fn new(config: Option<PathBuf>) -> Self {
344 Self { config, workspace: None, drawn: false }
345 }
346
347 fn files(&self, workspace: Option<PathBuf>) -> Files {
348 Files { config: self.config.clone(), workspace }
349 }
350
351 fn pane_files(&self) -> Files {
352 self.files(self.workspace.clone())
353 }
354
355 fn refresh(&self, out: &Outbox) {
356 if self.drawn {
357 out.view(VIEW, "", pane(&self.pane_files()));
358 }
359 }
360
361 fn tool(&mut self, name: &str, args: &Value, workspace: Option<PathBuf>) -> Result<Value, String> {
362 let files = self.files(workspace);
363 let text = args.get("text").and_then(Value::as_str).unwrap_or_default();
364 let scope = Scope::parse(args.get("scope").and_then(Value::as_str))?;
365 let r = match name {
366 "remember" => remember(&files, scope.unwrap_or(Scope::Global), text),
367 "forget" => forget(&files, scope, text),
368 other => return Err(format!("this backend has no tool {other:?} (known: {})", TOOLS.join(", "))),
369 };
370 r.map(Value::String)
371 }
372
373 fn view_event(&mut self, ev: &Value, out: &Outbox) {
374 let action = ev.get("action").and_then(Value::as_str).unwrap_or_default();
375 let values = ev.get("values").cloned().unwrap_or(Value::Null);
376 let files = self.pane_files();
377 let scope_of = |s: &str| if s == "workspace" { Scope::Workspace } else { Scope::Global };
378 let mut clear = None;
379 let result = if let Some(s) = action.strip_prefix("add:") {
380 let field = if s == "workspace" { "new_workspace" } else { "new_global" };
381 let text = values.get(field).and_then(Value::as_str).unwrap_or_default();
382 clear = Some(field);
383 if text.trim().is_empty() { Ok(String::new()) } else { remember(&files, scope_of(s), text) }
384 } else if let Some(rest) = action.strip_prefix("forget:") {
385 let (s, i) = rest.split_once(':').unwrap_or((rest, ""));
386 match i.parse::<usize>() {
387 Ok(i) => forget(&files, Some(scope_of(s)), &(i.saturating_add(1)).to_string()),
388 Err(_) => Err(format!("bad action {action:?}")),
389 }
390 } else {
391 Ok(String::new())
392 };
393 if let Err(e) = result {
394 out.notice(&e, "error");
395 }
396 let tree = pane(&files);
397 match clear {
398 Some(field) => out.send(json!({"type": "view", "id": VIEW, "key": "", "view": tree, "values": {field: ""}, "client": ev.get("client")})),
399 None => out.view(VIEW, "", tree),
400 }
401 }
402}
403
404impl NativeBackend for Memory {
405 fn init(&mut self, _init: &Value, out: &Outbox) {
406 out.subscribe(&["chat_opened"]);
407 }
408
409 fn event(&mut self, ev: &Value, out: &Outbox) {
410 match ev.get("event").and_then(Value::as_str).unwrap_or_default() {
411 "view" => {
412 if let Some(w) = workspace_of(ev) {
413 self.workspace = Some(w);
414 }
415 self.drawn = true;
416 self.view_event(ev, out);
417 }
418 "chat_opened" => {
419 let w = workspace_of(ev);
420 if w.is_some() && w != self.workspace {
421 self.workspace = w;
422 self.refresh(out);
423 }
424 }
425 _ => {}
426 }
427 }
428
429 fn request(&mut self, method: &str, params: &Value, _out: &Outbox) -> Result<Value, String> {
430 match method {
431 "tool" => {
432 let name = params.get("name").and_then(Value::as_str).unwrap_or_default();
433 self.tool(name, params.get("args").unwrap_or(&Value::Null), workspace_of(params))
434 }
435 "hook" if params.get("event").and_then(Value::as_str) == Some("before_prompt") => {
436 let files = self.files(workspace_of(params));
437 Ok(json!({"action": "modify", "add": [{"id": "memory", "text": prompt(&files)}]}))
438 }
439 "hook" => Ok(json!({"action": "continue"})),
440 "view" => {
441 if let Some(w) = workspace_of(params) {
442 self.workspace = Some(w);
443 }
444 self.drawn = true;
445 Ok(pane(&self.pane_files()))
446 }
447 other => Err(format!("unknown request {other:?}")),
448 }
449 }
450
451 fn after_request(&mut self, method: &str, out: &Outbox) {
452 if method == "tool" {
453 self.refresh(out);
454 }
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use std::sync::Mutex;
462
463 fn files(dir: &Path) -> Files {
464 Files { config: Some(dir.join("config")), workspace: Some(dir.join("ws")) }
465 }
466
467 #[test]
468 fn remember_writes_plain_markdown_and_skips_duplicates() {
469 let dir = tempfile::tempdir().unwrap();
470 let f = files(dir.path());
471 assert_eq!(remember(&f, Scope::Global, "Prefers metric\nunits").unwrap(), "Remembered (global).");
472 assert_eq!(remember(&f, Scope::Global, "prefers metric units.").unwrap(), "Already remembered (global).");
473 remember(&f, Scope::Workspace, "- Uses pnpm").unwrap();
474 let g = std::fs::read_to_string(dir.path().join("config/memory.md")).unwrap();
475 assert_eq!(g, format!("{HEADING}\n\n{INTRO}\n\n- Prefers metric units\n"));
476 let w = std::fs::read_to_string(dir.path().join("ws/.byob/memory.md")).unwrap();
477 assert!(w.ends_with("\n- Uses pnpm\n"), "{w}");
478 assert!(remember(&f, Scope::Global, " ").is_err());
479 let none = Files { config: None, workspace: None };
480 assert!(remember(&none, Scope::Global, "x").unwrap_err().contains("scope \"workspace\""));
481 assert!(remember(&none, Scope::Workspace, "x").unwrap_err().contains("no workspace"));
482 std::fs::write(dir.path().join("ws/.byob/memory.md"), "My notes\n\n- a").unwrap();
484 remember(&f, Scope::Workspace, "b").unwrap();
485 assert_eq!(std::fs::read_to_string(dir.path().join("ws/.byob/memory.md")).unwrap(), "My notes\n\n- a\n- b\n");
486 }
487
488 #[test]
489 fn forget_by_text_part_or_number_and_refuses_ambiguity() {
490 let dir = tempfile::tempdir().unwrap();
491 let f = files(dir.path());
492 for n in ["likes tea", "likes green tea", "lives in Oslo"] {
493 remember(&f, Scope::Global, n).unwrap();
494 }
495 remember(&f, Scope::Workspace, "likes tea").unwrap();
496 assert_eq!(forget(&f, None, "Likes tea").unwrap(), "Forgot: likes tea");
498 assert!(!read(&dir.path().join("ws/.byob/memory.md")).contains("likes tea"));
499 remember(&f, Scope::Global, "likes black tea").unwrap();
500 let e = forget(&f, None, "tea").unwrap_err();
501 assert!(e.contains("matches 2 notes"), "{e}");
502 assert_eq!(forget(&f, None, "oslo").unwrap(), "Forgot (global): lives in Oslo");
503 assert!(forget(&f, None, "paris").unwrap_err().contains("no note matches"));
504 assert!(forget(&f, None, "1").is_err());
506 assert_eq!(forget(&f, Some(Scope::Global), "#2").unwrap(), "Forgot (global): likes black tea");
507 assert!(forget(&f, Some(Scope::Global), "9").unwrap_err().contains("has 1 notes"));
508 let g = read(&dir.path().join("config/memory.md"));
509 assert!(g.starts_with(HEADING) && g.ends_with("- likes green tea\n"), "{g}");
510 }
511
512 #[test]
513 fn the_prompt_holds_both_files_capped() {
514 let dir = tempfile::tempdir().unwrap();
515 let f = files(dir.path());
516 assert!(prompt(&f).ends_with("Nothing is saved yet."));
517 remember(&f, Scope::Global, "prefers metric units").unwrap();
518 remember(&f, Scope::Workspace, "the data is in data/").unwrap();
519 let p = prompt(&f);
520 assert!(p.ends_with("\nEverywhere:\n- prefers metric units\nThis workspace:\n- the data is in data/"), "{p}");
521 assert!(!p.contains(INTRO));
522 let big: String = (0..400).map(|i| format!("- note number {i}\n")).collect();
523 std::fs::write(dir.path().join("config/memory.md"), big).unwrap();
524 let p = prompt(&f);
525 assert!(p.len() < 2 * PROMPT_CAP, "{}", p.len());
526 assert!(p.contains("(… more notes not shown)"));
527 assert!(remember(&f, Scope::Global, "one more").unwrap().contains("only its start"));
528 }
529
530 fn collect() -> (Outbox, Arc<Mutex<Vec<Value>>>) {
531 let seen = Arc::new(Mutex::new(Vec::new()));
532 let s = Arc::clone(&seen);
533 (Outbox::new(move |m| s.lock().unwrap().push(m)), seen)
534 }
535
536 #[test]
537 fn the_backend_serves_tools_hook_and_pane() {
538 let dir = tempfile::tempdir().unwrap();
539 let ws = dir.path().join("ws");
540 let ws_s = ws.display().to_string();
541 let mut m = Memory::new(Some(dir.path().join("config")));
542 let (out, seen) = collect();
543 let r = m.request("tool", &json!({"name": "remember", "args": {"text": "uses metric", "scope": "workspace"}, "workspace": ws_s}), &out).unwrap();
544 assert_eq!(r, "Remembered (workspace).");
545 assert!(m.request("tool", &json!({"name": "remember", "args": {"text": "x", "scope": "galaxy"}}), &out).is_err());
546 assert!(m.request("tool", &json!({"name": "nope", "args": {}}), &out).is_err());
547 let hook = m.request("hook", &json!({"event": "before_prompt", "chat": "c", "workspace": ws_s, "sections": []}), &out).unwrap();
548 assert_eq!(hook["action"], "modify");
549 assert!(hook["add"][0]["text"].as_str().unwrap().contains("This workspace:\n- uses metric"));
550 assert!(seen.lock().unwrap().is_empty());
552 let tree = m.request("view", &json!({"site": "pane", "view": "memory", "key": "", "workspace": ws_s}), &out).unwrap();
553 let (_, faults) = byob_protocol::tree::decode(tree.clone());
554 assert!(faults.is_empty(), "{faults:?}");
555 assert!(tree.to_string().contains("uses metric"));
556 m.request("tool", &json!({"name": "remember", "args": {"text": "likes tea"}, "workspace": ws_s}), &out).unwrap();
557 m.after_request("tool", &out);
558 assert!(seen.lock().unwrap().last().unwrap()["view"].to_string().contains("likes tea"));
559 m.event(
561 &json!({"event": "view", "view": "memory", "action": "add:global", "values": {"new_global": "lives in Oslo"}, "client": 3, "workspace": ws_s}),
562 &out,
563 );
564 let last = seen.lock().unwrap().last().unwrap().clone();
565 assert_eq!(last["values"], json!({"new_global": ""}));
566 assert!(last["view"].to_string().contains("lives in Oslo"));
567 m.event(&json!({"event": "view", "view": "memory", "action": "forget:workspace:0", "values": {}, "workspace": ws_s}), &out);
568 assert!(!read(&ws.join(WORKSPACE_FILE)).contains("uses metric"));
569 let n = seen.lock().unwrap().len();
571 m.event(&json!({"event": "chat_opened", "chat": "c2", "client": 3, "workspace": dir.path().join("other").display().to_string()}), &out);
572 assert_eq!(seen.lock().unwrap().len(), n + 1);
573 assert!(!seen.lock().unwrap().last().unwrap()["view"].to_string().contains("uses metric"));
574 }
575}