From 2c5d62b8c5e909c4ff9aa4e4b392032d36cade3a Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-memory: add saved module --- crates/capri-memory/src/saved.rs | 448 +++++++++++++++++++++++++++++++ 1 file changed, 448 insertions(+) create mode 100644 crates/capri-memory/src/saved.rs diff --git a/crates/capri-memory/src/saved.rs b/crates/capri-memory/src/saved.rs new file mode 100644 index 0000000..d83131f --- /dev/null +++ b/crates/capri-memory/src/saved.rs @@ -0,0 +1,448 @@ +//! Saved-memory viewer and "Clear long-term memory" (Capri `saved-memory.mjs`, `memory-controls.mjs`). +//! The viewer only reads owner-memory Markdown: never a model, the index or conversation archives. +use std::fs::{self, OpenOptions}; +use std::io::Read; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::path::Path; +use std::sync::LazyLock; + +use anyhow::{bail, Result}; +use regex::Regex; +use serde::Serialize; + +use crate::notes::NOTE_FILE; +use crate::{sha256_hex, truncate_utf16}; + +const FILE_BYTES: u64 = 128 * 1024; +const TOTAL_BYTES: u64 = 1024 * 1024; +const ENTRIES: usize = 4096; +const FILES: usize = 128; +const DEPTH: usize = 6; +const ITEMS: usize = 500; +const ITEM_CHARS: usize = 6000; +const PLACEHOLDERS: [&str; 2] = ["No user preferences have been saved yet.", "No memories have been saved yet."]; + +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct SavedItem { + pub id: String, + pub text: String, + pub source: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct SavedMemory { + pub items: Vec, + pub truncated: bool, + pub unavailable: bool, +} + +fn re(p: &str) -> Regex { + Regex::new(p).expect("valid saved-memory regex") +} +static CONTROL: LazyLock = LazyLock::new(|| re(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")); +static NOTE_ENTRY: LazyLock = LazyLock::new(|| re(r#"^- ([0-9]{4}-[0-9]{2}-[0-9]{2}) (".*")$"#)); +static FENCE: LazyLock = LazyLock::new(|| re(r"^\s{0,3}(`{3,}|~{3,})")); +static HEADING: LazyLock = LazyLock::new(|| re(r"^\s{0,3}#{1,6}(?:\s|$)|^\s*(?:[-*_]\s*){3,}$")); +static LIST_START: LazyLock = LazyLock::new(|| re(r"^\s*(?:[-+*]|\d+[.)])\s+")); +static SETEXT: LazyLock = LazyLock::new(|| re(r"^\s{0,3}(?:={3,}|-{3,})\s*$")); +static BULLET: LazyLock = LazyLock::new(|| re(r"^(\s*)(?:[-+*]|\d+[.)])\s+(.+)$")); + +fn clean(text: &str) -> String { + CONTROL.replace_all(text, "").trim().to_string() +} + +fn note_date(value: &str) -> Option { + chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").ok().map(|_| value.to_string()) +} + +/// Splits Markdown into displayable blocks (a source viewer, not an interpretation of facts). +fn memory_blocks(content: &str, source: &str, append: &mut dyn FnMut(String, Option)) { + let content = content.strip_prefix('\u{FEFF}').unwrap_or(content).replace("\r\n", "\n").replace('\r', "\n"); + let lines: Vec<&str> = content.split('\n').collect(); + let mut block: Vec = Vec::new(); + let mut list_indent: Option = None; + let mut pending_blank = false; + let mut fence: Option = None; + let mut comment = false; + fn flush(block: &mut Vec, list_indent: &mut Option, pending_blank: &mut bool, append: &mut dyn FnMut(String, Option)) { + if !block.is_empty() { + append(clean(&block.join("\n")), None); + } + block.clear(); + *list_indent = None; + *pending_blank = false; + } + let mut i = 0; + while i < lines.len() { + let raw = lines[i]; + i += 1; + if let Some(f) = &fence { + block.push(raw.to_string()); + let close = Regex::new(&format!(r"^\s*{}{{{},}}\s*$", regex::escape(&f[..1]), f.len())).expect("fence regex"); + if close.is_match(raw) { + fence = None; + flush(&mut block, &mut list_indent, &mut pending_blank, append); + } + continue; + } + // The writer's JSON string is data, even when it looks like HTML or Markdown. + if !comment + && source == format!("memory/{NOTE_FILE}") + && let Some(c) = NOTE_ENTRY.captures(raw) + && let Ok(note) = serde_json::from_str::(&c[2]) + { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + append(clean(¬e), note_date(&c[1])); + continue; + } + let line = visible(raw, &mut comment); + let trimmed = line.trim(); + if let Some(c) = FENCE.captures(&line) { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + fence = Some(c[1].to_string()); + block.push(line.clone()); + continue; + } + if trimmed.is_empty() { + if list_indent.is_some() { + pending_blank = true; + } else { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + } + continue; + } + if HEADING.is_match(&line) { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + continue; + } + if i < lines.len() && !LIST_START.is_match(&line) && SETEXT.is_match(lines[i]) { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + i += 1; + continue; + } + if PLACEHOLDERS.contains(&trimmed) { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + continue; + } + let indent = line.len() - line.trim_start().len(); + match BULLET.captures(&line) { + Some(b) if list_indent.is_none_or(|l| b[1].len() <= l) => { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + list_indent = Some(b[1].len()); + block.push(b[2].to_string()); + } + _ => { + if pending_blank { + if list_indent.is_some_and(|l| indent > l) { + block.push(String::new()); + } else { + flush(&mut block, &mut list_indent, &mut pending_blank, append); + } + } + pending_blank = false; + block.push(line); + } + } + } + flush(&mut block, &mut list_indent, &mut pending_blank, append); +} + +/// Text of `line` outside HTML comments; `comment` carries an open comment to the next line. +fn visible(line: &str, comment: &mut bool) -> String { + let mut text = String::new(); + let mut rest = line; + loop { + if *comment { + match rest.find("-->") { + None => return text, + Some(end) => { + *comment = false; + rest = &rest[end + 3..]; + } + } + } else { + match rest.find("\n- I prefer green tea.\n Especially loose leaf.\n - With no sugar.\n\n More detail.\n\n- I use a light theme.\n"); + write(ws, "MEMORY.md", "\u{FEFF}# Memory\r\n\r\nI use a dark theme.\r\nI switch themes often.\r\n"); + write(ws, "memory/capri-owner-notes.md", "# Explicit owner notes\n\n- 2026-11-05 \"My favorite game is Space Test\"\n- 2026-11-06 \"My favorite game is Another Test\"\n"); + write(ws, "memory/projects/work.md", "Project\n=======\n\n- Finish the synthetic project.\n"); + write(ws, "SOUL.md", "Do not expose"); + write(ws, "memory/notes.txt", "Do not read"); + let result = read_saved_memory(ws); + let texts: Vec<_> = result.items.iter().map(|i| i.text.as_str()).collect(); + assert_eq!( + texts, + [ + "I prefer green tea.\n Especially loose leaf.\n - With no sugar.\n\n More detail.", + "I use a light theme.", + "I use a dark theme.\nI switch themes often.", + "My favorite game is Space Test", + "My favorite game is Another Test", + "Finish the synthetic project.", + ] + ); + assert_eq!(result.items[3].date.as_deref(), Some("2026-11-05")); + assert_eq!(result.items[5].source, "memory/projects/work.md"); + assert!(!result.truncated && !result.unavailable); + assert_eq!(read_saved_memory(ws), result); + assert!(matches(&result.items[0], "GREEN tea")); + assert!(!matches(&result.items[0], "green coffee")); + } + + #[test] + fn invalid_records_stay_plain_and_links_are_refused() { + let dir = tempfile::tempdir().unwrap(); + let ws = dir.path().join("ws"); + write(&ws, "memory/capri-owner-notes.md", "# Notes\n\n- 2026-11-05 \"\"\n- 2026-11-06 \"Broken JSON\n"); + let texts: Vec<_> = read_saved_memory(&ws).items.into_iter().map(|i| i.text).collect(); + assert_eq!(texts, ["", "2026-11-06 \"Broken JSON"]); + fs::remove_dir_all(ws.join("memory")).unwrap(); + let outside = dir.path().join("outside"); + write(&outside, "secret.md", "Outside fixture content"); + std::os::unix::fs::symlink(&outside, ws.join("memory")).unwrap(); + fs::hard_link(outside.join("secret.md"), ws.join("USER.md")).unwrap(); + let result = read_saved_memory(&ws); + assert!(result.items.is_empty() && result.unavailable); + assert!(clear_saved_memory(&ws).is_err()); + assert_eq!(fs::read_to_string(outside.join("secret.md")).unwrap(), "Outside fixture content"); + } + + #[test] + fn clear_removes_notes_and_empties_profile() { + let dir = tempfile::tempdir().unwrap(); + let ws = dir.path(); + write(ws, "USER.md", "x"); + write(ws, "MEMORY.md", "y"); + write(ws, "memory/a.md", "z"); + write(ws, "memory/deep/b.md", "z"); + write(ws, "memory/keep.txt", "z"); + clear_saved_memory(ws).unwrap(); + assert_eq!(fs::read_to_string(ws.join("USER.md")).unwrap(), ""); + assert!(!ws.join("memory/a.md").exists() && !ws.join("memory/deep/b.md").exists()); + assert!(ws.join("memory/keep.txt").exists()); + } +}