capri-memory: add saved module
This commit is contained in:
1 file changed
+448
@@ -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<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct SavedMemory {
|
||||
pub items: Vec<SavedItem>,
|
||||
pub truncated: bool,
|
||||
pub unavailable: bool,
|
||||
}
|
||||
|
||||
fn re(p: &str) -> Regex {
|
||||
Regex::new(p).expect("valid saved-memory regex")
|
||||
}
|
||||
static CONTROL: LazyLock<Regex> = LazyLock::new(|| re(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]"));
|
||||
static NOTE_ENTRY: LazyLock<Regex> = LazyLock::new(|| re(r#"^- ([0-9]{4}-[0-9]{2}-[0-9]{2}) (".*")$"#));
|
||||
static FENCE: LazyLock<Regex> = LazyLock::new(|| re(r"^\s{0,3}(`{3,}|~{3,})"));
|
||||
static HEADING: LazyLock<Regex> = LazyLock::new(|| re(r"^\s{0,3}#{1,6}(?:\s|$)|^\s*(?:[-*_]\s*){3,}$"));
|
||||
static LIST_START: LazyLock<Regex> = LazyLock::new(|| re(r"^\s*(?:[-+*]|\d+[.)])\s+"));
|
||||
static SETEXT: LazyLock<Regex> = LazyLock::new(|| re(r"^\s{0,3}(?:={3,}|-{3,})\s*$"));
|
||||
static BULLET: LazyLock<Regex> = 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<String> {
|
||||
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<String>)) {
|
||||
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<String> = Vec::new();
|
||||
let mut list_indent: Option<usize> = None;
|
||||
let mut pending_blank = false;
|
||||
let mut fence: Option<String> = None;
|
||||
let mut comment = false;
|
||||
fn flush(block: &mut Vec<String>, list_indent: &mut Option<usize>, pending_blank: &mut bool, append: &mut dyn FnMut(String, Option<String>)) {
|
||||
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::<String>(&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("<!--") {
|
||||
None => return text + rest,
|
||||
Some(start) => {
|
||||
text.push_str(&rest[..start]);
|
||||
*comment = true;
|
||||
rest = &rest[start + 4..];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Reader {
|
||||
root: std::path::PathBuf,
|
||||
snapshot: SavedMemory,
|
||||
bytes: u64,
|
||||
files: usize,
|
||||
entries: usize,
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
fn exhausted(&self) -> bool {
|
||||
self.snapshot.items.len() >= ITEMS || self.bytes >= TOTAL_BYTES || self.files >= FILES
|
||||
}
|
||||
|
||||
fn add(&mut self, source: &str, text: String, date: Option<String>) {
|
||||
if text.is_empty() || PLACEHOLDERS.contains(&text.as_str()) {
|
||||
return;
|
||||
}
|
||||
if self.snapshot.items.len() >= ITEMS {
|
||||
self.snapshot.truncated = true;
|
||||
return;
|
||||
}
|
||||
let text = if capri_core::utf16_len(&text) > ITEM_CHARS {
|
||||
self.snapshot.truncated = true;
|
||||
truncate_utf16(&text, ITEM_CHARS).to_string()
|
||||
} else {
|
||||
text
|
||||
};
|
||||
let id = sha256_hex(format!("{source}\0{}\0{text}", self.snapshot.items.len()).as_bytes())[..24].to_string();
|
||||
self.snapshot.items.push(SavedItem { id, text, source: source.into(), date });
|
||||
}
|
||||
|
||||
fn inside(&self, path: &Path) -> bool {
|
||||
fs::canonicalize(path).is_ok_and(|p| p != self.root && p.starts_with(&self.root))
|
||||
}
|
||||
|
||||
fn read(&mut self, file: &Path) {
|
||||
if self.exhausted() {
|
||||
self.snapshot.truncated = true;
|
||||
return;
|
||||
}
|
||||
let before = match fs::symlink_metadata(file) {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
|
||||
Err(_) => return self.snapshot.unavailable = true,
|
||||
};
|
||||
if !before.file_type().is_file() || before.nlink() != 1 || !self.inside(file) {
|
||||
return self.snapshot.unavailable = true;
|
||||
}
|
||||
self.files += 1;
|
||||
let remaining = FILE_BYTES.min(TOTAL_BYTES - self.bytes);
|
||||
if before.len() > remaining {
|
||||
self.snapshot.truncated = true;
|
||||
return;
|
||||
}
|
||||
let source = file.strip_prefix(&self.root).map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
if source.len() > 512 || source.chars().any(|c| c.is_control()) {
|
||||
return self.snapshot.unavailable = true;
|
||||
}
|
||||
let Ok(handle) = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(file) else {
|
||||
return self.snapshot.unavailable = true;
|
||||
};
|
||||
let same = handle.metadata().is_ok_and(|m| m.is_file() && m.nlink() == 1 && m.dev() == before.dev() && m.ino() == before.ino());
|
||||
let mut bytes = Vec::new();
|
||||
if !same || handle.take(remaining + 1).read_to_end(&mut bytes).is_err() {
|
||||
return self.snapshot.unavailable = true;
|
||||
}
|
||||
self.bytes += bytes.len() as u64;
|
||||
if bytes.len() as u64 > remaining {
|
||||
self.snapshot.truncated = true;
|
||||
return;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes).into_owned();
|
||||
let mut found = Vec::new();
|
||||
memory_blocks(&text, &source, &mut |t, d| found.push((t, d)));
|
||||
for (text, date) in found {
|
||||
self.add(&source, text, date);
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(&mut self, dir: &Path, depth: usize) {
|
||||
if self.exhausted() || self.entries >= ENTRIES {
|
||||
self.snapshot.truncated = true;
|
||||
return;
|
||||
}
|
||||
match fs::symlink_metadata(dir) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
|
||||
Ok(m) if m.is_dir() && self.inside(dir) => {}
|
||||
_ => return self.snapshot.unavailable = true,
|
||||
}
|
||||
let Ok(list) = fs::read_dir(dir) else { return self.snapshot.unavailable = true };
|
||||
let mut names = Vec::new();
|
||||
for entry in list.flatten() {
|
||||
if self.entries >= ENTRIES {
|
||||
self.snapshot.truncated = true;
|
||||
break;
|
||||
}
|
||||
self.entries += 1;
|
||||
names.push(entry.file_name());
|
||||
}
|
||||
names.sort();
|
||||
for name in names {
|
||||
if self.exhausted() {
|
||||
self.snapshot.truncated = true;
|
||||
break;
|
||||
}
|
||||
let path = dir.join(&name);
|
||||
let Ok(info) = fs::symlink_metadata(&path) else { continue };
|
||||
if info.file_type().is_symlink() {
|
||||
self.snapshot.unavailable = true;
|
||||
} else if info.is_dir() {
|
||||
if depth >= DEPTH {
|
||||
self.snapshot.truncated = true;
|
||||
} else {
|
||||
self.visit(&path, depth + 1);
|
||||
}
|
||||
} else if info.is_file() && name.to_string_lossy().to_lowercase().ends_with(".md") {
|
||||
self.read(&path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owner-memory snapshot for the Settings viewer: USER.md, MEMORY.md, then memory/**/*.md.
|
||||
pub fn read_saved_memory(workspace: &Path) -> SavedMemory {
|
||||
let root = match fs::canonicalize(workspace) {
|
||||
Ok(root) if root.is_dir() => root,
|
||||
_ => return SavedMemory { unavailable: true, ..Default::default() },
|
||||
};
|
||||
let mut reader = Reader { root: root.clone(), snapshot: SavedMemory::default(), bytes: 0, files: 0, entries: 0 };
|
||||
reader.read(&root.join("USER.md"));
|
||||
reader.read(&root.join("MEMORY.md"));
|
||||
reader.visit(&root.join("memory"), 0);
|
||||
reader.snapshot
|
||||
}
|
||||
|
||||
/// Viewer search: every word of the query must appear in the text or the source.
|
||||
pub fn matches(item: &SavedItem, query: &str) -> bool {
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
let fold = |s: &str| s.nfkc().collect::<String>().to_lowercase();
|
||||
let haystack = fold(&format!("{} {}", item.text, item.source));
|
||||
fold(query).split_whitespace().all(|w| haystack.contains(w))
|
||||
}
|
||||
|
||||
/// Deletes notes under memory/ and empties USER.md and MEMORY.md. Conversation archives are kept.
|
||||
/// The caller resets the derived index (see `MemoryService::clear_long_term_memory`).
|
||||
pub fn clear_saved_memory(workspace: &Path) -> Result<()> {
|
||||
let root = fs::canonicalize(workspace)?;
|
||||
let mut files = Vec::new();
|
||||
fn visit(root: &Path, dir: &Path, files: &mut Vec<std::path::PathBuf>) -> Result<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let path = entry?.path();
|
||||
let info = fs::symlink_metadata(&path)?;
|
||||
if info.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
if !fs::canonicalize(&path)?.starts_with(root) {
|
||||
bail!("Memory path escapes the workspace.");
|
||||
}
|
||||
if info.is_dir() {
|
||||
visit(root, &path, files)?;
|
||||
} else if info.is_file() && path.extension().is_some_and(|e| e.eq_ignore_ascii_case("md")) {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let folder = root.join("memory");
|
||||
if let Ok(info) = fs::symlink_metadata(&folder) {
|
||||
if info.file_type().is_symlink() {
|
||||
bail!("Linked memory folders cannot be cleared.");
|
||||
}
|
||||
visit(&root, &folder, &mut files)?;
|
||||
}
|
||||
for name in ["USER.md", "MEMORY.md"] {
|
||||
if fs::symlink_metadata(root.join(name)).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
bail!("Linked memory files cannot be cleared.");
|
||||
}
|
||||
}
|
||||
for file in files {
|
||||
fs::remove_file(file)?;
|
||||
}
|
||||
for name in ["USER.md", "MEMORY.md"] {
|
||||
capri_core::fsutil::write_atomic(&root.join(name), b"")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(ws: &Path, name: &str, text: &str) {
|
||||
let path = ws.join(name);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_templates_show_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(read_saved_memory(dir.path()), SavedMemory::default());
|
||||
write(dir.path(), "USER.md", "# User\n\nNo user preferences have been saved yet.\n");
|
||||
write(dir.path(), "MEMORY.md", "# Memory\n\nNo memories have been saved yet.\n");
|
||||
assert_eq!(read_saved_memory(dir.path()), SavedMemory::default());
|
||||
assert!(!dir.path().join("memory").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_shows_notes_and_blocks() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ws = dir.path();
|
||||
write(ws, "USER.md", "# User\n\n<!-- hidden internal text -->\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 \"<img src=x onerror=alert(1)>\"\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, ["<img src=x onerror=alert(1)>", "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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user