From b94e9dc112e360c31868fb4757d02935adc4519f Mon Sep 17 00:00:00 2001 From: javis-bot Date: Fri, 13 Nov 2026 21:29:49 +0900 Subject: [PATCH] feat(app): background collection frame for sites, search words and RSS feeds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Targets (none by default), interval and keep days on a new 백그라운드 수집 screen with the results; the worker collects on its own thread through the web search's address check and writes only to the data folder's collect/ (logs carry target names and counts). Co-Authored-By: Claude Opus 5.5 --- app/src/admin.spec.md | 37 +++- app/src/admin_api.rs | 21 +++ app/src/collect.rs | 131 ++++++++++++++ app/src/features.rs | 4 +- app/src/lib.rs | 1 + app/src/services.rs | 6 + app/src/settings.rs | 134 +++++++++++++- app/src/settings_edit.rs | 10 +- app/ui/app.js | 67 ++++++- app/ui/index.html | 1 + docs/v2/roadmap.md | 2 +- src/voice_worker/__main__.py | 9 + src/voice_worker/collect.py | 241 ++++++++++++++++++++++++++ src/voice_worker/voice_worker.spec.md | 23 +++ tests/test_voice_worker_collect.py | 188 ++++++++++++++++++++ 15 files changed, 861 insertions(+), 14 deletions(-) create mode 100644 app/src/collect.rs create mode 100644 src/voice_worker/collect.py create mode 100644 tests/test_voice_worker_collect.py diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 3f6e70c..8922f00 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -38,9 +38,9 @@ that is not absolute, or is a file, is refused with a message. `config/settings.json` keeps the format of `discord_core.spec.md` and `conversation.spec.md`. - `fields()` describes every key the screens edit: its dotted path (`call.mode`), screen - (`bot`, `channels`, `chat`, `memory`, `model`, `features`), kind (bool, integer with a range, number with a + (`bot`, `channels`, `chat`, `memory`, `model`, `features`, `collect`), kind (bool, integer with a range, number with a range, text, text list, choice with its values, Discord ID, Discord ID list, ID to number map, - chat channel list, MCP server list, free object), its default and a Korean label. The screens are built from this + chat channel list, MCP server list, collection target list, free object), its default and a Korean label. The screens are built from this list, so a key is added in one place. - `view(dir)` returns every field's current value: the file's value, or the default when the file does not set it. A file that does not parse is reported, not overwritten. @@ -59,10 +59,11 @@ that is not absolute, or is a file, is refused with a message. manages the MCP servers it connects. - `features` (new section): `weather` (`getWeather`), `webSearch` (`webSearch`, `fetchWebPage`) and - `meals` (`logMeal`, `fetchMeals`, `deleteMeal`), each on by default. The tools of a feature that + `meals` (`logMeal`, `fetchMeals`, `deleteMeal`), each on by default; `collect` (background + collection, below; no brain tool), also on by default. The tools of a feature that is off go into the brain's `disabled_tools`: they are neither offered nor run (`voice_worker.spec.md`, "Tools"). The other features of the 기능 screen (browser control, PC - control, screen viewing, background collection) come with their milestones (M6, M7). + control, screen viewing) come with their milestones (M6, M7). - `mcpServers` (new list): each `{name, command, args, env, enabled}`. `name` is 1-32 letters, digits, `-` or `_` without `__` (the brain names a server's tools `__`), not listed twice; `command` is not empty; `args` a list of strings; `env` the names of the environment @@ -79,6 +80,26 @@ manages the MCP servers it connects. also without debug logging. MCP servers are programs the PC runs; the screen says to add only trusted ones. +## Background collection (`app/src/collect.rs`) + +`docs/v2/desktop-app.md`, "백그라운드 수집", and `docs/v2/pc-features.md`. The frame for collecting +sites, search words and RSS feeds on a schedule; there are **no targets by default**. + +- `collect` (new section): `keepDays` (1-365, default 30) and `targets` (default empty), each + `{name, kind, value, everyMinutes, enabled}`. `name` is 1-32 letters, digits, `-` or `_` (any + script; it names the target's folder, so not a Windows device name like `con` or `nul`), not + listed twice; `kind` is `site`, `search` or `rss`; `value` is an http(s) address for `site` and + `rss` (at most 2,000 characters) and the words for `search` (1-200 characters); + `everyMinutes` 15-10080 (default 60); `enabled` on by default. +- On start, with `features.collect` on and at least one enabled target, the app writes + `config/collect.json` (the folder `collect/`, `keepDays` and the enabled targets) and passes it to + the worker as `JARVIS_COLLECT_PATH`; otherwise it removes that file and passes nothing. The worker + collects while the services run (`voice_worker.spec.md`, "Background collection"); results stay + in `collect//.jsonl` in the data folder only. +- `results(data, target, limit)` reads them newest first (the newest day file first, its last line + first), each item with its `target`; a name that is not a valid target name is refused, so no + other folder is read. Lines that do not parse are skipped. + ## Secrets (`app/src/secrets.rs`) `config/secrets.dat` holds a JSON object of named secrets (`discordToken`, the MCP servers' @@ -284,6 +305,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run; `sync` with the chat channels sent to Discord (below) | | `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start | | `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) | +| `collect_results` `{target, limit}` | collected items newest first (`target` null: every target; `limit` 1-500, default 100) | | `mcp_env_status` / `mcp_env_set` `{server, name, value}` | which MCP environment values are stored (`{server: {NAME: bool}}`, never the values) / store one (an empty value removes it); only for a saved server and name | | `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it | | `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back | @@ -309,13 +331,16 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A Strata's last line, and stop in the header; the header with start, restart and stop is rebuilt only when the state changes, so a click is never lost to the refresh. Every screen change starts a new generation: an answer that arrives after the user moved to another screen is dropped. -- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델, 기능): built from `settings_fields`; only +- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델, 기능, 백그라운드 수집): built from `settings_fields`; only changed fields are sent; the server and voice channel are pickers (choosing another server clears the voice channel and lists only that server's channels); the chat channels are a table with their switches; the bot screen also changes the token; the 기능 screen has the feature switches and one card per MCP server (name, command, arguments and environment variable names one per line, on/off, delete), and for a saved server a password box per environment variable - that stores its value on its own. + that stores its value on its own. The 백그라운드 수집 screen has the targets (a table: name, kind, + address or words, interval in minutes, on/off, delete), the keep days, and the results (the + newest 100, filtered by target, each with its time, title, link and the start of its text shown + as plain text). - **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류 복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days. diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index cb74928..c2fe109 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -281,6 +281,11 @@ impl AdminApi { Ok(json!({"set": !value.is_empty(), "restartNeeded": self.controller()?.state() == crate::control::State::Running})) } + "collect_results" => { + let target = args.get("target").and_then(Value::as_str).filter(|t| !t.is_empty()); + let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(100).clamp(1, 500) as usize; + Ok(json!(crate::collect::results(self.dir()?.path(), target, limit)?)) + } "channel_sync_status" => Ok(Value::Object(self.syncer()?.status().into_iter() .map(|(id, s)| (id.to_string(), json!(s))).collect())), "discord_channel_info" => { @@ -392,6 +397,22 @@ mod tests { assert!(a.call("nope", json!({})).await.is_err()); } + #[tokio::test] + async fn collection_targets_are_saved_and_their_results_read_from_the_data_folder() { + let (a, base) = api("api-collect"); + let data = base.join("d"); + a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap(); + let targets = json!([{"name": "뉴스", "kind": "rss", "value": "https://feed.example/rss", "everyMinutes": 30}]); + a.call("settings_apply", json!({"changes": {"collect.targets": targets, "collect.keepDays": 7}})).await.unwrap(); + assert_eq!(a.call("settings_view", json!({})).await.unwrap()["collect.targets"], targets); + let day = data.join("collect").join("뉴스"); + std::fs::create_dir_all(&day).unwrap(); + std::fs::write(day.join("2026-11-13.jsonl"), "{\"at\": \"2026-11-13T09:00:00+09:00\", \"title\": \"t\"}\n").unwrap(); + let r = a.call("collect_results", json!({"target": null})).await.unwrap(); + assert_eq!(r, json!([{"at": "2026-11-13T09:00:00+09:00", "title": "t", "target": "뉴스"}])); + assert!(a.call("collect_results", json!({"target": "../config"})).await.is_err()); + } + #[tokio::test] async fn mcp_values_are_stored_encrypted_shown_only_as_set_masked_in_logs_and_go_with_their_server() { let (a, base) = api("api-mcp"); diff --git a/app/src/collect.rs b/app/src/collect.rs new file mode 100644 index 0000000..1b9ea02 --- /dev/null +++ b/app/src/collect.rs @@ -0,0 +1,131 @@ +//! Background collection (`app/src/admin.spec.md`, "Background collection"): the worker's +//! collection file, and the collected items for the 백그라운드 수집 screen. + +use std::path::{Path, PathBuf}; + +use serde_json::{json, Value}; + +use crate::settings::{valid_collect_name, Settings}; + +/// The worker's environment variable with the collection file (`voice_worker/collect.py`). +pub const COLLECT_ENV_VAR: &str = "JARVIS_COLLECT_PATH"; + +/// Write `config/collect.json` with the enabled targets and return it; with the feature off or no +/// enabled target, remove it and return None (the worker then collects nothing). +pub fn write_config(data: &Path, settings: &Settings) -> std::io::Result> { + let file = data.join("config").join("collect.json"); + let targets: Vec = settings.collect.targets.iter().filter(|t| t.enabled) + .map(|t| json!({"name": t.name, "kind": t.kind, "value": t.value, "everyMinutes": t.every_minutes})) + .collect(); + if !settings.features.collect || targets.is_empty() { + match std::fs::remove_file(&file) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), + _ => return Ok(None), + } + } + let cfg = json!({"dir": data.join("collect").to_string_lossy(), "keepDays": settings.collect.keep_days, + "targets": targets}); + let mut text = serde_json::to_string_pretty(&cfg).unwrap(); + text.push('\n'); + crate::datadir::write_atomic(&file, text.as_bytes())?; + Ok(Some(file)) +} + +/// The day files of one target folder, newest first. +fn day_files(folder: &Path) -> Vec { + let mut files: Vec = std::fs::read_dir(folder).into_iter().flatten().flatten().map(|e| e.path()) + .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.len() == 16 && n.ends_with(".jsonl"))) + .collect(); + files.sort(); + files.reverse(); + files +} + +/// Collected items newest first, each with its `target`; `target` None reads every target folder. +pub fn results(data: &Path, target: Option<&str>, limit: usize) -> Result, String> { + let root = data.join("collect"); + let names: Vec = match target { + Some(t) if !valid_collect_name(t) => return Err(format!("not a collection target name: {t}")), + Some(t) => vec![t.to_owned()], + None => std::fs::read_dir(&root).into_iter().flatten().flatten() + .filter(|e| e.path().is_dir()) + .filter_map(|e| e.file_name().to_str().map(str::to_owned)) + .filter(|n| valid_collect_name(n)) + .collect(), + }; + let mut out: Vec = Vec::new(); + for name in names { + let mut n = 0; + 'files: for f in day_files(&root.join(&name)) { + let text = std::fs::read_to_string(&f).unwrap_or_default(); + for line in text.lines().rev() { + if let Ok(Value::Object(mut item)) = serde_json::from_str::(line) { + item.insert("target".into(), Value::String(name.clone())); + out.push(Value::Object(item)); + n += 1; + if n == limit { + break 'files; + } + } + } + } + } + // `at` is the local time with its offset in one format, so the text order is the time order. + out.sort_by(|a, b| b["at"].as_str().unwrap_or("").cmp(a["at"].as_str().unwrap_or(""))); + out.truncate(limit); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::datadir::temp_dir; + use crate::settings::parse_settings; + + fn settings(v: Value) -> Settings { + parse_settings(&v).unwrap() + } + + #[test] + fn the_worker_gets_only_enabled_targets_and_nothing_without_them() { + let data = temp_dir("collect-cfg"); + let s = settings(json!({"collect": {"keepDays": 3, "targets": [ + {"name": "a", "kind": "rss", "value": "https://a.example/rss", "everyMinutes": 30}, + {"name": "b", "kind": "site", "value": "https://b.example", "enabled": false}]}})); + let file = write_config(&data, &s).unwrap().unwrap(); + let cfg: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + assert_eq!(cfg, json!({"dir": data.join("collect").to_string_lossy(), "keepDays": 3, + "targets": [{"name": "a", "kind": "rss", "value": "https://a.example/rss", "everyMinutes": 30}]})); + + let mut off = s.clone(); + off.features.collect = false; + assert_eq!(write_config(&data, &off).unwrap(), None); + assert!(!file.exists()); + write_config(&data, &s).unwrap(); + assert_eq!(write_config(&data, &settings(json!({}))).unwrap(), None); + assert!(!file.exists()); + } + + #[test] + fn results_come_newest_first_with_their_target_and_only_from_target_folders() { + let data = temp_dir("collect-res"); + let put = |name: &str, day: &str, lines: &[&str]| { + let d = data.join("collect").join(name); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join(format!("{day}.jsonl")), lines.join("\n") + "\n").unwrap(); + }; + put("뉴스", "2026-11-12", &[r#"{"at": "2026-11-12T09:00:00+09:00", "title": "old"}"#]); + put("뉴스", "2026-11-13", &[r#"{"at": "2026-11-13T09:00:00+09:00", "title": "n1"}"#, "not json", + r#"{"at": "2026-11-13T10:00:00+09:00", "title": "n2"}"#]); + put("site", "2026-11-13", &[r#"{"at": "2026-11-13T09:30:00+09:00", "title": "s1"}"#]); + std::fs::write(data.join("collect").join("뉴스").join("state.json"), r#"{"at": "9999"}"#).unwrap(); + let titles = |v: Vec| v.iter().map(|i| format!("{}:{}", i["target"].as_str().unwrap(), + i["title"].as_str().unwrap())).collect::>(); + assert_eq!(titles(results(&data, None, 100).unwrap()), ["뉴스:n2", "site:s1", "뉴스:n1", "뉴스:old"]); + assert_eq!(titles(results(&data, Some("뉴스"), 2).unwrap()), ["뉴스:n2", "뉴스:n1"]); + assert_eq!(titles(results(&data, None, 2).unwrap()), ["뉴스:n2", "site:s1"]); + assert!(results(&data, Some("missing"), 10).unwrap().is_empty()); + assert!(results(&data, Some(".."), 10).is_err()); + assert!(results(&data, Some("../config"), 10).is_err()); + } +} diff --git a/app/src/features.rs b/app/src/features.rs index 3d2599f..5d61406 100644 --- a/app/src/features.rs +++ b/app/src/features.rs @@ -100,9 +100,9 @@ mod tests { #[test] fn features_that_are_off_turn_their_tools_off() { - let all_on = FeatureSettings { weather: true, web_search: true, meals: true }; + let all_on = FeatureSettings { weather: true, web_search: true, meals: true, collect: true }; assert!(disabled_tools(&all_on).is_empty()); - let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false }); + let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false, collect: false }); assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal"]); } diff --git a/app/src/lib.rs b/app/src/lib.rs index 9e0a3d6..b341fcb 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -5,6 +5,7 @@ pub mod admin_api; pub mod calls; pub mod channel_sync; pub mod chat; +pub mod collect; pub mod control; pub mod conversation; pub mod dashboard; diff --git a/app/src/services.rs b/app/src/services.rs index b8b22f3..043d734 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -70,6 +70,12 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result { wopts.env.insert(crate::collect::COLLECT_ENV_VAR.into(), f.to_string_lossy().into_owned()); } + Ok(None) => {} + Err(e) => return Err(after_llm_stop(&llm, format!("could not write the collection settings: {e}")).await.into()), + } let worker_process = match WorkerProcess::new(wopts) { Ok(p) => p, Err(e) => return Err(after_llm_stop(&llm, e.to_string()).await.into()), diff --git a/app/src/settings.rs b/app/src/settings.rs index 5f258c5..4e8d64f 100644 --- a/app/src/settings.rs +++ b/app/src/settings.rs @@ -91,6 +91,25 @@ pub struct FeatureSettings { pub weather: bool, pub web_search: bool, pub meals: bool, + /// Background collection (admin.spec.md, "Background collection"). + pub collect: bool, +} + +/// Background collection (admin.spec.md, "Background collection"); no targets by default. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CollectSettings { + pub keep_days: u32, + pub targets: Vec, +} + +/// One thing to collect: `kind` is `site`, `search` or `rss`; `value` its address or words. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CollectTarget { + pub name: String, + pub kind: String, + pub value: String, + pub every_minutes: u32, + pub enabled: bool, } /// An MCP server the brain starts (stdio). The values of `env` are in the secrets, never here. @@ -121,6 +140,7 @@ pub struct Settings { pub llm: LlmSettings, pub features: FeatureSettings, pub mcp_servers: Vec, + pub collect: CollectSettings, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -164,8 +184,9 @@ impl Default for Settings { response: PolicySettings::default(), memory: Map::new(), llm: LlmSettings { url: None, port: 8080, context: 32768 }, - features: FeatureSettings { weather: true, web_search: true, meals: true }, + features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true }, mcp_servers: vec![], + collect: CollectSettings { keep_days: 30, targets: vec![] }, } } } @@ -483,12 +504,76 @@ pub fn parse_settings(raw: &Value) -> Result { weather: get_bool(f, "weather", "features", d.features.weather)?, web_search: get_bool(f, "webSearch", "features", d.features.web_search)?, meals: get_bool(f, "meals", "features", d.features.meals)?, + collect: get_bool(f, "collect", "features", d.features.collect)?, } }, mcp_servers: parse_mcp_servers(raw)?, + collect: parse_collect(raw, &d.collect)?, }) } +/// A collection target's name: 1-32 letters, digits, `-` or `_` in any script. It names the +/// target's folder, so a Windows device name (`con`, `nul`, `com1`, ...) is refused. +pub fn valid_collect_name(s: &str) -> bool { + let n = s.chars().count(); + let lower = s.to_ascii_lowercase(); + let device = ["con", "prn", "aux", "nul"].contains(&lower.as_str()) + || (lower.len() == 4 && (lower.starts_with("com") || lower.starts_with("lpt")) + && lower.as_bytes()[3].is_ascii_digit()); + (1..=32).contains(&n) && s.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') && !device +} + +fn get_uint(m: Option<&Map>, key: &str, path: &str, default: u32, min: u32, max: u32) + -> Result { + match m.and_then(|m| m.get(key)) { + None => Ok(default), + Some(v) => match v.as_u64() { + Some(n) if (min as u64..=max as u64).contains(&n) => Ok(n as u32), + _ => err(format!("{path}.{key} must be an integer {min}-{max}")), + }, + } +} + +fn parse_collect(raw: &Map, d: &CollectSettings) -> Result { + let c = section(raw, "collect")?; + let keep_days = get_uint(c, "keepDays", "collect", d.keep_days, 1, 365)?; + let list = match c.and_then(|m| m.get("targets")) { + None => return Ok(CollectSettings { keep_days, targets: vec![] }), + Some(Value::Array(a)) => a, + Some(_) => return err("collect.targets must be a list"), + }; + let mut targets: Vec = Vec::new(); + for (i, v) in list.iter().enumerate() { + let path = format!("collect.targets[{i}]"); + let Value::Object(m) = v else { return err(format!("{path} must be an object")) }; + let name = get_str(Some(m), "name", &path, "")?.trim().to_owned(); + if !valid_collect_name(&name) { + return err(format!("{path}.name must be 1-32 letters, digits, - or _ (not a device name like con)")); + } + if targets.iter().any(|t| t.name == name) { + return err(format!("{path}.name is listed twice")); + } + let kind = get_str(Some(m), "kind", &path, "")?; + let value = get_str(Some(m), "value", &path, "")?.trim().to_owned(); + let ok = match kind.as_str() { + "site" | "rss" => (value.starts_with("http://") || value.starts_with("https://")) && value.len() <= 2000, + "search" => (1..=200).contains(&value.chars().count()), + _ => return err(format!("{path}.kind must be site, search or rss")), + }; + if !ok { + return err(format!("{path}.value must be an http(s) address (site, rss) or 1-200 characters of words (search)")); + } + targets.push(CollectTarget { + name, + kind, + value, + every_minutes: get_uint(Some(m), "everyMinutes", &path, 60, 15, 10080)?, + enabled: get_bool(Some(m), "enabled", &path, true)?, + }); + } + Ok(CollectSettings { keep_days, targets }) +} + /// An MCP server name: 1-32 letters, digits, `-` or `_`, without `__` (the brain names a server's /// tools `__`). fn valid_mcp_name(s: &str) -> bool { @@ -718,13 +803,13 @@ mod tests { #[test] fn features_and_mcp_servers_are_read_and_checked() { let s = parse_settings(&json!({})); - assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true }); + assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true }); let s = parse_settings(&json!({ "features": {"weather": false, "meals": false}, "mcpServers": [{"name": "brave", "command": "npx", "args": ["-y", "brave"], "env": ["BRAVE_API_KEY", " "]}, {"name": "time-2", "command": "uvx", "enabled": false}] })).unwrap(); - assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false }); + assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true }); assert_eq!(s.mcp_servers, vec![ McpServerSettings { name: "brave".into(), command: "npx".into(), args: vec!["-y".into(), "brave".into()], env: vec!["BRAVE_API_KEY".into()], enabled: true }, @@ -747,6 +832,49 @@ mod tests { } } + #[test] + fn collection_targets_are_read_and_checked() { + let s = parse_settings(&json!({})).unwrap(); + assert_eq!(s.collect, CollectSettings { keep_days: 30, targets: vec![] }); + let s = parse_settings(&json!({"features": {"collect": false}, "collect": {"keepDays": 7, "targets": [ + {"name": "뉴스_1", "kind": "rss", "value": " https://feed.example/rss "}, + {"name": "rust", "kind": "search", "value": "rust release", "everyMinutes": 1440, "enabled": false}]}})).unwrap(); + assert!(!s.features.collect); + assert_eq!(s.collect, CollectSettings { keep_days: 7, targets: vec![ + CollectTarget { name: "뉴스_1".into(), kind: "rss".into(), value: "https://feed.example/rss".into(), + every_minutes: 60, enabled: true }, + CollectTarget { name: "rust".into(), kind: "search".into(), value: "rust release".into(), + every_minutes: 1440, enabled: false }, + ]}); + let t = |extra: Value| { + let mut m = json!({"name": "a", "kind": "site", "value": "https://a.example"}); + m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + json!({"collect": {"targets": [m]}}) + }; + let cases = [ + (json!({"collect": {"keepDays": 0}}), "collect.keepDays"), + (json!({"collect": {"keepDays": 366}}), "collect.keepDays"), + (json!({"collect": {"targets": {}}}), "collect.targets"), + (t(json!({"name": ""})), "collect.targets[0].name"), + (t(json!({"name": "a/b"})), "collect.targets[0].name"), + (t(json!({"name": "../x"})), "collect.targets[0].name"), + (t(json!({"name": "CON"})), "collect.targets[0].name"), + (t(json!({"name": "com1"})), "collect.targets[0].name"), + (t(json!({"kind": "video"})), "collect.targets[0].kind"), + (t(json!({"value": "ftp://a.example"})), "collect.targets[0].value"), + (t(json!({"kind": "search", "value": " "})), "collect.targets[0].value"), + (t(json!({"everyMinutes": 14})), "collect.targets[0].everyMinutes"), + (t(json!({"everyMinutes": 10081})), "collect.targets[0].everyMinutes"), + (json!({"collect": {"targets": [{"name": "a", "kind": "rss", "value": "https://a"}, + {"name": "a", "kind": "rss", "value": "https://b"}]}}), "collect.targets[1].name"), + ]; + for (raw, key) in cases { + let e = parse_settings(&raw).unwrap_err(); + assert!(e.0.contains(key), "{raw} -> {e}"); + } + assert!(valid_collect_name("console") && valid_collect_name("com") && valid_collect_name("날씨-서울")); + } + #[test] fn null_ids_clear_them() { let s = parse_settings(&json!({"discord": {"guildId": null, "voiceChannelId": null}})).unwrap(); diff --git a/app/src/settings_edit.rs b/app/src/settings_edit.rs index 9a26830..d5d3d48 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -20,6 +20,7 @@ pub enum Screen { Memory, Model, Features, + Collect, } #[derive(Debug, Clone, PartialEq, serde::Serialize)] @@ -45,6 +46,8 @@ pub enum Kind { ChatChannels, /// The MCP servers (their own rules are checked by `parse_settings`; values are secrets). McpServers, + /// The background collection targets (their own rules are checked by `parse_settings`). + CollectTargets, } #[derive(Debug, Clone, PartialEq, serde::Serialize)] @@ -119,7 +122,11 @@ pub fn fields() -> Vec { f("features.weather", Features, Bool, json!(true), "날씨"), f("features.webSearch", Features, Bool, json!(true), "웹 검색"), f("features.meals", Features, Bool, json!(true), "식단 기록"), + f("features.collect", Features, Bool, json!(true), "백그라운드 수집"), f("mcpServers", Features, McpServers, json!([]), "MCP 서버"), + // Background collection (admin.spec.md, "Background collection"): no targets by default. + f("collect.targets", Collect, CollectTargets, json!([]), "수집 대상"), + f("collect.keepDays", Collect, Int { min: 1, max: 365 }, json!(30), "보관 기간(일)"), ] } @@ -209,7 +216,7 @@ fn check(field: &Field, v: &Value) -> Result<(), String> { Kind::IdList => v.as_array().is_some_and(|a| a.iter().all(is_id)), Kind::IdNumberMap => v.as_object().is_some_and(|m| m.iter() .all(|(k, n)| is_id(&Value::String(k.clone())) && n.as_i64().is_some())), - Kind::ChatChannels | Kind::McpServers => v.is_array(), + Kind::ChatChannels | Kind::McpServers | Kind::CollectTargets => v.is_array(), }; if ok { Ok(()) } else { Err(format!("{} has a value it cannot take", field.path)) } } @@ -319,6 +326,7 @@ mod tests { (json!({"discord.commandName": "Big Name"}), "discord.commandName"), // A chat channel without a valid ID. (json!({"chatChannels": [{"id": "1"}]}), "chatChannels[0].id"), + (json!({"collect.targets": [{"name": "nul", "kind": "rss", "value": "https://a"}]}), "collect.targets[0].name"), ] { let e = apply(&p, &changes(c.clone()).into_iter().chain([("call.earcon".into(), json!(false))]).collect()) .unwrap_err(); diff --git a/app/ui/app.js b/app/ui/app.js index cd76842..d03e34a 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -123,6 +123,8 @@ function editor(f, value) { return chatChannelsEditor(f, value); case "mcpServers": return mcpServersEditor(f, value); + case "collectTargets": + return collectTargetsEditor(f, value); default: el = h("span", { class: "muted" }, JSON.stringify(value)); read = () => value; @@ -243,6 +245,67 @@ function mcpServersEditor(f, value) { list, h("button", { class: "btn", onclick: () => addServer() }, "서버 추가")), read, wide: true }; } +// The background collection targets: one row each (admin.spec.md, "Background collection"). +const KIND = { site: "사이트", search: "검색어", rss: "RSS" }; +function collectTargetsEditor(f, value) { + const body = h("tbody"); + const addRow = (t = {}) => { + const kind = h("select", { "data-k": "kind" }, + Object.entries(KIND).map(([k, label]) => h("option", { value: k, selected: (t.kind ?? "site") === k }, label))); + const val = h("input", { type: "text", value: t.value ?? "", "data-k": "value" }); + const hint = () => (val.placeholder = kind.value === "search" ? "검색어" : "https:// 주소"); + kind.addEventListener("change", hint); + hint(); + const on = h("input", { type: "checkbox", "data-k": "enabled" }); + on.checked = t.enabled ?? true; + const tr = h("tr", {}, + h("td", {}, h("input", { type: "text", value: t.name ?? "", placeholder: "이름 (글자, 숫자, - _)", "data-k": "name" })), + h("td", {}, kind), h("td", {}, val), + h("td", {}, h("input", { type: "number", min: 15, max: 10080, value: t.everyMinutes ?? 60, "data-k": "everyMinutes" })), + h("td", {}, on), + h("td", {}, h("button", { class: "btn", onclick: () => tr.remove() }, "삭제"))); + body.append(tr); + }; + (value || []).forEach(addRow); + const read = () => [...body.rows].map((tr) => { + const k = (key) => tr.querySelector(`[data-k="${key}"]`); + const every = Number(k("everyMinutes").value); + if (!Number.isInteger(every)) throw new Error(`${f.label}: 주기는 분 단위 정수`); + return { name: k("name").value.trim(), kind: k("kind").value, value: k("value").value.trim(), + everyMinutes: every, enabled: k("enabled").checked }; + }); + const table = h("table", {}, h("thead", {}, h("tr", {}, ["이름", "종류", "주소 또는 검색어", "주기(분)", "켜기", ""] + .map((x) => h("th", {}, x)))), body); + return { el: h("div", {}, h("div", { class: "hint" }, "기본 수집 대상은 없습니다. 모은 내용은 데이터 폴더의 collect 폴더에만 저장됩니다."), + table, h("button", { class: "btn", onclick: () => addRow() }, "대상 추가")), read, wide: true }; +} + +/** The newest collected items, filtered by target; web content, so shown only as plain text. */ +async function collectResults() { + const pick = h("select", {}, h("option", { value: "" }, "모든 대상")); + const list = h("div"); + const load = async () => { + try { + const items = await api("collect_results", { target: pick.value || null, limit: 100 }); + if (!pick.value) { + for (const name of new Set(items.map((i) => i.target))) + if (![...pick.options].some((o) => o.value === name)) pick.append(h("option", { value: name }, name)); + } + list.replaceChildren(items.length ? h("table", {}, h("tbody", {}, items.map((i) => h("tr", {}, + h("td", { class: "small muted" }, (i.at || "").replace("T", " ").slice(0, 16)), + h("td", { class: "small" }, i.target), + h("td", {}, h("div", {}, i.title || i.url || ""), + i.url ? h("div", { class: "small muted" }, i.url) : null, + i.text ? h("div", { class: "small" }, i.text.length > 200 ? i.text.slice(0, 200) + "…" : i.text) : null))))) + : h("div", { class: "muted" }, "아직 모은 내용이 없습니다.")); + } catch (e) { fail(e); } + }; + pick.addEventListener("change", load); + load(); + return h("div", { class: "card" }, h("h2", {}, "수집 결과"), + h("div", { class: "field" }, h("label", {}, "대상"), pick, h("button", { class: "btn", onclick: load }, "새로 고침")), list); +} + async function settingsScreen(screen, title, extra) { const [all, view] = await Promise.all([fields(), api("settings_view")]); const list = all.filter((f) => f.screen === screen); @@ -476,9 +539,11 @@ async function show(name) { try { if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; } if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; } - const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능" }; + const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능", + collect: "백그라운드 수집" }; const extra = name === "bot" ? await tokenCard() : null; const view = await settingsScreen(name, titles[name], extra); + if (name === "collect") view.append(await collectResults()); if (my === gen) screen.replaceChildren(view); } catch (e) { fail(e); } } diff --git a/app/ui/index.html b/app/ui/index.html index 865e681..a9586bc 100644 --- a/app/ui/index.html +++ b/app/ui/index.html @@ -18,6 +18,7 @@ +
diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 7781203..b9b01e9 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -10,7 +10,7 @@ | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 이 전체 실행의 날씨 실패 1개는 장소를 말하지 않은 "what's the weather this week"에 자동으로 잡힌 위치(`Hackney, England, UK`)를 인자로 옮겨 적은 것으로, 그 뒤 날씨 도구와 지시문을 사용자가 말한 위치만 넣도록 좁혀 고침. 고친 뒤 날씨 평가 12개를 따로 3번 돌려 36번 중 34번 통과(이 평가는 3번 모두 통과, 실패 2번은 날씨 한 번 부르기 평가가 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 전체 실행의 나머지 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트. 1단계 완료(2026-11-11): 앱의 호출 판정 `app/src/calls.rs`와 응답 정책 `app/src/policy.rs`(스펙 [conversation.spec.md](../../app/src/conversation.spec.md)), 설정 `call`·`response`. 비슷한 발음은 유니코드 NFKD로 한글을 자모로 나눠 편집 거리로 판단(기본 0.2: "자비즈"는 호출, "서비스"는 아님). 정책은 말이 끝난 시각 순서, 먼저 끝난 말의 전사 대기(최대 0.8초), 끼어들기, 놓친 요청 사유를 가짜 시각으로 시험함. 2단계 완료(2026-11-11): 대화 루프 `app/src/conversation.rs`가 최종 전사를 호출 판정과 응답 정책에 넣고, 정책의 결정대로 두뇌에 답을 요청해(`reply`, 답은 워커가 같은 id로 읽음) 앱의 재생 대기열에서 재생, 끼어들 때는 그 답만 멈춤, "자비스 멈춰"는 모든 말을 멈춤, 놓친 요청은 글 없이 최근 100개를 남김. 두뇌의 두 판정 `src/voice_worker/judges.py`(봇에게 하는 말인지, 중요도 순위)는 답과 따로 돌아 기다리지 않음. 평가 `evals/test_voice_judges.py` 12개를 qwen2.5:7b에서 모두 통과. 답을 만드는 중에 멈춘 요청은 말하지 않음. 실제 Python 워커(가짜 두뇌)와 앱의 통합 시험 통과. 3단계 완료(2026-11-11): 채팅 채널 호출. 채널마다 `answer`(호출어로 부를 때만 / 모든 메시지에 대답), 채팅 호출어(`call.chatWakeWords`, 없으면 음성과 같음)와 지정한 사람 설정은 음성과 같이 씀. 답은 같은 채널에 원래 메시지의 답글로 올리고 아무도 부르지 않음. 다른 봇의 글과 보내기가 꺼진 채널에는 답하지 않음. 음성 대화 순서와는 따로 감(워커가 음성 답과 채팅 답을 따로 써서 다른 사람의 채팅 답 때문에 음성 답이 기다리지 않음. 한 사람의 답은 물은 순서대로 하나씩 씀. 두 답의 LLM 호출이 동시에 돌려면 Strata를 `--parallel 2`로 띄움, 앱이 Strata를 띄우는 M5 전까지). 5분 넘게 늦은 채팅 답은 올리지 않음. 실제 디스코드 시험과 지연 측정은 4단계. 4단계 첫 측정(2026-11-12): 앱의 실제 서비스(`start_services`: 대화 루프, 응답 정책, 워커, 두뇌)를 게임PC Strata(`--parallel 2`)에 붙이고, 봇 두 개로 질문 5개를 2번씩 말해 잼(`app/tests/live_round_trip.rs`). 10개 모두 소리로 답했고, 말 끝부터 첫 소리까지 중앙값 3.5초(최소 2.8초, 날씨 도구 8.6초). 9명이 동시에 말하는 부하(워커의 두 번째 연결로 녹음 문장 9개를 실시간으로 넣음, 그동안 최종 전사 259개)에서는 중앙값 4.4초, 최종 전사가 0.6~0.9초에서 0.8~1.8초로 늦어졌고 1번은 "기분"을 "딥"으로 잘못 들어 날씨 도구를 불러 18.8초가 걸림. 짧은 답의 시간은 최종 전사 0.65~0.85초, 두뇌 2.0~2.9초(도구 고르기 0.42초, 계획 0.5초, 답 호출의 지시문 약 4,300토큰 읽기 1.1초와 생성), 재생 시작과 전달 약 0.4초. Strata의 Qwen3.6 엔진은 지시문 앞부분 재사용을 하지 않아(`--prompt-cache-every`는 "이 엔진의 옵션이 아님"으로 무시됨, 같은 대화를 그대로 이어 갈 때만 재사용) 매 호출을 처음부터 읽음. 생성은 0.2~0.5초라 문장 단위로 흘려도 짧은 답은 거의 빨라지지 않음. 1.5초 기준은 아직 못 맞춤. 같은 시험에서 찾아 고친 것: v1 TTS 설정(영어 전용 Piper) 때문에 한국어 질문에 영어로 답하던 것(v2 두뇌는 묻는 사람의 언어로 답함), 호출어 뒤에 쉬면 "자비스"만 따로 끊겨 그 이름에만 답하고 이어진 질문은 무시하던 것(이제 같은 사람이 이어서 하는 말과 합침, `call.followUpMs`). 4단계 지연 줄이기(사용자 결정, 2026-11-12): 부름을 받으면 "띠링" 효과음(앱이 만든 0.3초 소리, `call.earcon`, 이름만 부르고 쉬면 그때 바로), 답은 한국어 기본(영어 등은 따로 부탁할 때만), v2 두뇌의 짧은 지시문(성격 설명 7.4천 자를 1.3천 자로, 답은 최대한 짧게, 화면공유 도구는 v2에 없어 뺌: 인사의 답 지시문 4,500토큰이 1,400토큰), 답 전에 판단 한 번(도구 고르기로 도구가 필요한지 정하고, 필요할 때만 계획. 계획 하나로 합치거나 계획을 아예 빼 보니 날씨나 여러 단계 질문이 틀려 이 방식으로 정함), 말하는 중의 중간 전사가 호출로 읽히면 도구 고르기를 미리 해 둠(워커 `prepare`). 평가 전체(v2 설정, 마지막 지시문 수정 전) 219개 통과, 6개 실패: 파리·런던 비교와 지식 그래프 갈래 분류는 전부터 실패, 3개는 v2가 쓰지 않는 v1 개인 기억(그래프·일기) 평가, 1개는 새 답 길이 평가("하늘은 왜 파래"의 답이 72자로 기준 70자를 넘음). 그 뒤 "왜·어떻게" 질문은 핵심 이유만 말하도록 지시문을 고치고 답 길이 평가를 따로 3번 돌려 3번 모두 통과(v2 답 합계 185~205자, 예전 315~356자), 한국어 기본·지난 대화·채팅 채널·건너뛴 도구 평가 22개도 모두 통과(전체 평가는 이 수정 뒤 다시 돌리지 않음). 실제 디스코드 재측정(2026-11-12, `app/tests/live_round_trip.rs`, 질문 5개 2번): 첫 소리(효과음)는 이름 뒤에 쉬면 질문이 끝나기 전에, 쉬지 않으면 0.94~1.10초. 답의 첫 소리는 중앙값 1.9초(1.56~2.30초, 날씨 도구 5.75~5.85초), 9명이 동시에 말할 때 2.8초(2.13~3.41초, "기분"을 "딥"으로 잘못 들은 1번은 웹 검색으로 13.3초). 혼자일 때는 미리 해 둔 판단이 5번 모두 쓰여 말 끝 뒤 두뇌 시간이 0.6~0.74초였고, 9명 부하에서는 중간 전사가 밀려 미리 판단이 한 번도 되지 않음(두뇌 1.4초). 같은 시험에서 찾아 고친 것: 모델이 "10시 37분"을 오후로 읽음(시간 줄에 12시간 표기 추가), 없는 타이머 도구 호출 글자(``)를 답으로 내 TTS가 읽을 뻔함(도구 호출로 읽음) | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영은 아직. 4단계 첫 부분 완료(2026-11-12): 설치 `install.rs`·`download.rs`(이어받기, SHA-256 확인), M0 키트와 같은 방식으로 uv 0.11.20 → 워커·두뇌 Python 3.12 환경(v2 전용 패키지 목록 `requirements-brain.txt`) → MeloTTS Python 3.11 환경 → Whisper large-v3-turbo → MeloTTS 한국어 음성 → Strata를 모두 데이터 폴더 안에 설치하고, 끝나면 다운로드 캐시를 비우고 워커 설정을 설치된 Python으로 바꿈. 마법사 "모델" 단계에서 진행·취소·다시 시도. 이 서버(Linux)에서 빈 폴더부터 전부 설치해 보고 그 런타임으로 서비스를 켜 워커 연결, 받아 적기·음성 준비까지 확인했고, 설치 중 데이터 폴더 밖에는 아무것도 쓰지 않음. 대화 모델(약 23GB)은 앱이 Strata를 직접 띄우는 다음 부분에서 받음. 4단계 뒷부분 완료(2026-11-12): 서비스를 켜면 앱이 먼저 데이터 폴더의 Strata를 띄움(`app/src/strata.rs`, M0와 같은 모델과 평소 배치, 처음 켤 때 대화 모델 약 23GB를 받음, 대시보드에 진행률과 Strata의 마지막 줄, 켜는 중에도 정지 가능, 서비스를 끄면 Strata도 끔). 동시 요청은 1개(모든 메시지에 답하는 채팅 채널이 있으면 2개), 그림 읽기는 v2에서 아직 쓰지 않아 끔. 시작할 때마다 두뇌 설정 `config/brain.json`(Strata 주소, Strata가 알려 준 모델 이름, 데이터 폴더 안의 기억 DB)을 써서 워커에 넘김. 이미 떠 있는 서버를 쓰려면 설정 파일의 `llm.url`. 확인: 가짜 Strata로 진행률·준비·정지·다운로드 중 취소·실패를 단위 시험, 게임PC의 Strata 0.1.59가 앱의 실행 옵션을 그대로 받아들임(`--plan`), 앱 서비스를 `llm.url`로 게임PC Strata에 붙여 실제 디스코드 왕복 10개 모두 소리로 답함. 앱이 Strata를 직접 띄워 모델을 받는 실제 확인은 이 서버에서 할 수 없어(메모리) Windows 빌드 단계에서 게임PC로 함. 5단계 완료(2026-11-12): Tauri 2 창 `app/shell`(`jarvis.exe`, 화면의 명령을 같은 `AdminApi`로 넘김, 창을 닫으면 서비스와 Strata를 끄고 끝날 때까지 기다림, 창의 브라우저 자료는 위치 기억 파일 옆)과 Windows 빌드 `app/shell/package.sh`(이 서버에서 `x86_64-pc-windows-gnu`로 빌드, `Jarvis/` 폴더에 실행 파일·WebView2Loader.dll·Python 소스 `python-src`, zip 11MB). 시험용 Windows VM에서: 창과 마법사, PC 점검, uv·워커 환경 설치, 설치 취소 뒤 남은 프로세스 없음, 봇 토큰 DPAPI 암호화 저장, 시작 실패 이유 표시, 로그 화면·오류 복사·zip, 창 닫기로 종료, %APPDATA%·%LOCALAPPDATA%에 아무것도 안 남김, 앱 핵심 단위 테스트(Windows 빌드) 통과. 게임PC(RTX 5070 Ti, C:\JarvisM0 안에서만)에서 같은 관리 명령으로: 전체 설치 7단계 6분 40초, 앱이 직접 띄운 Strata가 엔진과 대화 모델 22.9GB를 약 6분에 받고 준비, 워커(GPU 받아 적기·음성) 연결, 디스코드 음성 채널 입장, 시험 봇이 말한 질문 5개에 모두 소리로 답함(앱이 잰 전체 중앙값 3.36초, 처음 질문 6.4초, 날씨 11.6초), 정지 8초에 GPU 메모리 반환. 같은 시험에서 찾아 고친 것: Windows는 닫힌 로컬 포트의 연결 거부가 약 2초 늦어 정지 확인이 실패로 나오던 것, Strata가 모델 크기(`X of Y GB`)로만 진행을 알려 진행률이 앞 단계의 80%에 멈춰 있던 것, Strata와 NVIDIA 셰이더 캐시가 %APPDATA%에 쓰던 것(데이터 폴더로). 마무리(2026-11-12): 채팅 채널 이름·주제 반영 `app/src/channel_sync.rs`(채널마다 "디스코드에도 반영", 기본 켜짐; 등록하면 디스코드의 이름·주제로 채움, 저장하면 바뀐 채널만 디스코드에 반영하고 디스코드가 바꾼 이름(공백은 `-`)을 화면에 다시 보여 줌, 주제 1,024자 초과는 저장 전에 거절, 10분에 2번 제한에 걸리면 "잠시 뒤 반영" 후 디스코드가 알려 준 시간 뒤 마지막 저장값으로 저절로 다시 시도, 권한이 없으면 이유를 보여 주고 앱에만 저장). 실제 디스코드 시험 채널에서 채움·반영·제한(587초 대기)·자동 재시도까지 확인 후 채널 삭제. 모델 화면에 TTS 말하기 속도(MeloTTS, 0.5~2.0, 기본 1.5; 한국어 모델은 목소리가 KR 하나뿐이라 목소리 선택은 없음). 창을 닫을 때 설치 중이면 취소하고 끝날 때까지 기다림, 정리를 확인하지 못하면 창을 닫지 않고 이유를 보여 줌(한 번 더 닫으면 종료), 실패한 실행이 남긴 Strata도 정리. 창의 WebView 자료는 데이터 폴더(`cache/webview`), 폴더를 고르기 전에는 임시 폴더에 두었다가 다음 시작 때 지움(`%APPDATA%\JarvisBot`에는 위치 파일 하나만). Windows의 UTF-8 옵션이 꺼진 PC의 CP949 출력도 끝까지 읽음. VM에서 다시 확인: 설치 중 창 닫기 뒤 남은 프로세스 없음, `--location` 없이 실행 시 위치 파일 하나만, Windows용 단위 테스트 168개 통과. 게임PC에서 UTF-8 옵션을 끈 상태(코드 페이지 949)로 다시 확인: 전체 설치 7단계, Strata의 대화 모델 22.9GB 다운로드(진행률 10.9%→90%로 표시)와 준비, 워커·디스코드 연결, 시험 봇 질문 5개 모두 소리로 답함(앱이 잰 전체 중앙값 4.0초), 정지 7초에 GPU 메모리 반환, 로그 485줄에 깨진 글자 없음. 남은 것: 설치 파일(NSIS), Strata가 VRAM을 거의 다 써서(15.8/16.3GB) 받아 적기와 GPU를 나누는 문제(M0의 STT 자리 남기기 배치, M7 성능 단계와 함께) | -| M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인. 1단계 완료(2026-11-13): 관리 앱 "기능" 화면(`app/src/features.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Features and MCP servers"). 날씨·웹 검색·식단 기록 켜기/끄기(끄면 그 도구는 두뇌가 제안하지도 실행하지도 않음, 모델이 이름을 대도, 도구 찾기 도구로도 안 나옴), MCP 서버 추가·삭제·켜기/끄기(이름, 명령, 인자, 환경 변수 이름). API 키 같은 환경 변수 값은 암호화 저장소에만 두고 화면에는 저장 여부만, 로그에서는 가림, 서버를 지우면 값도 지움. 앱이 켤 때 값을 워커 환경으로만 넘기고 두뇌는 그 변수를 자기 환경에서 빼서 각 서버에 자기 값만 줌. 서버마다 연결 결과(도구 수, 실패 이유)는 디버그 없이도 LLM 로그 탭에 남음. 같은 작업에서 v2 두뇌가 v1의 PC 파일 도구(홈 폴더 읽기·쓰기·지우기)와 화면 캡처 도구를 쓰던 것을 뺌(음성·채팅 채널의 누구든 요청할 수 있었음, 화면 보기는 M7에서 권한과 함께). 이 서버에서 확인: 개발용 서버의 브라우저로 날씨를 끄고 MCP 서버(시험용 서버)와 키를 저장, 실제 서비스를 켜니 `brain.json`에 끈 도구와 서버만 있고 키는 없음, 워커가 "MCP server fake: 1 tool(s)"를 남기고 MCP 서버 프로세스만 키를 받음, 로그·설정 파일에 키 없음, 정지 때 MCP 서버도 꺼짐. 남은 것: 봇용 크롬과 가상 모니터, 예약 수집 틀, 나머지 기능 스위치(브라우저 제어·PC 제어·화면 보기·백그라운드 수집, 각 기능과 함께) | +| M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인. 1단계 완료(2026-11-13): 관리 앱 "기능" 화면(`app/src/features.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Features and MCP servers"). 날씨·웹 검색·식단 기록 켜기/끄기(끄면 그 도구는 두뇌가 제안하지도 실행하지도 않음, 모델이 이름을 대도, 도구 찾기 도구로도 안 나옴), MCP 서버 추가·삭제·켜기/끄기(이름, 명령, 인자, 환경 변수 이름). API 키 같은 환경 변수 값은 암호화 저장소에만 두고 화면에는 저장 여부만, 로그에서는 가림, 서버를 지우면 값도 지움. 앱이 켤 때 값을 워커 환경으로만 넘기고 두뇌는 그 변수를 자기 환경에서 빼서 각 서버에 자기 값만 줌. 서버마다 연결 결과(도구 수, 실패 이유)는 디버그 없이도 LLM 로그 탭에 남음. 같은 작업에서 v2 두뇌가 v1의 PC 파일 도구(홈 폴더 읽기·쓰기·지우기)와 화면 캡처 도구를 쓰던 것을 뺌(음성·채팅 채널의 누구든 요청할 수 있었음, 화면 보기는 M7에서 권한과 함께). 이 서버에서 확인: 개발용 서버의 브라우저로 날씨를 끄고 MCP 서버(시험용 서버)와 키를 저장, 실제 서비스를 켜니 `brain.json`에 끈 도구와 서버만 있고 키는 없음, 워커가 "MCP server fake: 1 tool(s)"를 남기고 MCP 서버 프로세스만 키를 받음, 로그·설정 파일에 키 없음, 정지 때 MCP 서버도 꺼짐. 2단계 완료(2026-11-13): 예약 수집 틀(`app/src/collect.rs`, 워커 `src/voice_worker/collect.py`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Background collection"). 관리 앱 "백그라운드 수집" 화면에서 대상(사이트·검색어·RSS, 주기 15분~7일, 켜기/끄기)과 보관 기간(기본 30일)을 정하고 결과를 봄. 기본 대상은 없음. 기능 화면의 "백그라운드 수집" 스위치를 끄거나 켠 대상이 없으면 워커에 아무것도 넘기지 않음. 워커가 음성·두뇌와 따로 돌며, 사이트는 바뀌었을 때만, RSS·검색은 새 항목만 남김. 모든 요청은 웹 검색의 주소 검사(공개 주소만, 리디렉트마다 다시 검사, 1MB, 15초)를 거치고, 모은 내용은 데이터 폴더 `collect/`에만 쓰며 두뇌나 로그로 가지 않음(로그에는 대상 이름과 개수만). 덕덕고가 봇 확인 화면을 주면 "결과 없음"이 아니라 실패로 남김. 이 서버에서 확인: 실제 인터넷의 RSS(hnrss 20개), Atom(cpython 10개), 검색어(10개), 사이트(1개) 수집, 내부 주소는 거절, 개발용 서버 화면에서 대상 저장·잘못된 이름 거절·결과 보기, 실제 서비스 시작으로 켠 대상만 워커에 넘어가 수집되고 정지 때 워커도 꺼짐. 남은 것: 봇용 크롬과 가상 모니터, 나머지 기능 스위치(브라우저 제어·PC 제어·화면 보기, 각 기능과 함께) | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | diff --git a/src/voice_worker/__main__.py b/src/voice_worker/__main__.py index e343e96..99a170a 100644 --- a/src/voice_worker/__main__.py +++ b/src/voice_worker/__main__.py @@ -67,6 +67,13 @@ def main() -> int: brain = JarvisBrain(language=args.tool_language or None, reply_language=args.reply_language or None, mcp_env=mcp_env) + # Background collection runs apart from the voice and the brain (voice_worker.spec.md). + collector = None + if os.environ.get("JARVIS_COLLECT_PATH"): + from .collect import Collector, load_config + collector = Collector(load_config(os.environ["JARVIS_COLLECT_PATH"])) + collector.start() + async def run() -> None: worker = VoiceWorker(token, transcriber, vad.stream, tts, history=history, brain=brain) server = await worker.serve(args.host, args.port) @@ -81,6 +88,8 @@ def main() -> int: except KeyboardInterrupt: pass finally: + if collector: + collector.stop() if tts: tts.close() if history: diff --git a/src/voice_worker/collect.py b/src/voice_worker/collect.py new file mode 100644 index 0000000..9fbad62 --- /dev/null +++ b/src/voice_worker/collect.py @@ -0,0 +1,241 @@ +"""Background collection of sites, search words and RSS feeds (voice_worker.spec.md, "Background +collection"). Results go only to day files in the data folder; logs carry target names and counts.""" + +from __future__ import annotations + +import hashlib +import json +import re +import threading +import time +import urllib.parse +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from datetime import date, datetime, timedelta +from pathlib import Path +from typing import Callable, Optional + +from .log import debug_log, notice + +MAX_BYTES = 1024 * 1024 +TIMEOUT_S = 15 +MAX_REDIRECTS = 5 +SITE_CHARS = 20_000 +SUMMARY_CHARS = 2_000 +SEEN_KEEP = 1000 +USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/120.0.0.0 Safari/537.36") +_DAY_FILE = re.compile(r"^(\d{4}-\d{2}-\d{2})\.jsonl$") + + +@dataclass +class Target: + name: str + kind: str + value: str + every_s: float + + +@dataclass +class Config: + dir: Path + keep_days: int + targets: list + + +def load_config(path) -> Config: + raw = json.loads(Path(path).read_text(encoding="utf-8")) + return Config(Path(raw["dir"]), int(raw.get("keepDays", 30)), + [Target(t["name"], t["kind"], t["value"], float(t["everyMinutes"]) * 60) for t in raw.get("targets", [])]) + + +def safe_get(url: str) -> bytes: + """GET a public http(s) address: every redirect checked again, at most ``MAX_BYTES``.""" + import requests + from jarvis.tools.builtin.web_search import _is_public_url + + for _ in range(MAX_REDIRECTS + 1): + if not _is_public_url(url): + raise ValueError("not a public address") + with requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=TIMEOUT_S, + allow_redirects=False, stream=True) as r: + if r.is_redirect or r.is_permanent_redirect: + url = urllib.parse.urljoin(url, r.headers.get("Location", "")) + continue + r.raise_for_status() + if r.status_code != 200: # e.g. DuckDuckGo's 202 challenge + raise ValueError(f"status {r.status_code}") + body = b"" + for chunk in r.iter_content(64 * 1024): + body += chunk + if len(body) > MAX_BYTES: + raise ValueError("response too large") + return body + raise ValueError("too many redirects") + + +def _text(html) -> str: + from bs4 import BeautifulSoup + soup = BeautifulSoup(html, "html.parser") + for tag in soup(["script", "style", "noscript"]): + tag.decompose() + return " ".join(soup.get_text(" ").split()) + + +def _site(body: bytes) -> list: + from bs4 import BeautifulSoup + soup = BeautifulSoup(body, "html.parser") + title = soup.title.get_text().strip() if soup.title else "" + for tag in soup(["script", "style", "noscript", "title"]): + tag.decompose() + text = "\n".join(line for line in (" ".join(l.split()) for l in soup.get_text("\n").splitlines()) if line) + return [{"title": title, "text": text[:SITE_CHARS]}] + + +def _local(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _feed(body: bytes) -> list: + """RSS 2.0 items or Atom entries, each with an ``id`` to tell new ones.""" + out = [] + for el in ET.fromstring(body).iter(): + if _local(el.tag) not in ("item", "entry"): + continue + f = {_local(c.tag): c for c in el} + link = (f["link"].get("href") or (f["link"].text or "")).strip() if "link" in f else "" + get = lambda *keys: next(((f[k].text or "").strip() for k in keys if k in f), "") + item = {"title": get("title"), "url": link, "published": get("pubDate", "published", "updated"), + "text": _text(get("description", "summary", "content"))[:SUMMARY_CHARS]} + item["id"] = get("guid", "id") or link or item["title"] + out.append(item) + return out + + +def search_url(words: str) -> str: + return "https://lite.duckduckgo.com/lite/?q=" + urllib.parse.quote_plus(words) + + +class SearchBlocked(Exception): + """DuckDuckGo served its bot challenge instead of results (web_search.spec.md).""" + + +def _search(body: bytes) -> list: + from bs4 import BeautifulSoup + if b"anomaly-modal" in body or b"anomaly.js" in body: + raise SearchBlocked() + out = [] + for a in BeautifulSoup(body, "html.parser").find_all("a", href=True): + href, title = a["href"], " ".join(a.get_text().split()) + if href.startswith("//duckduckgo.com/l/"): + href = urllib.parse.parse_qs(urllib.parse.urlparse(href).query).get("uddg", [""])[0] + host = urllib.parse.urlparse(href).hostname or "" + if href.startswith("http") and len(title) > 10 and not host.endswith("duckduckgo.com"): + out.append({"title": title, "url": href, "id": href}) + return out[:10] + + +class Collector: + def __init__(self, cfg: Config, fetch: Callable[[str], bytes] = safe_get, check_every: float = 30.0): + self.cfg = cfg + self.fetch = fetch + self.check_every = check_every + self._stop = threading.Event() + self._thread: Optional[threading.Thread] = None + + # -- state ---------------------------------------------------------------------------------- + def _folder(self, t: Target) -> Path: + return self.cfg.dir / t.name + + def _state(self, t: Target) -> dict: + try: + return json.loads((self._folder(t) / "state.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + def _save_state(self, t: Target, state: dict) -> None: + f = self._folder(t) / "state.json" + f.parent.mkdir(parents=True, exist_ok=True) + tmp = f.with_suffix(".tmp") + tmp.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8") + tmp.replace(f) + + def _keep(self, t: Target, new: list) -> None: + if not new: + return + f = self._folder(t) / f"{date.today()}.jsonl" + f.parent.mkdir(parents=True, exist_ok=True) + at = datetime.now().astimezone().isoformat(timespec="seconds") + with f.open("a", encoding="utf-8") as out: + for item in new: + out.write(json.dumps({"at": at, **item}, ensure_ascii=False) + "\n") + + # -- one round ------------------------------------------------------------------------------ + def _prune(self) -> None: + oldest = date.today() - timedelta(days=self.cfg.keep_days) + if not self.cfg.dir.is_dir(): + return + for folder in self.cfg.dir.iterdir(): + if not folder.is_dir(): + continue + for f in folder.iterdir(): + m = _DAY_FILE.match(f.name) + if m and date.fromisoformat(m.group(1)) < oldest: + f.unlink(missing_ok=True) + + def _run(self, t: Target, state: dict) -> int: + if t.kind == "site": + [page] = _site(self.fetch(t.value)) + digest = hashlib.sha256(page["text"].encode()).hexdigest() + if digest == state.get("hash"): + return 0 + state["hash"] = digest + self._keep(t, [{**page, "url": t.value}]) + return 1 + found = _feed(self.fetch(t.value)) if t.kind == "rss" else _search(self.fetch(search_url(t.value))) + seen = state.get("seen", []) + new = [i for i in found if i["id"] not in seen] + state["seen"] = (seen + [i["id"] for i in new])[-SEEN_KEEP:] + self._keep(t, [{k: v for k, v in i.items() if k != "id"} for i in new]) + return len(new) + + def run_due(self, now: Optional[float] = None) -> None: + now = time.time() if now is None else now + self._prune() + for t in self.cfg.targets: + if self._stop.is_set(): + return + state = self._state(t) + if now - state.get("last", float("-inf")) < t.every_s: + continue + state["last"] = now + t0 = time.perf_counter() + try: + n = self._run(t, state) + notice(f"collect {t.name}: {n} new", "voice_worker") + except Exception as e: # noqa: BLE001 - a broken target waits for its next interval + notice(f"Warning: collect {t.name} failed: {type(e).__name__}", "voice_worker") + self._save_state(t, state) + debug_log(f"collect {t.name} kind={t.kind} ms={(time.perf_counter() - t0) * 1000:.0f}", "voice_worker") + + # -- thread --------------------------------------------------------------------------------- + def start(self) -> None: + def loop(): + while not self._stop.is_set(): + try: + self.run_due() + except Exception as e: # noqa: BLE001 - e.g. the folder became unwritable + notice(f"Warning: collect round failed: {type(e).__name__}", "voice_worker") + self._stop.wait(self.check_every) + + self._thread = threading.Thread(target=loop, name="collect", daemon=True) + self._thread.start() + debug_log(f"collect started: {len(self.cfg.targets)} target(s)", "voice_worker") + + def stop(self, timeout: float = 5.0) -> None: + self._stop.set() + if self._thread: + self._thread.join(timeout) + + def running(self) -> bool: + return bool(self._thread and self._thread.is_alive()) diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index c473f13..f3ebd68 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -317,6 +317,29 @@ which carry Discord's own time. `budget_tokens` (4000). - Logs carry IDs, counts and timings only, never record, question or answer text. +### Background collection (M6) + +With `JARVIS_COLLECT_PATH` set, the worker collects on its own thread, apart from the voice and the +brain (`app/src/admin.spec.md`, "Background collection"). The file is +`{"dir": "/collect", "keepDays": 30, "targets": [{"name", "kind", "value", "everyMinutes"}]}`; +the app writes only enabled targets. Nothing is collected without targets. + +- A target runs when `everyMinutes` passed since its last run (also across restarts; the last run is + kept in `//state.json`), one target at a time, checked every 30 s. A failed run counts + as a run, so a broken site is tried again only at its next interval. +- Kinds: `site` keeps the page's title and text (at most 20,000 characters) when it differs from the + last kept one; `rss` (RSS or Atom) keeps each new item (title, link, time, summary of at most 2,000 + characters, new by its id or link); `search` keeps each new web search result (title and link) for + the words, from DuckDuckGo's lite page, which needs no key (its bot challenge is a failed run, not "no results"). +- Every request goes through the web search's address check (`web_search.spec.md`): only public + http(s) addresses, every redirect checked again, at most 1 MB, 15 s. The collected text is web + content: it goes only to `//.jsonl` (one JSON object per line: `at`, then + `title`, `url`, `text` as the kind has them), never to the brain or a log. +- Day files older than `keepDays` are deleted in every folder of `dir` at each check, also of + targets no longer listed. +- Each run is a `notice` line (category `voice_worker`): the target's name and how many new items, or + a `Warning` with the error's type. Never a URL, words or collected text. + ### Errors `{"type": "error", "code": "...", "message": "...", "id": "..."}`. Codes: `bad_message` (unknown type, diff --git a/tests/test_voice_worker_collect.py b/tests/test_voice_worker_collect.py new file mode 100644 index 0000000..257420a --- /dev/null +++ b/tests/test_voice_worker_collect.py @@ -0,0 +1,188 @@ +"""Background collection (voice_worker.spec.md, "Background collection"). + +The collector runs against a fake fetcher (the real one refuses loopback addresses, which is +checked on its own). Behaviours: each kind keeps only what is new, a target runs again only after +its interval (also across a restart), a failure counts as a run and logs no URL, old day files go, +and nothing collected reaches the log. +""" + +from __future__ import annotations + +import json +import time +from datetime import datetime, timedelta +from pathlib import Path + +import pytest + +from voice_worker.collect import Collector, load_config, safe_get + +RSS = """feed +Firsthttps://example.com/1id-1 +Fri, 13 Nov 2026 10:00:00 +0900<p>one <b>bold</b></p> +{more} +""" +SECOND = """Secondhttps://example.com/2id-2""" + +ATOM = """a +Atom onetag:a,1 +2026-11-13T01:00:00Zsum""" + +DDG = """Settings +A first result title here +Another result title here{more}""" + +PAGE = "Status

Version {v} is out

" + + +class Fake: + """url -> bytes (or an exception to raise); records what was asked.""" + + def __init__(self, pages): + self.pages = pages + self.asked = [] + + def __call__(self, url): + self.asked.append(url) + v = self.pages[url] + if isinstance(v, Exception): + raise v + return v.encode() if isinstance(v, str) else v + + +def config(tmp_path, targets, keep_days=30): + p = tmp_path / "collect.json" + p.write_text(json.dumps({"dir": str(tmp_path / "collect"), "keepDays": keep_days, "targets": targets})) + return load_config(p) + + +def items(tmp_path, name): + out = [] + for f in sorted((tmp_path / "collect" / name).glob("*.jsonl")): + out += [json.loads(line) for line in f.read_text(encoding="utf-8").splitlines()] + return out + + +def lines(capfd): + return capfd.readouterr().err + + +def test_rss_keeps_each_new_item_once(tmp_path, capfd): + fake = Fake({"https://feed.example/rss": RSS.format(more="")}) + cfg = config(tmp_path, [{"name": "뉴스", "kind": "rss", "value": "https://feed.example/rss", "everyMinutes": 15}]) + c = Collector(cfg, fetch=fake) + c.run_due(now=1000.0) + got = items(tmp_path, "뉴스") + assert [i["title"] for i in got] == ["First"] + assert got[0]["url"] == "https://example.com/1" + assert got[0]["text"] == "one bold" + assert got[0]["published"] == "Fri, 13 Nov 2026 10:00:00 +0900" + fake.pages["https://feed.example/rss"] = RSS.format(more=SECOND) + c.run_due(now=1000.0 + 15 * 60) + assert [i["title"] for i in items(tmp_path, "뉴스")] == ["First", "Second"] + out = lines(capfd) + assert "collect 뉴스: 1 new" in out + assert "feed.example" not in out and "First" not in out + + +def test_atom_feeds_are_read_too(tmp_path): + fake = Fake({"https://a.example/atom": ATOM}) + c = Collector(config(tmp_path, [{"name": "a", "kind": "rss", "value": "https://a.example/atom", "everyMinutes": 60}]), + fetch=fake) + c.run_due(now=0.0) + [item] = items(tmp_path, "a") + assert (item["title"], item["url"], item["text"]) == ("Atom one", "https://example.org/a1", "sum") + + +def test_search_keeps_new_results_for_the_words(tmp_path): + fake = Fake({}) + url = "https://lite.duckduckgo.com/lite/?q=rust+release" + fake.pages[url] = DDG.format(more="") + c = Collector(config(tmp_path, [{"name": "s", "kind": "search", "value": "rust release", "everyMinutes": 60}]), + fetch=fake) + c.run_due(now=0.0) + assert [(i["title"], i["url"]) for i in items(tmp_path, "s")] == [ + ("A first result title here", "https://news.example/a"), ("Another result title here", "https://news.example/b")] + fake.pages[url] = DDG.format(more='A third result title') + c.run_due(now=3600.0) + assert [i["url"] for i in items(tmp_path, "s")][-1] == "https://news.example/c" + assert len(items(tmp_path, "s")) == 3 + + +def test_a_search_challenge_page_is_a_failure_not_zero_results(tmp_path, capfd): + url = "https://lite.duckduckgo.com/lite/?q=words" + fake = Fake({url: '
'}) + c = Collector(config(tmp_path, [{"name": "s", "kind": "search", "value": "words", "everyMinutes": 60}]), fetch=fake) + c.run_due(now=0.0) + assert "Warning: collect s failed: SearchBlocked" in lines(capfd) + assert not list((tmp_path / "collect").glob("s/*.jsonl")) + + +def test_a_site_is_kept_only_when_it_changed(tmp_path): + fake = Fake({"https://s.example/": PAGE.format(v=1)}) + c = Collector(config(tmp_path, [{"name": "site", "kind": "site", "value": "https://s.example/", "everyMinutes": 15}]), + fetch=fake) + c.run_due(now=0.0) + c.run_due(now=900.0) + got = items(tmp_path, "site") + assert len(got) == 1 and got[0]["title"] == "Status" and got[0]["text"] == "Version 1 is out" + fake.pages["https://s.example/"] = PAGE.format(v=2) + c.run_due(now=1800.0) + assert [i["text"] for i in items(tmp_path, "site")] == ["Version 1 is out", "Version 2 is out"] + + +def test_a_target_runs_again_only_after_its_interval_also_after_a_restart(tmp_path): + fake = Fake({"https://s.example/": PAGE.format(v=1)}) + targets = [{"name": "site", "kind": "site", "value": "https://s.example/", "everyMinutes": 60}] + Collector(config(tmp_path, targets), fetch=fake).run_due(now=10_000.0) + again = Collector(config(tmp_path, targets), fetch=fake) + again.run_due(now=10_000.0 + 59 * 60) + assert len(fake.asked) == 1 + again.run_due(now=10_000.0 + 60 * 60) + assert len(fake.asked) == 2 + + +def test_a_failure_counts_as_a_run_and_logs_no_address(tmp_path, capfd): + fake = Fake({"https://secret-site.example/": ConnectionError("down at https://secret-site.example/")}) + c = Collector(config(tmp_path, [{"name": "x", "kind": "site", "value": "https://secret-site.example/", "everyMinutes": 15}]), + fetch=fake) + c.run_due(now=0.0) + c.run_due(now=60.0) + assert len(fake.asked) == 1 + out = lines(capfd) + assert "Warning: collect x failed: ConnectionError" in out + assert "secret-site" not in out + + +def test_old_day_files_go_in_every_folder(tmp_path): + cfg = config(tmp_path, [], keep_days=2) + today = datetime.now().date() + for name in ("listed", "removed"): + d = tmp_path / "collect" / name + d.mkdir(parents=True) + for age in (0, 2, 3): + (d / f"{today - timedelta(days=age)}.jsonl").write_text("{}\n") + (d / "state.json").write_text("{}") + Collector(cfg, fetch=Fake({})).run_due(now=time.time()) + for name in ("listed", "removed"): + left = sorted(p.name for p in (tmp_path / "collect" / name).iterdir()) + assert left == sorted([f"{today - timedelta(days=2)}.jsonl", f"{today}.jsonl", "state.json"]) + + +def test_the_real_fetcher_refuses_addresses_that_are_not_public(): + for url in ("http://127.0.0.1:1/", "http://192.168.0.1/", "file:///etc/passwd", "http://localhost/"): + with pytest.raises(ValueError): + safe_get(url) + + +def test_the_thread_collects_on_its_own_and_stops(tmp_path): + fake = Fake({"https://s.example/": PAGE.format(v=1)}) + c = Collector(config(tmp_path, [{"name": "site", "kind": "site", "value": "https://s.example/", "everyMinutes": 15}]), + fetch=fake, check_every=0.05) + c.start() + deadline = time.monotonic() + 5 + while not list((tmp_path / "collect").glob("site/*.jsonl")): + assert time.monotonic() < deadline + time.sleep(0.02) + c.stop() + assert not c.running()