Files
javis_bot/app/src/notes.rs
javis-bot a5bd25b86f feat: personal notes, each person's standing instructions for how Jarvis answers them
A personalNotes tool (add, list, delete the asker's own notes) offered only
with a notes backend. The app keeps the notes in config/notes.json and sends
the asker's with every voice, chat and task reply; the reply engine puts them
in a <person_notes> fence as that person's preferences, which never permit an
action or a tool. The worker's schedule bridge becomes a shared app bridge
for schedule_action and note_action. A 사람별 지침 screen edits and deletes
any note; features.notes turns the tool and the notes off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:10:53 +09:00

194 lines
7.3 KiB
Rust

//! Each person's standing instructions for how Jarvis answers them (`app/src/admin.spec.md`,
//! "Personal notes"; `docs/v2/proactive.md` 제안 4): the store in the data folder, the brain's
//! `note_action`, and the notes sent with each of that person's replies.
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::worker_client::NoteAction;
pub const MAX_TEXT_CHARS: usize = 300;
/// Notes one person may have (the worker takes at most this many with a reply).
pub const PER_PERSON: usize = 20;
static FILE_LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Note {
pub id: u64,
pub user: u64,
pub name: String,
pub text: String,
pub created: i64,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct File {
next_id: u64,
items: Vec<Note>,
}
pub struct Notes {
file: PathBuf,
}
fn clean(text: &str) -> Result<String, String> {
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
if text.is_empty() || text.chars().count() > MAX_TEXT_CHARS {
return Err(format!("a note must be 1-{MAX_TEXT_CHARS} characters"));
}
Ok(text)
}
impl Notes {
pub fn new(data: &Path) -> Self {
Self { file: data.join("config").join("notes.json") }
}
fn load(&self) -> Result<File, String> {
match std::fs::read_to_string(&self.file) {
Ok(t) => serde_json::from_str(&t).map_err(|e| format!("지침 파일을 읽을 수 없습니다: {e}")),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(File::default()),
Err(e) => Err(format!("지침 파일을 읽을 수 없습니다: {e}")),
}
}
fn change<T>(&self, f: impl FnOnce(&mut File) -> Result<T, String>) -> Result<T, String> {
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let mut file = self.load()?;
let out = f(&mut file)?;
let mut text = serde_json::to_string_pretty(&file).unwrap();
text.push('\n');
crate::datadir::write_atomic(&self.file, text.as_bytes()).map_err(|e| format!("지침 파일을 쓸 수 없습니다: {e}"))?;
Ok(out)
}
/// Every note, by person then age.
pub fn all(&self) -> Result<Vec<Note>, String> {
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let mut items = self.load()?.items;
items.sort_by_key(|n| (n.user, n.id));
Ok(items)
}
/// One person's notes, oldest first.
pub fn of(&self, user: u64) -> Result<Vec<Note>, String> {
Ok(self.all()?.into_iter().filter(|n| n.user == user).collect())
}
/// The texts sent with that person's replies; a store that cannot be read sends none.
pub fn texts_of(&self, user: u64) -> Vec<String> {
match self.of(user) {
Ok(n) => n.into_iter().map(|n| n.text).take(PER_PERSON).collect(),
Err(e) => {
crate::warn_log!("conversation", "Warning: {e}");
vec![]
}
}
}
pub fn add(&self, user: u64, name: &str, text: &str, now: i64) -> Result<Note, String> {
let text = clean(text)?;
self.change(|f| {
if f.items.iter().filter(|n| n.user == user).count() >= PER_PERSON {
return Err(format!("at most {PER_PERSON} notes per person; delete one first"));
}
f.next_id += 1;
let n = Note { id: f.next_id, user, name: name.to_owned(), text, created: now };
f.items.push(n.clone());
Ok(n)
})
}
/// Change a note's text (the screen).
pub fn update(&self, id: u64, text: &str) -> Result<Note, String> {
let text = clean(text)?;
self.change(|f| {
let n = f.items.iter_mut().find(|n| n.id == id).ok_or("no such note")?;
n.text = text;
Ok(n.clone())
})
}
/// Delete a note; with `user`, only one of theirs.
pub fn delete(&self, id: u64, user: Option<u64>) -> Result<Note, String> {
self.change(|f| {
let pos = f.items.iter().position(|n| n.id == id && user.is_none_or(|u| u == n.user))
.ok_or_else(|| "no such note of this person".to_string())?;
Ok(f.items.remove(pos))
})
}
}
fn brain_item(n: &Note) -> Value {
json!({"id": n.id.to_string(), "text": n.text})
}
/// Do what the brain's personalNotes tool asked for the person in `a.user` (named `name`).
pub fn act(notes: &Notes, a: &NoteAction, name: &str, now: i64) -> Result<Value, String> {
let user: u64 = a.user.parse().map_err(|_| "bad user id".to_string())?;
match a.action.as_str() {
"list" => Ok(json!({"items": notes.of(user)?.iter().map(brain_item).collect::<Vec<_>>()})),
"add" => {
let n = notes.add(user, name, a.text.as_deref().unwrap_or(""), now)?;
crate::info_log!("conversation", "note {} added by {user}", n.id);
Ok(json!({"item": brain_item(&n)}))
}
"delete" => {
let id: u64 = a.note.as_deref().and_then(|s| s.trim().parse().ok()).ok_or("delete needs the note's id")?;
Ok(json!({"item": brain_item(&notes.delete(id, Some(user))?)}))
}
other => Err(format!("unknown note action {other}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn notes() -> Notes {
Notes::new(&crate::datadir::temp_dir("notes"))
}
fn action(action: &str, user: &str, extra: Value) -> NoteAction {
let mut v = json!({"id": "x", "action": action, "user": user, "via": "voice"});
v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
serde_json::from_value(v).unwrap()
}
#[test]
fn a_persons_notes_are_theirs_alone() {
let n = notes();
let added = act(&n, &action("add", "1", json!({"text": " 반말로 해 "})), "가", 10).unwrap();
assert_eq!(added["item"]["text"], "반말로 해");
act(&n, &action("add", "2", json!({"text": "섭씨로"})), "나", 10).unwrap();
assert_eq!(n.texts_of(1), vec!["반말로 해".to_string()]);
assert!(!act(&n, &action("list", "2", json!({})), "나", 10).unwrap().to_string().contains("반말"));
let id = added["item"]["id"].as_str().unwrap().to_owned();
assert!(act(&n, &action("delete", "2", json!({"note": id})), "나", 10).is_err());
assert!(act(&n, &action("delete", "1", json!({"note": id})), "가", 10).is_ok());
assert!(n.texts_of(1).is_empty());
}
#[test]
fn bad_notes_and_too_many_are_refused_and_the_screen_can_edit_any() {
let n = notes();
assert!(n.add(1, "가", " ", 0).is_err());
assert!(n.add(1, "가", &"x".repeat(MAX_TEXT_CHARS + 1), 0).is_err());
for i in 0..PER_PERSON {
n.add(1, "가", &format!("지침 {i}"), 0).unwrap();
}
assert!(n.add(1, "가", "하나 더", 0).is_err());
let first = n.of(1).unwrap()[0].clone();
assert_eq!(n.update(first.id, "고친 지침").unwrap().text, "고친 지침");
assert!(n.update(first.id, "").is_err());
assert_eq!(n.texts_of(1)[0], "고친 지침");
assert_eq!(n.delete(first.id, None).unwrap().id, first.id);
}
}