Files
capri-core-rust/crates/capri-memory/src/notes.rs
T

428 lines
22 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Explicit owner notes fast path (Capri `owner-notes.mjs`): "remember that my X is Y"
//! is saved to `<ws>/memory/capri-owner-notes.md` without a model call, and "what is my X?" is
//! answered from that file.
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use anyhow::{bail, Result};
use capri_core::utf16_len;
use regex::Regex;
use unicode_normalization::UnicodeNormalization;
pub const NOTE_FILE: &str = "capri-owner-notes.md";
pub const MAX_NOTE: usize = 1200;
const MAX_FILE: u64 = 128 * 1024;
/// Journal replies (the engine translates "Done." through the interface catalog).
pub const REPLY_SAVED: &str = "Done.";
pub fn reply_failed(language: &str) -> &'static str {
if language == "ru" { "Не удалось сохранить заметку." } else { "The note could not be saved." }
}
pub fn reply_refused(language: &str) -> &'static str {
if language == "ru" { "Я не сохраняю пароли и ключи доступа в памяти." } else { "I can’t save passwords or access keys in memory." }
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NoteRequest {
Save(String),
Refused,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Saved {
pub already_saved: bool,
}
fn re(pattern: &str) -> Regex {
Regex::new(pattern).expect("valid owner-notes regex")
}
// `(?-u:\b)` keeps JavaScript's ASCII word boundaries.
static OPTIONAL_NAME: LazyLock<Regex> = LazyLock::new(|| re(r"(?i)^(?:(?:hey\s+)?(?:capri|капри)[,:!]?\s+)"));
pub(crate) static ENGLISH_FACT: LazyLock<Regex> = LazyLock::new(|| re(r"(?i)^(?:my|our)\s+(.+?)\s+(?:is|are|was|were)\s+(.+)$"));
pub(crate) static RUSSIAN_FACT: LazyLock<Regex> = LazyLock::new(|| re(r"(?i)^мо(?:й|я|ё|е|и)\s+(.+?)\s*[:—–-]\s*(.+)$"));
pub(crate) static PORTUGUESE_FACT: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)^(?:(?:o|a|os|as)\s+)?(?:meu|minha|meus|minhas|nosso|nossa|nossos|nossas)\s+(.+?)\s+(?:é|são|era|eram)\s+(.+)$")
});
static FILE_SUBJECT: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)(?:^|[^\p{L}\p{N}_])(?:files?|folders?|documents?|workbooks?|spreadsheets?|reports?|scripts?|screenshots?|images?|pictures?|videos?|recordings?|screens?|cameras?|microphones?|logs?|applications?|apps?|programs?|notes?|drafts?|projects?|work|homework|progress|sessions?|tabs?|pages?|windows?|bookmarks?|selections?|clipboard|browsers?|views?|text|content|messages?|chats?|conversations?|arquivos?|ficheiros?|pastas?|documentos?|planilhas?|relat[oó]rios?|imagens?|v[ií]deos?|grava[cç][oõ]es|telas?|c[aâ]meras?|microfones?|aplicativos?|programas?|rascunhos?|projetos?|trabalho|tarefas?|sess[oõ]es|abas?|guias?|p[aá]ginas?|janelas?|favoritos?|marcadores?|sele[cç][aã]o|sele[cç][oõ]es|[aá]rea de transfer[eê]ncia|navegadores?|visualiza[cç][aã]o|textos?|conte[uú]do|mensagens?|conversas?)(?:$|[^\p{L}\p{N}_])|[\\/:]")
});
pub(crate) static SENSITIVE: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)(?-u:\b)(?:password|passphrase|passcode|pin(?: code)?|secret key|api key|access token|private key|recovery phrase|seed phrase|bearer|senhas?|palavra[ -]passe|c[oó]digo de acesso|token de acesso|chave(?: de)? (?:api|acesso|recupera[cç][aã]o|privada|secreta)|frase (?:semente|de recupera[cç][aã]o))(?-u:\b)|парол[ьяюе]|код доступа|секретн\p{L}* ключ|токен|api[ -]?ключ|(?-u:\b)(?:sk-[0-9A-Za-z_-]{12,}|gh[pousr]_[0-9A-Za-z_]{16,}|github_pat_[0-9A-Za-z_]{16,}|hf_[0-9A-Za-z_]{16,}|AKIA[A-Z0-9]{16})(?-u:\b)|-----BEGIN [A-Z ]+PRIVATE KEY-----|https?://[^\s/@:]+:[^\s/@]+@")
});
static COMPOUND: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)(?:(?-u:\b)(?:and|then|also)\s+(?:then\s+)?(?:(?:please|kindly)\s+)?(?:open|launch|start|stop|send|save|store|record|write|type|click|download|delete|install|run|turn|tell|show|search|find|set|change|enable|disable|use|play|pause|resume|press|scroll|move|copy|read)(?-u:\b)|(?:\s|^)(?:и|затем|потом|также)\s+(?:пожалуйста\s+)?(?:открой|запусти|закрой|отправь|сохрани|напиши|нажми|скачай|удали|установи|включи|выключи|скажи|покажи|найди|измени)|(?:\s|^)(?:e|depois|ent[aã]o|tamb[eé]m|em seguida)\s+(?:por\s+favor\s+)?(?:abra|inicie|execute|envie|salve|anote|digite|clique|baixe|apague|exclua|instale|ative|desative|diga|mostre|procure|pesquise|altere|use|toque|pause|copie|mova))")
});
static COURTESY: LazyLock<Regex> = LazyLock::new(|| re(r"(?i),\s*(?:please|kindly|por favor|пожалуйста)[.!?]*$"));
static END_PUNCT: LazyLock<Regex> = LazyLock::new(|| re(r"[.!?]+$"));
static REDUNDANT_SAVE: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)(?:,\s*(?:and\s+)?|\s+and\s+)(?:(?:please|kindly)\s+)?(?:(?:write|note|jot)\s+(?:it|that)\s+down|(?:save|store|record|remember)\s+(?:it|that)(?:\s+(?:in|to)\s+(?:(?:your|long-term|long term)\s+)?(?:memory|notes))?)$|(?:,\s*(?:e\s+)?|\s+e\s+)(?:anote(?:\s+isso)?|(?:guarde|salve|registre)\s+isso(?:\s+(?:na|em sua)\s+mem[oó]ria)?)$")
});
static POLITE_EN: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)^(?:(?:please|kindly)[,\s]+)?(?:(?:(?:can|could|would)\s+you|i\s+(?:want|need|would\s+like)\s+you\s+to)\s+)?(?:(?:please|kindly)[,\s]+)?")
});
static POLITE_PT: LazyLock<Regex> = LazyLock::new(|| re(r"(?i)^(?:por\s+favor[,\s]+)?(?:(?:voc[eê]\s+)?(?:pode|poderia)\s+(?:por\s+favor[,\s]+)?)?"));
static EXPLICIT: LazyLock<[Regex; 3]> = LazyLock::new(|| {
[
re(r"(?i)^remember\s*(?:that\s+|:\s*)(.+)$"),
re(r"(?i)^(?:пожалуйста[, ]+)?запомни(?:те)?(?:,?\s+что\s+|\s*:\s*|[, ]+)(.+)$"),
re(r"(?i)^(?:lembre(?:-se)?|lembrar(?:-se)?)(?:\s+de)?(?:\s+que\s+|\s*:\s*)(.+)$"),
]
});
static PLAIN: LazyLock<Regex> = LazyLock::new(|| re(r"(?i)^(?:remember|lembre(?:-se)?|lembrar(?:-se)?)\s+(?:de\s+)?(.+)$"));
static ALIAS: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)^(?:save|store|record|write\s+down|note\s+down|jot\s+down|anote|anotar|guarde|guardar|salve|salvar|registre|registrar)(?:\s+(?:(?:that|que)\s+)?|:\s*)(.+)$")
});
static AS_EN: LazyLock<Regex> = LazyLock::new(|| re(r"(?i)^(my|our)\s+(.+?)\s+as\s+(.+)$"));
static AS_PT: LazyLock<Regex> = LazyLock::new(|| {
re(r"(?i)^(?:(?:o|a|os|as)\s+)?(meu|minha|meus|minhas|nosso|nossa|nossos|nossas)\s+(.+?)\s+como\s+(.+)$")
});
static SEPARATORS: LazyLock<Regex> = LazyLock::new(|| re(r"[\p{Cc}\p{Zl}\p{Zp}]"));
static QUESTION: LazyLock<Regex> = LazyLock::new(|| re(r"\?(?:\s|$)"));
static RECORD: LazyLock<Regex> = LazyLock::new(|| re(r#"^- [0-9]{4}-[0-9]{2}-[0-9]{2} (".*")$"#));
static NON_WORD: LazyLock<Regex> = LazyLock::new(|| re(r"[^\p{L}\p{N}]+"));
static RECALL: LazyLock<[Regex; 4]> = LazyLock::new(|| {
[
re(r"(?i)^(?:what(?: is| was|'s)|do you remember|can you recall|tell me)\s+(?:my|our)\s+(.+?)(?:\s+(?:is|was))?[?.!]*$"),
re(r"(?i)^(?:what|which)\s+(.+?)\s+did I (?:ask|tell) you to (?:remember|save)[?.!]*$"),
re(r"(?i)^(?:како[йея]|какая|какие|какого цвета)\s+(?:мо[йяёи]|мое)\s+(.+?)[?.!]*$"),
re(r"(?i)^(?:qual|quais)\s+(?:é|são|era|eram)\s+(?:(?:o|a|os|as)\s+)?(?:meu|minha|meus|minhas|nosso|nossa|nossos|nossas)\s+(.+?)[?.!]*$"),
]
});
pub fn is_sensitive(text: &str) -> bool {
SENSITIVE.is_match(text)
}
fn prompt(value: &str) -> String {
OPTIONAL_NAME.replace(value.trim(), "").trim().to_string()
}
fn without_courtesy(value: &str) -> String {
let value = COURTESY.replace(value, "");
END_PUNCT.replace(&value, "").trim().to_string()
}
pub(crate) fn fact(text: &str) -> Option<(String, String)> {
[&*ENGLISH_FACT, &*RUSSIAN_FACT, &*PORTUGUESE_FACT]
.iter()
.find_map(|r| r.captures(text))
.map(|c| (c[1].to_string(), c[2].to_string()))
}
fn supplied_fact(value: &str, as_value: bool) -> Option<String> {
if fact(value).is_some() {
return Some(value.to_string());
}
if !as_value {
return None;
}
if let Some(c) = AS_EN.captures(value) {
return Some(format!("{} {} is {}", &c[1], &c[2], &c[3]));
}
AS_PT.captures(value).map(|c| format!("{} {} é {}", &c[1], &c[2], &c[3]))
}
/// Matches an explicit note supplied in this user turn (never the model's prose).
pub fn owner_note_request(value: &str) -> Option<NoteRequest> {
let text = prompt(value);
let text = POLITE_EN.replace(&text, "");
let text = POLITE_PT.replace(&text, "").to_string();
let explicit = EXPLICIT.iter().find_map(|r| r.captures(&text));
let plain = PLAIN.captures(&text);
let alias = ALIAS.captures(&text);
let raw = [&explicit, &plain, &alias].iter().find_map(|c| c.as_ref().map(|c| c[1].to_string())).unwrap_or_default();
let mut note = without_courtesy(raw.trim());
for _ in 0..2 {
note = REDUNDANT_SAVE.replace(&note, "").trim().to_string();
}
if note.is_empty() {
return None;
}
if explicit.is_none() {
note = supplied_fact(&note, alias.is_some())?;
let (subject, _) = fact(&note)?;
if alias.is_some() && FILE_SUBJECT.is_match(&subject) {
return None;
}
}
if is_sensitive(&note) {
return Some(NoteRequest::Refused);
}
if utf16_len(&note) > MAX_NOTE || SEPARATORS.is_match(&note) || QUESTION.is_match(&note) || COMPOUND.is_match(&note) {
return None;
}
Some(NoteRequest::Save(note))
}
pub(crate) fn subject_key(value: &str) -> String {
let folded: String = value.nfkc().collect::<String>().to_lowercase();
NON_WORD.replace_all(&folded, " ").trim().to_string()
}
fn notes_dir(workspace: &Path, create: bool) -> Result<PathBuf> {
let root = fs::canonicalize(workspace)?;
let dir = root.join("memory");
if create {
use std::os::unix::fs::DirBuilderExt;
fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir)?;
}
let info = fs::symlink_metadata(&dir)?;
if !info.is_dir() || fs::canonicalize(&dir)? != dir {
bail!("Unsafe owner notes directory");
}
Ok(dir)
}
fn open_note_file(workspace: &Path, create: bool) -> Result<File> {
let path = notes_dir(workspace, create)?.join(NOTE_FILE);
let before = match fs::symlink_metadata(&path) {
Ok(m) => Some(m),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && create => None,
Err(e) => return Err(e.into()),
};
if let Some(b) = &before
&& (!b.file_type().is_file() || b.nlink() != 1)
{
bail!("Unsafe owner notes file");
}
let mut options = OpenOptions::new();
options.read(true).custom_flags(libc::O_NOFOLLOW).mode(0o600);
if create {
options.append(true).create_new(before.is_none());
}
let file = options.open(&path)?;
let info = file.metadata()?;
if !info.is_file() || info.nlink() != 1 || info.len() > MAX_FILE || before.is_some_and(|b| b.dev() != info.dev() || b.ino() != info.ino()) {
bail!("Unsafe or oversized owner notes file");
}
Ok(file)
}
/// Valid notes of the file, in order.
pub(crate) fn records(content: &str) -> Vec<String> {
content
.split('\n')
.map(|l| l.strip_suffix('\r').unwrap_or(l))
.filter_map(|line| RECORD.captures(line))
.filter_map(|c| serde_json::from_str::<String>(&c[1]).ok())
.filter(|note| utf16_len(note) <= MAX_NOTE && !is_sensitive(note))
.collect()
}
fn read_all(file: &mut File) -> Result<String> {
file.seek(SeekFrom::Start(0))?;
let mut text = String::new();
file.take(MAX_FILE + 1).read_to_string(&mut text)?;
Ok(text)
}
/// Appends one note (also used by the Settings "Save memory" action). Only this fixed file is written.
pub fn save_owner_note(workspace: &Path, note: &str) -> Result<Saved> {
if note.trim().is_empty() || utf16_len(note) > MAX_NOTE || SEPARATORS.is_match(note) || is_sensitive(note) {
bail!("Invalid owner note");
}
let mut file = open_note_file(workspace, true)?;
let content = read_all(&mut file)?;
if records(&content).last().is_some_and(|n| n == note) {
return Ok(Saved { already_saved: true });
}
let line = format!("- {} {}\n", chrono::Utc::now().format("%Y-%m-%d"), serde_json::to_string(note)?);
let entry = if content.is_empty() {
format!("# Explicit owner notes\n\n{line}")
} else if content.ends_with('\n') {
line
} else {
format!("\n{line}")
};
if (content.len() + entry.len()) as u64 > MAX_FILE {
bail!("Owner notes file is full");
}
file.write_all(entry.as_bytes())?;
file.sync_all()?;
let written = read_all(&mut file)?;
if records(&written).last().is_none_or(|n| n != note) {
bail!("The memory could not be verified.");
}
Ok(Saved { already_saved: false })
}
/// Reads back a matching simple owner fact without a model or a stale index.
pub fn recall_owner_note(workspace: &Path, value: &str) -> Option<String> {
let text = without_courtesy(&prompt(value));
let subject = RECALL.iter().find_map(|r| r.captures(&text))?[1].to_string();
if is_sensitive(&subject) {
return None;
}
let key = subject_key(&subject);
if key.is_empty() || utf16_len(&key) > 120 {
return None;
}
let mut file = open_note_file(workspace, false).ok()?;
let content = read_all(&mut file).ok()?;
let mut facts: Vec<(String, String)> = Vec::new();
for note in records(&content) {
if let Some((subject, value)) = fact(&note) {
let k = subject_key(&subject);
facts.retain(|(s, _)| *s != k);
facts.push((k, value));
}
}
if let Some((_, v)) = facts.iter().find(|(s, _)| *s == key) {
return Some(v.clone());
}
let suffix = format!(" {key}");
let mut matches = facts.iter().filter(|(s, _)| s.ends_with(&suffix));
match (matches.next(), matches.next()) {
(Some((_, v)), None) => Some(v.clone()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn save(text: &str) -> String {
match owner_note_request(text) {
Some(NoteRequest::Save(n)) => n,
other => panic!("{text}: {other:?}"),
}
}
#[test]
fn notes_persist_dedupe_and_recall() {
let ws = tempfile::tempdir().unwrap();
fs::write(ws.path().join("MEMORY.md"), "# Previously saved note\n").unwrap();
let note = save("Please remember my test color is teal.");
assert_eq!(note, "my test color is teal");
assert!(!save_owner_note(ws.path(), &note).unwrap().already_saved);
assert!(save_owner_note(ws.path(), &note).unwrap().already_saved);
let file = fs::read_to_string(ws.path().join("memory").join(NOTE_FILE)).unwrap();
assert!(file.starts_with("# Explicit owner notes\n\n- "));
assert_eq!(file.matches("test color is teal").count(), 1);
assert_eq!(fs::read_to_string(ws.path().join("MEMORY.md")).unwrap(), "# Previously saved note\n");
assert_eq!(recall_owner_note(ws.path(), "Which color did I ask you to remember?").as_deref(), Some("teal"));
assert_eq!(recall_owner_note(ws.path(), "What is my test color?").as_deref(), Some("teal"));
save_owner_note(ws.path(), &save("Remember my test color is violet.")).unwrap();
assert_eq!(recall_owner_note(ws.path(), "What is my test color?").as_deref(), Some("violet"));
assert_eq!(recall_owner_note(ws.path(), "What is my shoe size?"), None);
let mode = fs::metadata(ws.path().join("memory").join(NOTE_FILE)).unwrap().permissions();
assert_eq!(std::os::unix::fs::PermissionsExt::mode(&mode) & 0o777, 0o600);
}
#[test]
fn natural_forms_round_trip() {
for (text, question, answer) in [
("Can you please remember that my test color is teal?", "What is my test color?", "teal"),
("Could you please remember my test color is teal?", "What is my test color?", "teal"),
("I want you to remember that my test color is teal.", "What is my test color?", "teal"),
("Remember that my test color is teal and write it down, please.", "What is my test color?", "teal"),
("Please save my test color as teal.", "What is my test color?", "teal"),
("Store my test color is teal.", "What is my test color?", "teal"),
("Write down my test color is teal.", "What is my test color?", "teal"),
("Lembre-se de que minha cor de teste é verde-azulado.", "Qual é a minha cor de teste?", "verde-azulado"),
("Por favor, anote minha cor de teste é verde-azulado e guarde isso na memória.", "Qual é minha cor de teste?", "verde-azulado"),
("Você poderia por favor salvar minha cor de teste como verde-azulado?", "Qual é a minha cor de teste?", "verde-azulado"),
("Por favor, salve a minha cor de teste como verde-azulado.", "Qual é a minha cor de teste?", "verde-azulado"),
("Remember my favorite word is please.", "What is my favorite word?", "please"),
("Remember that my page count is 24.", "What is my page count?", "24"),
("Remember my favorite browser is Firefox.", "What is my favorite browser?", "Firefox"),
("Lembre-se de que minha página favorita é documentação.", "Qual é minha página favorita?", "documentação"),
("Капри, запомни: мой любимый цвет — синий", "Какой мой любимый цвет?", "синий"),
] {
let ws = tempfile::tempdir().unwrap();
save_owner_note(ws.path(), &save(text)).unwrap();
assert_eq!(recall_owner_note(ws.path(), question).as_deref(), Some(answer), "{text}");
assert!(!fs::read_to_string(ws.path().join("memory").join(NOTE_FILE)).unwrap().contains("write it down"));
}
}
#[test]
fn quoted_negated_file_and_compound_requests_are_not_notes() {
for text in [
"Do not remember that my test color is teal.",
"Never save my test color as teal.",
"Não salve minha cor de teste como verde-azulado.",
"\"Remember that my test color is teal.\"",
"Translate: remember that my test color is teal.",
"Can you save documents?",
"Save my report as monthly.pdf.",
"Save my file as C:\\folder\\result.txt.",
"Salve meu documento como resultado.pdf.",
"Record my screen as MP4.",
"Save my work as backup.",
"Registre minha tela como MP4.",
"Save my tab as a PDF.",
"Save my current page as an HTML file.",
"Save my window as an image.",
"Save my bookmarks as backup.",
"Save my selection as plain text.",
"Save my clipboard contents as text.",
"Save my selected text as a PDF.",
"Salve minha aba como PDF.",
"Salve minha guia como PDF.",
"Salve a minha página como PDF.",
"Salve minha janela como imagem.",
"Salve meus favoritos como backup.",
"Salve minha seleção como texto.",
"Salve minha área de transferência como texto.",
"Remember that my test color is teal and write it down, then open Chrome.",
"Save my test color as teal and please open Chrome.",
"Remember that my test color is teal and play Spotify.",
"Anote minha cor de teste é verde-azulado e por favor abra o Chrome.",
"Remember that my test color is teal, then open Chrome.",
] {
assert_eq!(owner_note_request(text), None, "{text}");
}
}
#[test]
fn secrets_are_refused() {
for text in [
"Remember that my password is synthetic-private.",
"Lembre-se de que minha senha é synthetic-private.",
"Salve minha chave de API como synthetic-private.",
"Anote meu código de acesso é synthetic-private.",
"Guarde minha frase de recuperação é synthetic-private.",
"Anote meu token de acesso é synthetic-private.",
"Salve minha chave API como synthetic-private.",
"Salve a minha senha como synthetic-private.",
"Anote meu PIN é synthetic-private.",
"Запомни: мой пароль — synthetic",
"Remember that my key is sk-abcdefghijklmnop.",
] {
assert_eq!(owner_note_request(text), Some(NoteRequest::Refused), "{text}");
}
let ws = tempfile::tempdir().unwrap();
assert!(save_owner_note(ws.path(), "my password is x").is_err());
assert!(!ws.path().join("memory").join(NOTE_FILE).exists());
}
#[test]
fn linked_files_are_rejected() {
let ws = tempfile::tempdir().unwrap();
let outside = ws.path().join("outside.md");
fs::write(&outside, "Unchanged").unwrap();
fs::create_dir(ws.path().join("memory")).unwrap();
fs::hard_link(&outside, ws.path().join("memory").join(NOTE_FILE)).unwrap();
assert!(save_owner_note(ws.path(), "my test color is teal").is_err());
fs::remove_file(ws.path().join("memory").join(NOTE_FILE)).unwrap();
std::os::unix::fs::symlink(&outside, ws.path().join("memory").join(NOTE_FILE)).unwrap();
assert!(save_owner_note(ws.path(), "my test color is teal").is_err());
assert_eq!(fs::read_to_string(&outside).unwrap(), "Unchanged");
let linked = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(ws.path(), linked.path().join("memory")).unwrap();
assert!(save_owner_note(linked.path(), "my test color is teal").is_err());
}
#[test]
fn records_skip_invalid_lines() {
let text = "# Notes\n\n- 2026-11-05 \"my a is b\"\r\n- 2026-11-06 \"Broken\n- x \"y\"\n- 2026-11-07 \"my password is z\"\n";
assert_eq!(records(text), ["my a is b"]);
}
}