The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(tinymemes): add remixed and docs modules
Steven Enamakel0578384e0e98
diff --git a/crates/openhuman-core/src/tinymemes/docs.rs b/crates/openhuman-core/src/tinymemes/docs.rsnew file mode 100644index 0000000000..3cf7a6c9e8--- /dev/null+++ b/crates/openhuman-core/src/tinymemes/docs.rs@@ -0,0 +1,112 @@+//! The learned-state documents the module asks the host to keep: the slang+//! index, the meme index and the ring of remixed message ids.+//!+//! They live on the storage document port ([`crate::storage`]) under the+//! acting scope, one opaque JSON text per [`IndexKind`]. The host never parses+//! them: the formats, the ring and its cap belong to the module.+//!+//! Older installs kept them as `<workspace>/tinymemes/{slang-index,+//! meme-index,remixed}.json`. The first load of a kind with no stored document+//! adopts that file's content once and renames the file to `<name>.migrated`,+//! so nothing is lost and the file is never read again.++use std::path::{Path, PathBuf};++use anyhow::{anyhow, Result};+use serde_json::{json, Value};+use tinystoragedrivers::{CollectionSpec, Precondition};+use tinymemes_bus::IndexKind;++use crate::config::Config;+use crate::storage::documents::{text, Repo};++const DOMAIN: &str = "tinymemes::docs";+const COLLECTION: &str = "tinymemes_documents";+/// Directory of the pre-storage files, under the workspace.+const LEGACY_DIR: &str = "tinymemes";+const FIELD: &str = "json";++fn collections() -> Vec<CollectionSpec> {+ vec![CollectionSpec::new(COLLECTION)]+}++fn doc_id(kind: IndexKind) -> &'static str {+ match kind {+ IndexKind::Slang => "slang",+ IndexKind::Memes => "memes",+ IndexKind::Remixed => "remixed",+ }+}++fn legacy_file(kind: IndexKind) -> &'static str {+ match kind {+ IndexKind::Slang => "slang-index.json",+ IndexKind::Memes => "meme-index.json",+ IndexKind::Remixed => "remixed.json",+ }+}++fn legacy_path(workspace_dir: &Path, kind: IndexKind) -> PathBuf {+ workspace_dir.join(LEGACY_DIR).join(legacy_file(kind))+}++fn repo(config: &Config) -> Result<Repo> {+ Repo::current_for(&config.workspace_dir, DOMAIN, collections)+}++/// The stored document for `kind`, adopting the legacy file once.+pub(super) fn load(config: &Config, kind: IndexKind) -> Result<Option<String>> {+ let repo = repo(config)?;+ let id = doc_id(kind);+ let stored = repo.run(move |docs| async move { docs.get(COLLECTION, id).await })?;+ if let Some(stored) = stored {+ return Ok(text(&stored.doc, FIELD).map(str::to_owned));+ }+ let path = legacy_path(&config.workspace_dir, kind);+ let Ok(legacy) = std::fs::read_to_string(&path) else {+ return Ok(None);+ };+ // `Absent`: a concurrent save wins over the old file's content.+ let adopted = legacy.clone();+ let written = repo.run(move |docs| async move {+ docs.put(COLLECTION, id, json!({ FIELD: adopted }), Precondition::Absent)+ .await+ .map(|_| ())+ });+ match written {+ Ok(()) => {+ let migrated = path.with_extension("json.migrated");+ match std::fs::rename(&path, &migrated) {+ Ok(()) => log::info!(+ "[tinymemes] adopted {} into storage (kept as {})",+ legacy_file(kind),+ migrated.display()+ ),+ Err(e) => log::warn!("[tinymemes] cannot retire {}: {e}", path.display()),+ }+ Ok(Some(legacy))+ }+ // Somebody stored a document in between; theirs is the truth.+ Err(_) => {+ let stored = repo.run(move |docs| async move { docs.get(COLLECTION, id).await })?;+ Ok(stored.and_then(|s| text(&s.doc, FIELD).map(str::to_owned)))+ }+ }+}++/// Replace the stored document for `kind`.+pub(super) fn save(config: &Config, kind: IndexKind, json: String) -> Result<()> {+ let repo = repo(config)?;+ let id = doc_id(kind);+ repo.run(move |docs| async move {+ let doc: Value = json!({ FIELD: json });+ docs.put(COLLECTION, id, doc, Precondition::None)+ .await+ .map(|_| ())+ })+ .map_err(|e| anyhow!("save {id}: {e}"))+}++#[cfg(test)]+#[path = "docs_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/tinymemes/docs_tests.rs b/crates/openhuman-core/src/tinymemes/docs_tests.rsnew file mode 100644index 0000000000..5e2713eb87--- /dev/null+++ b/crates/openhuman-core/src/tinymemes/docs_tests.rs@@ -0,0 +1,86 @@+use super::*;++fn config_in(dir: &Path) -> Config {+ let mut config = Config::default();+ config.config_path = dir.join("config.toml");+ config.workspace_dir = dir.join("workspace");+ config.secrets.encrypt = false;+ config+}++fn write_legacy(config: &Config, kind: IndexKind, content: &str) {+ let path = legacy_path(&config.workspace_dir, kind);+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, content).unwrap();+}++#[test]+fn a_saved_document_loads_back_and_kinds_are_separate() {+ let dir = tempfile::tempdir().unwrap();+ let config = config_in(dir.path());+ assert_eq!(load(&config, IndexKind::Slang).unwrap(), None);+ save(&config, IndexKind::Slang, "{\"terms\":1}".into()).unwrap();+ assert_eq!(+ load(&config, IndexKind::Slang).unwrap().as_deref(),+ Some("{\"terms\":1}")+ );+ assert_eq!(load(&config, IndexKind::Memes).unwrap(), None);+ assert_eq!(load(&config, IndexKind::Remixed).unwrap(), None);+ save(&config, IndexKind::Slang, "{\"terms\":2}".into()).unwrap();+ assert_eq!(+ load(&config, IndexKind::Slang).unwrap().as_deref(),+ Some("{\"terms\":2}")+ );+}++#[test]+fn the_legacy_remixed_json_is_adopted_once_and_retired() {+ let dir = tempfile::tempdir().unwrap();+ let config = config_in(dir.path());+ write_legacy(&config, IndexKind::Remixed, "[\"m1\",\"m2\"]");++ assert_eq!(+ load(&config, IndexKind::Remixed).unwrap().as_deref(),+ Some("[\"m1\",\"m2\"]")+ );+ let legacy = legacy_path(&config.workspace_dir, IndexKind::Remixed);+ assert!(!legacy.exists(), "the old file is retired");+ assert!(legacy.with_extension("json.migrated").is_file());++ // The module's later saves are the truth; a stray file is not re-adopted.+ save(&config, IndexKind::Remixed, "[\"m1\",\"m2\",\"m3\"]".into()).unwrap();+ write_legacy(&config, IndexKind::Remixed, "[\"stale\"]");+ assert_eq!(+ load(&config, IndexKind::Remixed).unwrap().as_deref(),+ Some("[\"m1\",\"m2\",\"m3\"]")+ );+}++#[test]+fn every_legacy_index_file_is_adopted() {+ let dir = tempfile::tempdir().unwrap();+ let config = config_in(dir.path());+ write_legacy(&config, IndexKind::Slang, "{\"slang\":true}");+ write_legacy(&config, IndexKind::Memes, "{\"memes\":true}");+ assert_eq!(+ load(&config, IndexKind::Slang).unwrap().as_deref(),+ Some("{\"slang\":true}")+ );+ assert_eq!(+ load(&config, IndexKind::Memes).unwrap().as_deref(),+ Some("{\"memes\":true}")+ );+}++#[test]+fn a_stored_document_wins_over_a_legacy_file() {+ let dir = tempfile::tempdir().unwrap();+ let config = config_in(dir.path());+ save(&config, IndexKind::Memes, "{\"new\":1}".into()).unwrap();+ write_legacy(&config, IndexKind::Memes, "{\"old\":1}");+ assert_eq!(+ load(&config, IndexKind::Memes).unwrap().as_deref(),+ Some("{\"new\":1}")+ );+ assert!(legacy_path(&config.workspace_dir, IndexKind::Memes).exists());+}diff --git a/crates/openhuman-core/src/tinymemes/remixed.rs b/crates/openhuman-core/src/tinymemes/remixed.rsdeleted file mode 100644index e4fbbd126c..0000000000--- a/crates/openhuman-core/src/tinymemes/remixed.rs+++ /dev/null@@ -1,89 +0,0 @@-//! Ids of thread messages that were delivered remixed, kept at-//! `<workspace>/tinymemes/remixed.json`, so the next reading can tell the-//! module which assistant turns carry the bot's own style.-//!-//! One store per workspace. Writes are atomic (temp file, then rename).--use std::collections::{HashMap, VecDeque};-use std::path::{Path, PathBuf};-use std::sync::{Arc, LazyLock, Mutex};--use crate::security::secret_storage::file_store::write_atomic;--pub(super) const DIR: &str = "tinymemes";-const FILE: &str = "remixed.json";-/// Remixed-message ids remembered per workspace (oldest dropped first).-const CAP: usize = 4000;--pub(super) struct RemixedIds {- path: PathBuf,- ids: Mutex<VecDeque<String>>,-}--static STORES: LazyLock<Mutex<HashMap<PathBuf, Arc<RemixedIds>>>> =- LazyLock::new(|| Mutex::new(HashMap::new()));--/// The store for a workspace, loaded from disk on first use. `None` when the-/// state directory cannot be created.-pub(super) fn for_workspace(workspace_dir: &Path) -> Option<Arc<RemixedIds>> {- let mut stores = STORES.lock().unwrap_or_else(|e| e.into_inner());- if let Some(store) = stores.get(workspace_dir) {- return Some(store.clone());- }- let dir = workspace_dir.join(DIR);- if let Err(e) = std::fs::create_dir_all(&dir) {- log::warn!("[tinymemes] cannot create state dir: {e}");- return None;- }- let store = Arc::new(RemixedIds::open(dir.join(FILE)));- stores.insert(workspace_dir.to_path_buf(), store.clone());- Some(store)-}--impl RemixedIds {- /// A store over `path`, with the newest [`CAP`] ids from disk.- pub(super) fn open(path: PathBuf) -> Self {- let mut ids: VecDeque<String> = std::fs::read_to_string(&path)- .ok()- .and_then(|json| serde_json::from_str(&json).ok())- .unwrap_or_default();- cap(&mut ids);- Self {- path,- ids: Mutex::new(ids),- }- }-- pub(super) fn contains(&self, message_id: &str) -> bool {- self.ids- .lock()- .unwrap_or_else(|e| e.into_inner())- .iter()- .any(|id| id == message_id)- }-- /// Record a delivered remix. The list stays locked through the write, so- /// concurrent calls persist in order.- pub(super) fn mark(&self, message_id: String) {- let mut ids = self.ids.lock().unwrap_or_else(|e| e.into_inner());- if ids.contains(&message_id) {- return;- }- ids.push_back(message_id);- cap(&mut ids);- let snapshot = serde_json::to_string(&*ids).unwrap_or_default();- if let Err(e) = write_atomic(&self.path, snapshot.as_bytes()) {- log::warn!("[tinymemes] cannot save remixed ids: {e}");- }- }-}--fn cap(ids: &mut VecDeque<String>) {- while ids.len() > CAP {- ids.pop_front();- }-}--#[cfg(test)]-#[path = "remixed_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tinymemes/remixed_tests.rs b/crates/openhuman-core/src/tinymemes/remixed_tests.rsdeleted file mode 100644index 25ca361f35..0000000000--- a/crates/openhuman-core/src/tinymemes/remixed_tests.rs+++ /dev/null@@ -1,45 +0,0 @@-use super::*;--#[test]-fn marks_survive_a_reopen_and_are_written_atomically() {- let dir = tempfile::TempDir::new().unwrap();- let path = dir.path().join(FILE);- let store = RemixedIds::open(path.clone());- assert!(!store.contains("r1"));- store.mark("r1".into());- store.mark("r1".into());- store.mark("r2".into());- assert!(store.contains("r1"));-- let reopened = RemixedIds::open(path);- assert!(reopened.contains("r1") && reopened.contains("r2"));- let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();- assert_eq!(entries.len(), 1, "temp files left behind");-}--#[test]-fn an_oversized_file_is_capped_on_load_keeping_the_newest() {- let dir = tempfile::TempDir::new().unwrap();- let path = dir.path().join(FILE);- let ids: Vec<String> = (0..CAP + 50).map(|i| format!("id-{i}")).collect();- std::fs::write(&path, serde_json::to_string(&ids).unwrap()).unwrap();- let store = RemixedIds::open(path);- assert!(!store.contains("id-0"));- assert!(store.contains(&format!("id-{}", CAP + 49)));-}--#[test]-fn a_corrupt_file_starts_empty() {- let dir = tempfile::TempDir::new().unwrap();- let path = dir.path().join(FILE);- std::fs::write(&path, "not json").unwrap();- assert!(!RemixedIds::open(path).contains("x"));-}--#[test]-fn one_store_serves_a_workspace() {- let dir = tempfile::TempDir::new().unwrap();- let a = for_workspace(dir.path()).unwrap();- let b = for_workspace(dir.path()).unwrap();- assert!(Arc::ptr_eq(&a, &b));-}