diff --git a/app/src/activity.rs b/app/src/activity.rs index 1ec48cf..3d9f68d 100644 --- a/app/src/activity.rs +++ b/app/src/activity.rs @@ -1,6 +1,7 @@ //! What Jarvis did outside its answers (`app/src/admin.spec.md`, "Activity"; `docs/v2/proactive.md` //! 제안 5): chat channel actions and schedule deliveries, by kind, target, who asked and outcome, -//! never their text. Day files `activity/.jsonl` in the data folder, kept `KEEP_DAYS`. +//! never their text. Day files `activity/.jsonl` in the data folder, kept `KEEP_DAYS` +//! (old ones deleted at the start and on the first record of each new day). use std::path::{Path, PathBuf}; use std::sync::Mutex; @@ -32,6 +33,32 @@ pub struct Entry { pub struct Activity { dir: PathBuf, + /// The day old files were last deleted; a record on a later day deletes again. + pruned: Mutex, +} + +/// Recorded instead of an id that is not one (the model may put any text there). +pub const INVALID_ID: &str = "(잘못된 ID)"; +/// Recorded instead of a chat action's error (it may quote what the model wrote). +pub const CHAT_FAILED: &str = "채팅 동작 실패"; +const CHAT_ACTIONS: &[&str] = &["send", "edit", "react", "delete", "pin", "unpin"]; + +/// `s` when it is a Discord id (digits only), else `INVALID_ID`. +pub fn id_or_mark(s: &str) -> String { + if (1..=20).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit()) { s.to_owned() } else { INVALID_ID.into() } +} + +/// The kind of a chat action: `chat.` for the known ones, else `chat.other`. +pub fn chat_kind(action: &str) -> String { + format!("chat.{}", if CHAT_ACTIONS.contains(&action) { action } else { "other" }) +} + +/// The target of a chat action, from ids only. +pub fn chat_target(channel: &str, message: Option<&str>) -> String { + match message { + Some(m) => format!("채널 {} 메시지 {}", id_or_mark(channel), id_or_mark(m)), + None => format!("채널 {}", id_or_mark(channel)), + } } fn day_name(d: NaiveDate) -> String { @@ -41,8 +68,9 @@ fn day_name(d: NaiveDate) -> String { impl Activity { /// The log in `data`; day files older than `KEEP_DAYS` are deleted. pub fn new(data: &Path) -> Self { - let a = Self { dir: data.join("activity") }; - a.prune(Local::now().date_naive()); + let today = Local::now().date_naive(); + let a = Self { dir: data.join("activity"), pruned: Mutex::new(today) }; + a.prune(today); a } @@ -70,6 +98,14 @@ impl Activity { /// Append one entry (a failure to write is logged, never raised: the action itself happened). pub fn record(&self, kind: &str, target: &str, by: Option, ok: bool, note: Option) { let now = Local::now(); + let today = now.date_naive(); + let rolled = { + let mut p = self.pruned.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::replace(&mut *p, today) != today + }; + if rolled { + self.prune(today); + } let e = Entry { at: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, false), kind: kind.into(), target: target.into(), by, ok, note }; let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); @@ -125,6 +161,32 @@ mod tests { assert_eq!(a.recent(1).len(), 1); } + #[test] + fn a_chat_action_is_recorded_by_ids_and_known_words_only() { + // What the model put in the fields never reaches the log, valid or not. + assert_eq!(chat_kind("edit"), "chat.edit"); + assert_eq!(chat_kind("비밀 회의"), "chat.other"); + assert_eq!(chat_target("223456789012345678", Some("323456789012345678")), + "채널 223456789012345678 메시지 323456789012345678"); + let bad = chat_target("일정 채널", Some("비밀 회의")); + assert!(!bad.contains("비밀") && !bad.contains("일정"), "{bad}"); + assert_eq!(chat_target("223456789012345678", None), "채널 223456789012345678"); + assert_eq!(id_or_mark("12a"), INVALID_ID); + } + + #[test] + fn a_long_run_still_deletes_old_day_files_when_the_day_changes() { + let data = crate::datadir::temp_dir("activity-rollover"); + let a = Activity::new(&data); + let old = Local::now().date_naive() - chrono::Duration::days(KEEP_DAYS + 1); + std::fs::create_dir_all(data.join("activity")).unwrap(); + std::fs::write(data.join("activity").join(day_name(old)), "{}\n").unwrap(); + // The app has been running since yesterday. + *a.pruned.lock().unwrap() = Local::now().date_naive() - chrono::Duration::days(1); + a.record("chat.send", "채널 1", None, true, None); + assert!(!data.join("activity").join(day_name(old)).exists()); + } + #[test] fn day_files_past_the_keep_days_are_deleted() { let data = crate::datadir::temp_dir("activity-prune"); diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 7b97764..0cc4854 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -171,9 +171,12 @@ failed. PC control actions join it with M7. Ordinary answers are not recorded. - One JSON line per action in `activity/.jsonl` (the folder is made at the first one): `{at, kind, target, by, ok, note}`. `target` is the channel (and message) id or `예약 `; `by` is who asked, ` ` (the brain's `chat_action` carries the asker, voice_worker.spec.md); - `note` is why it failed. **Never the text** of a message, reminder or answer. -- Day files older than 30 days are deleted when the services or the screen open the log. A failed - write is a warning in the log and never stops the action. + `note` is why a schedule delivery failed, or the fixed `채팅 동작 실패` for a chat action (its error + may quote what the model wrote). **Never the text** of a message, reminder or answer: an id that + is not digits is recorded as `(잘못된 ID)` and an unknown chat action as `chat.other`. +- Day files older than 30 days are deleted when the services or the screen open the log, and on + the first record of each new day while it runs. A failed write is a warning in the log and never + stops the action. - `activity_list` `{limit}` (1-1000, default 200) reads the newest first. ## Secrets (`app/src/secrets.rs`) diff --git a/app/src/discord.rs b/app/src/discord.rs index be2a649..b75cecd 100644 --- a/app/src/discord.rs +++ b/app/src/discord.rs @@ -891,16 +891,16 @@ async fn worker_task(core: std::sync::Weak, mut rx: mpsc::UnboundedReceiv debug_log!("chat", "chat {} {} failed: {e}", a.action, a.id); } if let Some(activity) = core.inner.activity.get() { - let target = match &a.message_id { - Some(m) => format!("채널 {} 메시지 {m}", a.channel), - None => format!("채널 {}", a.channel), - }; + // Ids and known words only: the model may put any text in these fields, + // and errors may quote it. + use crate::activity::{chat_kind, chat_target, id_or_mark, CHAT_FAILED}; + let target = chat_target(&a.channel, a.message_id.as_deref()); let by = a.user.as_ref().map(|u| match u.parse() { - Ok(id) => format!("{u} {}", name_of(&core.inner, id)), - Err(_) => u.clone(), + Ok(id) if id_or_mark(u) == *u => format!("{u} {}", name_of(&core.inner, id)), + _ => id_or_mark(u), }); - activity.record(&format!("chat.{}", a.action), &target, by, result.is_ok(), - result.as_ref().err().cloned()); + activity.record(&chat_kind(&a.action), &target, by, result.is_ok(), + result.is_err().then(|| CHAT_FAILED.to_owned())); } core.inner.worker.chat_action_result(&a.id, result); });