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 host, history, and remix support
Steven Enamakel410bf82da147
diff --git a/crates/openhuman-core/src/tinymemes/history.rs b/crates/openhuman-core/src/tinymemes/history.rsnew file mode 100644index 0000000000..1693bc6819--- /dev/null+++ b/crates/openhuman-core/src/tinymemes/history.rs@@ -0,0 +1,53 @@+//! The thread as the user saw it, in the contract's vocabulary.++use tinymemes_bus::{WireRole, WireTurn};++use crate::threads::store::ConversationMessage;++/// Whether a finished reply is worth remixing at all.+pub(super) fn should_remix(reply: &str, placeholder: &str) -> bool {+ reply != placeholder && !reply.trim().is_empty()+}++/// The thread as the user saw it, oldest first: delivered replies (remixed or+/// not) and the user's messages. `current_user_message` is appended unless it+/// is already the last stored turn (the store may have persisted it first).+pub(super) fn history_turns(+ messages: &[ConversationMessage],+ current_user_message: &str,+ is_remixed: impl Fn(&str) -> bool,+) -> Vec<WireTurn> {+ let mut turns: Vec<WireTurn> = messages+ .iter()+ .filter(|m| !m.content.trim().is_empty())+ .filter_map(|m| match m.sender.as_str() {+ "user" => Some(WireTurn {+ role: WireRole::User,+ text: m.content.clone(),+ remixed: false,+ }),+ "agent" | "assistant" => Some(WireTurn {+ role: WireRole::Assistant,+ text: m.content.clone(),+ remixed: is_remixed(&m.id),+ }),+ _ => None,+ })+ .collect();+ let current = current_user_message.trim();+ let already_there = turns+ .last()+ .is_some_and(|t| t.role == WireRole::User && t.text.trim() == current);+ if !current.is_empty() && !already_there {+ turns.push(WireTurn {+ role: WireRole::User,+ text: current.to_owned(),+ remixed: false,+ });+ }+ turns+}++#[cfg(test)]+#[path = "history_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/tinymemes/host.rs b/crates/openhuman-core/src/tinymemes/host.rsdeleted file mode 100644index d891703324..0000000000--- a/crates/openhuman-core/src/tinymemes/host.rs+++ /dev/null@@ -1,374 +0,0 @@-//! One tinymemes engine per workspace, plus the state it keeps on disk under-//! `<workspace>/tinymemes/`:-//!-//! - `slang-index.json`: the slang index, which grows from web research.-//! - `meme-index.json`: reaction GIFs learned from the web, already vetted.-//! - `remixed.json`: ids of thread messages that were delivered remixed, so the-//! next reading can tell Jev which assistant turns carry the bot's own style.-//!-//! Files are written atomically (temp file, then rename). The engine is-//! rebuilt when the configuration or credentials it was built from change,-//! keeping its learned state.--use std::collections::hash_map::DefaultHasher;-use std::collections::{HashMap, VecDeque};-use std::hash::{Hash, Hasher};-use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Arc, LazyLock, Mutex};--use tinymemes::{- ChatModel, EnvConfig, Evaluator, IndexPolicy, MemeEngine, RatingPolicy, SearchResearcher,- SlangIndex, SlangResearcher, Turn,-};--use crate::config::Config;--use crate::threads::store::ConversationMessage;--const DIR: &str = "tinymemes";-const INDEX_FILE: &str = "slang-index.json";-const MEME_INDEX_FILE: &str = "meme-index.json";-const REMIXED_FILE: &str = "remixed.json";-/// Remixed-message ids remembered per workspace (oldest dropped first).-const REMIXED_CAP: usize = 4000;--/// Replies to wait after a meme before sending another (0 = no cooldown).-pub(crate) const MEME_COOLDOWN_ENV: &str = "OPENHUMAN_TINYMEMES_MEME_COOLDOWN";--pub(crate) struct Host {- pub(crate) engine: MemeEngine,- dir: PathBuf,- remixed: Mutex<VecDeque<String>>,- /// Held across each index snapshot and its write, so concurrent saves land- /// in order and an older snapshot never replaces a newer one.- persist: Mutex<()>,- /// What the engine was built from; a change rebuilds it.- fingerprint: u64,-}--/// `TINYMEMES_*` overrides that change how the engine is built.-const ENV_KEYS: &[&str] = &[- "TINYMEMES_OPENROUTER_KEY",- "TINYMEMES_MODEL",- "TINYMEMES_JEV",- "TINYMEMES_TYPESAFE_KEY",- "TYPESAFE_API_KEY",- "TINYMEMES_OPENJEV_KEY",- "OPENJEV_API_KEY",- MEME_COOLDOWN_ENV,-];--/// A fingerprint of everything the engine is built from: the provider route,-/// endpoints, the backend credential (hashed in memory, never stored or-/// logged), search availability, and the env overrides. Settings changes,-/// sign-in after first use, and credential rotation all change it.-pub(crate) fn fingerprint(config: &Config) -> u64 {- let mut h = DefaultHasher::new();- config.memory_provider.hash(&mut h);- config.inference_url.hash(&mut h);- config.api_url.hash(&mut h);- config.default_model.hash(&mut h);- crate::security::credentials::session_support::resolve_backend_credential(config)- .ok()- .map(|c| c.into_secret())- .hash(&mut h);- openhuman_search(config).is_some().hash(&mut h);- for key in ENV_KEYS {- std::env::var(key).ok().hash(&mut h);- }- h.finish()-}--static HOSTS: LazyLock<Mutex<HashMap<PathBuf, Arc<Host>>>> =- LazyLock::new(|| Mutex::new(HashMap::new()));--/// The engine for a workspace, built on first use. `None` if it cannot be-/// built (the turn then goes out unchanged).-///-/// Backends, each overridable by `TINYMEMES_*` env (see `tinymemes::env`):-///-/// | piece | default (OpenHuman) | env override |-/// | --- | --- | --- |-/// | chat model | OpenHuman's `summarization` provider | `TINYMEMES_OPENROUTER_KEY` (+ `TINYMEMES_MODEL`) |-/// | Jev | OpenHuman-managed; the LLM fallback when unavailable | `TINYMEMES_JEV` (+ its key variables) |-/// | slang research | OpenHuman web search + the chat model | `TINYMEMES_OPENROUTER_KEY` (OpenRouter web plugin) |-pub(crate) fn host_for(config: &Config) -> Option<Arc<Host>> {- let workspace_dir = config.workspace_dir.as_path();- let fp = fingerprint(config);- let mut hosts = HOSTS.lock().unwrap_or_else(|e| e.into_inner());- let previous = match hosts.get(workspace_dir) {- Some(host) if host.fingerprint == fp => return Some(host.clone()),- Some(host) => {- log::info!("[tinymemes] configuration or credentials changed; rebuilding the engine");- Some(host.clone())- }- None => None,- };- 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;- }- // Learned state carries over a rebuild; on first use it loads from disk.- let (index, meme_index, remixed) = match &previous {- Some(p) => (- p.engine.slang_index().clone(),- p.engine.meme_index().clone(),- p.remixed.lock().unwrap_or_else(|e| e.into_inner()).clone(),- ),- None => (- Arc::new(load_slang_index(&dir)),- Arc::new(load_meme_index(&dir)),- load_remixed(&dir),- ),- };-- let env = EnvConfig::from_env();- let http = reqwest::Client::new();-- let (chat, chat_label): (Arc<dyn ChatModel>, String) = match env.chat_model(&http) {- Some(model) => (model, format!("env:openrouter/{}", env.model_id())),- None => (- Arc::new(super::inference::OpenHumanChatModel::new(config.clone())),- format!("openhuman:{}", super::inference::resolved_model(config)),- ),- };-- // Jev: OpenHuman-managed always, unless TINYMEMES_JEV overrides it. With- // no managed Jev (signed out / offline session), OpenHuman's LLM answers- // Jev's questions instead.- let (jev, jev_label): (Arc<dyn Evaluator>, &str) = if env.forces_llm_jev() {- (- tinymemes::env::llm_jev(chat.clone()),- "llm (TINYMEMES_JEV=llm)",- )- } else {- let overridden = match env.jev {- Some(_) => env.jev().unwrap_or_else(|e| {- log::warn!("[tinymemes] TINYMEMES_JEV override unusable, using managed: {e}");- None- }),- None => None,- };- match overridden {- Some((jev, label)) => (jev, label),- None => match super::jev::managed(config) {- Some(jev) => (jev, "openhuman-managed"),- None => (- tinymemes::env::llm_jev(chat.clone()),- "llm (managed jev unavailable)",- ),- },- }- };-- let search = openhuman_search(config);- let (researcher, research_label): (Option<Arc<dyn SlangResearcher>>, &str) =- match env.web_researcher(&http) {- Some(r) => (Some(Arc::new(r)), "env:openrouter-web"),- None => match search.clone() {- Some(search) => (- Some(Arc::new(SearchResearcher::new(search, chat.clone()))),- "openhuman-search",- ),- None => (None, "off (no search provider)"),- },- };-- let mut builder = MemeEngine::builder(jev, chat)- .source(Arc::new(tinymemes::source::Imgflip::new(http.clone())))- .slang_index(index)- .meme_index(meme_index)- .policy(rating_policy())- // Research runs in the background after delivery, never on the- // reply's critical path.- .learn_inline(None);- if let Some(researcher) = researcher {- builder = builder.researcher(researcher);- }- let meme_research_label = match search {- Some(search) => {- builder = builder- .meme_researcher(Arc::new(tinymemes::GiphyPageResearcher::new(search, http)));- "giphy-pages"- }- None => "off (no search provider)",- };- let engine = builder.build();- log::info!(- "[tinymemes] engine ready chat={chat_label} jev={jev_label} research={research_label} \- meme_research={meme_research_label} slang_terms={} learned_memes={}",- engine.slang_index().len("IN"),- engine.meme_index().len("IN")- );- let host = Arc::new(Host::new(engine, dir, remixed, fp));- hosts.insert(workspace_dir.to_path_buf(), host.clone());- Some(host)-}--#[cfg(feature = "modules")]-fn openhuman_search(config: &Config) -> Option<Arc<dyn tinymemes::WebSearch>> {- super::search::OpenHumanSearch::available(config)- .map(|s| Arc::new(s) as Arc<dyn tinymemes::WebSearch>)-}--#[cfg(not(feature = "modules"))]-fn openhuman_search(_config: &Config) -> Option<Arc<dyn tinymemes::WebSearch>> {- None-}--fn load_slang_index(dir: &Path) -> SlangIndex {- match std::fs::read_to_string(dir.join(INDEX_FILE)) {- Ok(json) => SlangIndex::from_json(&json, IndexPolicy::default()).unwrap_or_else(|e| {- log::warn!("[tinymemes] slang index unreadable, starting fresh: {e}");- SlangIndex::new(IndexPolicy::default())- }),- Err(_) => SlangIndex::new(IndexPolicy::default()),- }-}--fn load_meme_index(dir: &Path) -> tinymemes::MemeIndex {- let policy = tinymemes::MemeIndexPolicy::default();- match std::fs::read_to_string(dir.join(MEME_INDEX_FILE)) {- Ok(json) => tinymemes::MemeIndex::from_json(&json, policy).unwrap_or_else(|e| {- log::warn!("[tinymemes] meme index unreadable, starting fresh: {e}");- tinymemes::MemeIndex::new(policy)- }),- Err(_) => tinymemes::MemeIndex::new(policy),- }-}--/// Remixed ids from disk, newest `REMIXED_CAP` kept.-fn load_remixed(dir: &Path) -> VecDeque<String> {- let mut ids: VecDeque<String> = std::fs::read_to_string(dir.join(REMIXED_FILE))- .ok()- .and_then(|json| serde_json::from_str(&json).ok())- .unwrap_or_default();- cap_remixed(&mut ids);- ids-}--fn cap_remixed(ids: &mut VecDeque<String>) {- while ids.len() > REMIXED_CAP {- ids.pop_front();- }-}--static TMP_SEQ: AtomicU64 = AtomicU64::new(0);--/// Write `contents` to `path` atomically: a unique temp file in the same-/// directory, then a rename over the target. Concurrent writers each rename a-/// complete file; a crash never leaves a half-written one.-pub(crate) fn write_atomic(path: &Path, contents: &str) -> std::io::Result<()> {- let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);- let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("state");- let tmp = path.with_file_name(format!(".{name}.{}.{seq}.tmp", std::process::id()));- std::fs::write(&tmp, contents)?;- std::fs::rename(&tmp, path).inspect_err(|_| {- let _ = std::fs::remove_file(&tmp);- })-}--fn rating_policy() -> RatingPolicy {- let mut policy = RatingPolicy::default();- if let Some(turns) = std::env::var(MEME_COOLDOWN_ENV)- .ok()- .and_then(|v| v.trim().parse::<usize>().ok())- {- policy.meme_cooldown_turns = turns;- }- policy-}--impl Host {- /// A host over `engine`, keeping its state files in `dir`.- pub(crate) fn new(- engine: MemeEngine,- dir: PathBuf,- remixed: VecDeque<String>,- fingerprint: u64,- ) -> Self {- Self {- engine,- dir,- remixed: Mutex::new(remixed),- persist: Mutex::new(()),- fingerprint,- }- }-- pub(crate) fn is_remixed(&self, message_id: &str) -> bool {- self.remixed- .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(crate) fn mark_remixed(&self, message_id: String) {- let mut ids = self.remixed.lock().unwrap_or_else(|e| e.into_inner());- if ids.contains(&message_id) {- return;- }- ids.push_back(message_id);- cap_remixed(&mut ids);- let snapshot = serde_json::to_string(&*ids).unwrap_or_default();- if let Err(e) = write_atomic(&self.dir.join(REMIXED_FILE), &snapshot) {- log::warn!("[tinymemes] cannot save remixed ids: {e}");- }- }-- pub(crate) fn save_memes(&self) {- let _order = self.persist.lock().unwrap_or_else(|e| e.into_inner());- let json = self.engine.meme_index().to_json();- if let Err(e) = write_atomic(&self.dir.join(MEME_INDEX_FILE), &json) {- log::warn!("[tinymemes] cannot save meme index: {e}");- }- }-- pub(crate) fn save_index(&self) {- let _order = self.persist.lock().unwrap_or_else(|e| e.into_inner());- let json = self.engine.slang_index().to_json();- if let Err(e) = write_atomic(&self.dir.join(INDEX_FILE), &json) {- log::warn!("[tinymemes] cannot save slang index: {e}");- }- }-}--/// The thread as the user saw it, oldest first: delivered replies (remixed or-/// not) and the user's messages. `current_user_message` is appended unless it-/// is already the last stored turn (the store may have persisted it first).-pub(crate) fn history_turns(- messages: &[ConversationMessage],- current_user_message: &str,- is_remixed: impl Fn(&str) -> bool,-) -> Vec<Turn> {- let mut turns: Vec<Turn> = messages- .iter()- .filter(|m| !m.content.trim().is_empty())- .filter_map(|m| match m.sender.as_str() {- "user" => Some(Turn::user(m.content.clone())),- "agent" | "assistant" => Some(if is_remixed(&m.id) {- Turn::remixed(m.content.clone())- } else {- Turn::assistant(m.content.clone())- }),- _ => None,- })- .collect();- let current = current_user_message.trim();- let already_there = turns- .last()- .is_some_and(|t| t.role == tinymemes::Role::User && t.text.trim() == current);- if !current.is_empty() && !already_there {- turns.push(Turn::user(current.to_owned()));- }- turns-}--#[cfg(test)]-#[path = "host_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tinymemes/host_tests.rs b/crates/openhuman-core/src/tinymemes/host_tests.rsdeleted file mode 100644index 075a26fce9..0000000000--- a/crates/openhuman-core/src/tinymemes/host_tests.rs+++ /dev/null@@ -1,190 +0,0 @@-use super::*;--fn msg(id: &str, sender: &str, content: &str) -> ConversationMessage {- ConversationMessage {- id: id.to_owned(),- content: content.to_owned(),- message_type: "text".to_owned(),- extra_metadata: serde_json::Value::Null,- sender: sender.to_owned(),- created_at: "2026-10-09T00:00:00Z".to_owned(),- }-}--#[test]-fn history_marks_remixed_replies_and_appends_the_pending_message() {- let messages = vec![- msg("u1", "user", "bhai build fail"),- msg("r1", "agent", "Arre yaar, moye moye"),- msg("r2", "agent", "Plain reply"),- msg("s1", "system", "ignored"),- msg("u2", "user", " "),- ];- let turns = history_turns(&messages, "phir se fail", |id| id == "r1");- assert_eq!(turns.len(), 4);- assert!(turns[1].remixed);- assert!(!turns[2].remixed);- assert_eq!(turns[3].text, "phir se fail");-}--#[test]-fn pending_message_is_not_duplicated_when_already_stored() {- let messages = vec![msg("u1", "user", "hello there")];- let turns = history_turns(&messages, "hello there ", |_| false);- assert_eq!(turns.len(), 1);-}--#[test]-fn a_new_message_repeating_an_earlier_one_is_still_appended() {- // user("hello"), agent("reply"), then a new "hello": a distinct message.- let messages = vec![msg("u1", "user", "hello"), msg("r1", "agent", "reply")];- let turns = history_turns(&messages, "hello", |_| false);- assert_eq!(turns.len(), 3);- assert_eq!(turns[2].text, "hello");-}--#[test]-fn atomic_writes_replace_the_file_and_leave_no_temp_files() {- let dir = tempfile::TempDir::new().unwrap();- let path = dir.path().join("slang-index.json");- write_atomic(&path, "{\"a\":1}").unwrap();- write_atomic(&path, "{\"a\":2}").unwrap();- assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"a\":2}");- let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();- assert_eq!(entries.len(), 1, "temp files left behind");-}--#[test]-fn an_oversized_remixed_file_is_capped_on_load() {- let dir = tempfile::TempDir::new().unwrap();- let ids: Vec<String> = (0..REMIXED_CAP + 50).map(|i| format!("id-{i}")).collect();- std::fs::write(- dir.path().join(REMIXED_FILE),- serde_json::to_string(&ids).unwrap(),- )- .unwrap();- let loaded = load_remixed(dir.path());- assert_eq!(loaded.len(), REMIXED_CAP);- // The newest are kept.- assert_eq!(- loaded.back().map(String::as_str),- Some(format!("id-{}", REMIXED_CAP + 49)).as_deref()- );- assert_eq!(loaded.front().map(String::as_str), Some("id-50"));-}--#[test]-fn the_fingerprint_follows_the_provider_settings() {- let config = crate::config::Config::default();- let base = fingerprint(&config);- assert_eq!(fingerprint(&config), base);- let mut changed = config.clone();- changed.memory_provider = Some("openrouter:deepseek/deepseek-v4-flash".into());- assert_ne!(fingerprint(&changed), base);- let mut changed = config.clone();- changed.inference_url = Some("https://openrouter.ai/api/v1".into());- assert_ne!(fingerprint(&changed), base);-}--fn config_in(dir: &std::path::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-}--#[test]-fn remixed_ids_are_deduplicated_persisted_and_capped() {- let dir = tempfile::TempDir::new().unwrap();- let host = host_for(&config_in(dir.path())).expect("engine");- host.mark_remixed("m1".into());- host.mark_remixed("m1".into());- host.mark_remixed("m2".into());- assert!(host.is_remixed("m1") && host.is_remixed("m2"));- assert!(!host.is_remixed("m3"));- let saved = load_remixed(&dir.path().join("workspace").join(DIR));- assert_eq!(saved, ["m1", "m2"]);-- let mut ids: VecDeque<String> = (0..REMIXED_CAP + 3).map(|i| i.to_string()).collect();- cap_remixed(&mut ids);- assert_eq!(ids.len(), REMIXED_CAP);- assert_eq!(ids.front().map(String::as_str), Some("3"));-}--#[test]-fn learned_state_survives_an_engine_rebuild() {- let dir = tempfile::TempDir::new().unwrap();- let config = config_in(dir.path());- let first = host_for(&config).expect("engine");- assert!(Arc::ptr_eq(&first, &host_for(&config).unwrap()));- first.mark_remixed("kept".into());-- // A settings change rebuilds the engine but keeps what it learned.- let mut changed = config.clone();- changed.inference_url = Some("https://openrouter.ai/api/v1".into());- let rebuilt = host_for(&changed).expect("engine");- assert!(!Arc::ptr_eq(&first, &rebuilt));- assert!(rebuilt.is_remixed("kept"));-}--#[test]-fn indexes_round_trip_through_disk() {- let dir = tempfile::TempDir::new().unwrap();- let config = config_in(dir.path());- let host = host_for(&config).expect("engine");- host.save_index();- host.save_memes();- let state = dir.path().join("workspace").join(DIR);- assert!(state.join(INDEX_FILE).exists());- assert!(state.join(MEME_INDEX_FILE).exists());- assert_eq!(- load_slang_index(&state).to_json(),- host.engine.slang_index().to_json()- );- assert_eq!(- load_meme_index(&state).to_json(),- host.engine.meme_index().to_json()- );-}--#[test]-fn unreadable_state_files_start_fresh() {- let dir = tempfile::TempDir::new().unwrap();- for file in [INDEX_FILE, MEME_INDEX_FILE, REMIXED_FILE] {- std::fs::write(dir.path().join(file), "not json").unwrap();- }- assert_eq!(load_slang_index(dir.path()).len("IN"), 0);- assert_eq!(load_meme_index(dir.path()).len("IN"), 0);- assert!(load_remixed(dir.path()).is_empty());- // Missing files are a fresh start too.- let empty = tempfile::TempDir::new().unwrap();- assert_eq!(load_slang_index(empty.path()).len("IN"), 0);- assert_eq!(load_meme_index(empty.path()).len("IN"), 0);-}--#[test]-fn the_meme_cooldown_follows_its_env_override() {- if std::env::var(MEME_COOLDOWN_ENV).is_err() {- assert_eq!(- rating_policy().meme_cooldown_turns,- RatingPolicy::default().meme_cooldown_turns- );- }-}--#[test]-fn a_failed_write_leaves_no_temp_file() {- let dir = tempfile::TempDir::new().unwrap();- // Renaming over a directory fails; the temp file must be cleaned up.- let target = dir.path().join("taken");- std::fs::create_dir(&target).unwrap();- std::fs::write(target.join("child"), "x").unwrap();- assert!(write_atomic(&target, "{}").is_err());- let leftovers: Vec<_> = std::fs::read_dir(dir.path())- .unwrap()- .filter_map(|e| e.ok())- .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))- .collect();- assert!(leftovers.is_empty());-}diff --git a/crates/openhuman-core/src/tinymemes/mod.rs b/crates/openhuman-core/src/tinymemes/mod.rsindex 22d459d0f2..8d5cfc7726 100644--- a/crates/openhuman-core/src/tinymemes/mod.rs+++ b/crates/openhuman-core/src/tinymemes/mod.rs@@ -1,30 +1,42 @@//! TinyMemes host adapter: remixes the orchestrator's final reply with//! region slang and memes when the chat can take it.//!-//! - Gated by `OPENHUMAN_TINYMEMES` (off by default; see [`arm`] for `on` and-//! the `ab` / `ab:NN` experiment split).+//! The engine (Jev reading, rating, rewrite, slang and meme indexes) runs in+//! the `tinymemes` module, reached over its `tinymemes-bus` contract. This+//! domain keeps what is the host's:+//!+//! - the `OPENHUMAN_TINYMEMES` flag and the A/B split ([`arm`]);+//! - the thread as the user saw it, with earlier remixed replies tagged+//! ([`history`], [`remixed`]);+//! - the callbacks the module asks for while it works: OpenHuman inference,+//! managed Jev, web search and the workspace index files ([`callbacks`],+//! served over the bus by [`service`]).+//!+//! Behaviour:+//!//! - Runs after the turn, on `full_response` only. Sub-agent output never//! reaches it.-//! - Reads the thread as the user saw it (earlier replies already remixed),-//! not the agent's original transcript. The agent's own transcript keeps the-//! original wording, so the orchestrator never sees its replies in slang.-//! - Fails open: any error or timeout delivers the original reply.-//! - Slang web research runs in the background after delivery, only when Jev-//! judges the slang index short for the reply.+//! - The agent's own transcript keeps the original wording, so the+//! orchestrator never sees its replies in slang.+//! - Fails open: any error, refusal or timeout delivers the original reply.//!//! Every turn in an experiment logs one grep-friendly `[tinymemes] turn` line//! (arm, turn time, remix time, rating, outcome) for the A/B comparison. No//! user content is logged.mod arm;-mod host;+mod callbacks;+mod history;mod inference;mod jev;-#[cfg(feature = "modules")]+mod remixed;mod search;+pub(crate) mod service;use crate::config::Config;+use async_trait::async_trait;use std::time::{Duration, Instant};+use tinymemes_bus::{RemixRequest, RemixResponse, SkipReason};pub(crate) use arm::Arm;pub(crate) use arm::FLAG_ENV;@@ -44,6 +56,25 @@ pub(crate) fn holds_text_stream(thread_id: &str) -> bool {arm::assign(arm::mode(), thread_id) == Arm::Treatment}+/// Something that can remix one reply: the module in production, a script in+/// tests.+#[async_trait]+pub(crate) trait Remixer: Send + Sync {+ async fn remix(&self, request: RemixRequest) -> Result<RemixResponse, String>;+}++/// The loadable `tinymemes` module, with this workspace's callbacks served.+struct ModuleRemixer<'a> {+ config: &'a Config,+}++#[async_trait]+impl Remixer for ModuleRemixer<'_> {+ async fn remix(&self, request: RemixRequest) -> Result<RemixResponse, String> {+ service::remix(self.config, request).await+ }+}+/// Remix a finished task's reply in place, when it is a real answer (not/// empty, not the `placeholder` sent when the inference budget ran out) and/// the thread is in the treatment arm. Fails open: the reply is left@@ -57,7 +88,7 @@ pub(crate) async fn remix_task_reply(placeholder: &str,turn_elapsed: Duration,) {- if !should_remix(full_response, placeholder) {+ if !history::should_remix(full_response, placeholder) {return;}if let Some(remixed) = remix_final_reply(@@ -75,11 +106,6 @@ pub(crate) async fn remix_task_reply(}}-/// Whether a finished reply is worth remixing at all.-fn should_remix(reply: &str, placeholder: &str) -> bool {- reply != placeholder && !reply.trim().is_empty()-}-/// Remix a finished turn's reply. Returns the text to deliver instead, or/// `None` to deliver the original. `turn_elapsed` is the agent turn's own/// duration, logged for both arms so throughput can be compared.@@ -101,7 +127,7 @@ async fn remix_final_reply(return None;}let started = Instant::now();- let Some((host, messages)) = load(config, thread_id).await else {+ let Some((remixed, messages)) = load(config, thread_id).await else {log_outcome(&turn, started, "engine_unavailable", None);return None;};@@ -111,8 +137,10 @@ async fn remix_final_reply(log_outcome(&turn, started, "history_unavailable", None);return None;};+ let remixer = ModuleRemixer { config };remix_with(- &host,+ &remixer,+ &remixed,&messages,&turn,started,@@ -151,26 +179,25 @@ fn gate(arm: Arm, turn: &TurnInfo<'_>) -> bool {}}-/// The workspace's engine and the thread as stored. Engine lookup-/// (credentials, first-use state files) and the thread read are blocking file-/// work, so they run off the async runtime. `None` when no engine can be-/// built; the inner `None` when the thread cannot be read.+/// The workspace's remixed-id store and the thread as stored. Both are+/// blocking file work, so they run off the async runtime. `None` when the+/// store cannot be opened; the inner `None` when the thread cannot be read.async fn load(config: &Config,thread_id: &str,) -> Option<(- std::sync::Arc<host::Host>,+ std::sync::Arc<remixed::RemixedIds>,Option<Vec<crate::threads::store::ConversationMessage>>,)> {let config = config.clone();let thread_id = thread_id.to_owned();crate::core::runtime::spawn_blocking_scoped(move || {- let host = host::host_for(&config)?;+ let ids = remixed::for_workspace(&config.workspace_dir)?;let messages =crate::threads::store::get_messages(config.workspace_dir.clone(), &thread_id).map_err(|e| log::warn!("[tinymemes] thread history unavailable: {e}")).ok();- Some((host, messages))+ Some((ids, messages))}).await.ok()@@ -187,8 +214,10 @@ fn budget() -> Duration {}/// Read, rate, and remix `reply` against the thread, within `budget`.+#[allow(clippy::too_many_arguments)]async fn remix_with(- host: &std::sync::Arc<host::Host>,+ remixer: &dyn Remixer,+ remixed: &std::sync::Arc<remixed::RemixedIds>,messages: &[crate::threads::store::ConversationMessage],turn: &TurnInfo<'_>,started: Instant,@@ -196,10 +225,26 @@ async fn remix_with(reply: &str,budget: Duration,) -> Option<String> {- let request_id = turn.request_id;- let turns = host::history_turns(messages, user_message, |id| host.is_remixed(id));- let outcome = match tokio::time::timeout(budget, host.engine.process(&turns, reply)).await {- Ok(outcome) => outcome,+ let request = RemixRequest {+ conversation: history::history_turns(messages, user_message, |id| remixed.contains(id)),+ reply: reply.to_owned(),+ region: None,+ enabled: true,+ timeout_ms: u64::try_from(budget.as_millis()).unwrap_or(u64::MAX),+ deliver: false,+ };+ // The module enforces `timeout_ms` itself; this outer bound also covers+ // module load, callback serving and the bus hop.+ let response = match tokio::time::timeout(budget, remixer.remix(request)).await {+ Ok(Ok(response)) => response,+ Ok(Err(error)) => {+ log::warn!(+ "[tinymemes] remix unavailable request_id={}: {error}",+ turn.request_id+ );+ log_outcome(turn, started, "error", None);+ return None;+ }Err(_) => {log_outcome(turn, started, "timeout", None);return None;@@ -207,110 +252,36 @@ async fn remix_with(};// Whether the delivered reply actually changed.- let remixed = outcome.remix.is_some() && outcome.reply.trim() != reply.trim();-- // Slang research, off the critical path, only for a reply that was- // actually remixed and only when Jev judged the index short of slang for it.- if let (Some(reading), true) = (&outcome.reading, remixed) {- let policy = host.engine.slang_index().policy();- if reading.wants_more_slang(policy.search_below) {- let host = host.clone();- let intent = reading.reply_intent;- let reply = reply.to_owned();- let request_id = request_id.to_owned();- crate::core::runtime::spawn_scoped(async move {- match host.engine.learn_for_reply(intent, &reply).await {- Ok(Some(r)) => log::info!(- "[tinymemes] slang research request_id={request_id} added={} \- corroborated={} rejected={} failed_jev={}",- r.added,- r.corroborated,- r.rejected,- r.failed_verification- ),- Ok(None) => {- log::debug!("[tinymemes] slang research skipped (repeat or budget)")- }- Err(e) => log::warn!("[tinymemes] slang research failed: {e}"),- }- persist(&host, |h| h.save_index()).await;- });+ let changed = response.remixed && response.reply.trim() != reply.trim();+ let result = if changed {+ let id = crate::threads::store::run_reply_message_id(turn.request_id);+ let remixed = remixed.clone();+ if let Err(e) =+ crate::core::runtime::spawn_blocking_scoped(move || remixed.mark(id)).await+ {+ log::warn!("[tinymemes] remixed-id write task failed: {e}");}- }-- // Meme research, off the critical path: a meme was allowed but nothing in- // the catalog fit. New GIFs are vetted before Jev can pick them.- if outcome.wants_more_memes() {- if let Some(reading) = &outcome.reading {- let host = host.clone();- let intent = reading.reply_intent;- let request_id = request_id.to_owned();- // Only a short, generic meme concept derived from this is searched.- let moment = user_message.to_owned();- crate::core::runtime::spawn_scoped(async move {- match host.engine.learn_memes(intent, &moment).await {- // The query is derived from the user's message, so it stays- // out of the log; only counters are recorded.- Ok(Some(r)) => log::info!(- "[tinymemes] meme research request_id={request_id} found={} \- added={} rejected_rating={} rejected_topic={} duplicates={} \- failed_jev={}",- r.found,- r.added,- r.rejected_rating,- r.rejected_topic,- r.duplicates,- r.failed_verification- ),- Ok(None) => {- log::debug!("[tinymemes] meme research skipped (repeat, budget, or busy)")- }- Err(e) => log::warn!("[tinymemes] meme research failed: {e}"),- }- persist(&host, |h| h.save_memes()).await;- });- }- }-- let result = if remixed {- let id = crate::threads::store::run_reply_message_id(request_id);- persist(host, move |h| {- h.mark_remixed(id);- h.save_index();- h.save_memes();- })- .await;"remixed"- } else if outcome.skipped.is_some() && outcome.rating.is_none() {- "error"} else {- "unchanged"+ match response.skipped {+ Some(SkipReason::Timeout) => "timeout",+ Some(SkipReason::Failed) => "error",+ _ => "unchanged",+ }};- log_outcome(turn, started, result, Some(&outcome));- remixed.then_some(outcome.reply)-}--/// Run state-file writes on the blocking pool: they are synchronous-/// serialization and file I/O, and must not stall an async worker.-async fn persist(- host: &std::sync::Arc<host::Host>,- write: impl FnOnce(&host::Host) + Send + 'static,-) {- let host = host.clone();- if let Err(e) = crate::core::runtime::spawn_blocking_scoped(move || write(&host)).await {- log::warn!("[tinymemes] state write task failed: {e}");- }+ log_outcome(turn, started, result, Some(&response));+ changed.then_some(response.reply)}fn log_outcome(turn: &TurnInfo<'_>,started: Instant,result: &str,- outcome: Option<&tinymemes::Outcome>,+ response: Option<&RemixResponse>,) {log::info!("{}",- turn_line(turn, started.elapsed().as_millis(), result, outcome)+ turn_line(turn, started.elapsed().as_millis(), result, response));}@@ -319,55 +290,28 @@ fn turn_line(turn: &TurnInfo<'_>,remix_ms: u128,result: &str,- outcome: Option<&tinymemes::Outcome>,+ response: Option<&RemixResponse>,) -> String {let TurnInfo {request_id,bucket,turn_ms,} = *turn;- let rating = outcome.and_then(|o| o.rating);- let remix = outcome.and_then(|o| o.remix.as_ref());- let reading = outcome.and_then(|o| o.reading.as_ref());format!("[tinymemes] turn arm=treatment bucket={bucket} request_id={request_id} turn_ms={turn_ms} \- remix_ms={remix_ms} outcome={result} score={} tier={} mode={} memes={} rewrite_kept={} \- dupes={} slang_enough={} wants_search={} meme_pick={} meme_p={} matches={}",- rating.map_or(-1, |r| i32::from(r.score)),- rating.map_or("none", |r| match r.tier {- tinymemes::Tier::Off => "off",- tinymemes::Tier::Light => "light",- tinymemes::Tier::Spicy => "spicy",- tinymemes::Tier::Unhinged => "unhinged",- }),- remix.map_or("none", |r| match r.mode {- tinymemes::RemixMode::Rewrite => "rewrite",- tinymemes::RemixMode::MemeOnly => "meme_only",- }),- remix.map_or(0, |r| r.memes.len()),- remix.is_none_or(|r| r.rewrite_kept),- remix.map_or(0, |r| r.duplicates_removed),- reading- .and_then(|r| r.slang_enough)- .map_or_else(|| "none".to_owned(), |p| format!("{p:.2}")),- reading.is_some_and(|r| r.wants_more_slang(0.5)),- reading.map_or_else(- || "none".to_owned(),- |r| match &r.meme {- tinymemes::reading::MemePick::Pick(t) => t.replace(' ', "_"),- tinymemes::reading::MemePick::NoneFit => match &r.meme_weak {- Some(t) => format!("weak:{}", t.replace(' ', "_")),- None => "none_fit".to_owned(),- },- tinymemes::reading::MemePick::Unasked => "unasked".to_owned(),- }- ),- reading- .and_then(|r| r.meme_p)- .map_or_else(|| "none".to_owned(), |p| format!("{p:.2}")),- reading- .and_then(|r| r.reply_matches_user)- .map_or_else(|| "none".to_owned(), |p| format!("{p:.2}")),+ remix_ms={remix_ms} outcome={result} score={} skipped={} wants_more_memes={}",+ response+ .and_then(|r| r.score)+ .map_or(-1, i32::from),+ response+ .and_then(|r| r.skipped)+ .map_or("none", |s| match s {+ SkipReason::Disabled => "disabled",+ SkipReason::BelowThreshold => "below_threshold",+ SkipReason::Timeout => "timeout",+ SkipReason::Failed => "failed",+ }),+ response.is_some_and(|r| r.wants_more_memes),)}diff --git a/crates/openhuman-core/src/tinymemes/mod_tests.rs b/crates/openhuman-core/src/tinymemes/mod_tests.rsdeleted file mode 100644index 531c01f0b6..0000000000--- a/crates/openhuman-core/src/tinymemes/mod_tests.rs+++ /dev/null@@ -1,414 +0,0 @@-use super::*;--use std::collections::{BTreeMap, VecDeque};-use std::sync::Arc;--use async_trait::async_trait;-use tinymemes::decisions::{- Answer, ChoiceAnswer, EvaluationRequest, EvaluationResponse, NoulAnswer, ScoreAnswer, Usage,-};-use tinymemes::{BoxError, ChatModel, Evaluator, MemeEngine, Region};--use crate::threads::store::ConversationMessage;--/// Answers every reading question the same way, whatever the chat.-struct ScriptedJev {- frankness: f64,- playful: f64,- serious: f64,- slang_enough: f64,- meme: Option<&'static str>,-}--#[async_trait]-impl Evaluator for ScriptedJev {- async fn evaluate(&self, request: &EvaluationRequest) -> Result<EvaluationResponse, BoxError> {- let choice = |c: &str| {- Answer::Choice(ChoiceAnswer {- choice: c.to_owned(),- probabilities: BTreeMap::new(),- confidence: 0.9,- })- };- let noul = |p: f64| Answer::Noul(NoulAnswer { noul: p });- let mut answers = BTreeMap::from([- ("chat_intent".to_owned(), choice("celebration")),- ("reply_intent".to_owned(), choice("celebration")),- (- "frankness".to_owned(),- Answer::Score(ScoreAnswer {- score: self.frankness * 4.0,- legend: BTreeMap::new(),- probabilities: BTreeMap::new(),- confidence: 0.8,- }),- ),- ("playful".to_owned(), noul(self.playful)),- ("serious".to_owned(), noul(self.serious)),- ]);- if request.questions.contains_key("slang_enough") {- answers.insert("slang_enough".to_owned(), noul(self.slang_enough));- answers.insert("slang_best".to_owned(), choice("yaar"));- }- if let (Some(meme), true) = (self.meme, request.questions.contains_key("meme_best")) {- answers.insert("meme_best".to_owned(), choice(meme));- }- Ok(EvaluationResponse {- model: "jev-latest".into(),- answers,- usage: Usage::default(),- })- }-}--struct FailingJev;--#[async_trait]-impl Evaluator for FailingJev {- async fn evaluate(&self, _: &EvaluationRequest) -> Result<EvaluationResponse, BoxError> {- Err("jev down".into())- }-}--/// Returns a fixed rewrite, after an optional delay.-struct ScriptedModel {- rewrite: &'static str,- delay: Duration,-}--#[async_trait]-impl ChatModel for ScriptedModel {- async fn complete(&self, _system: &str, _user: &str) -> Result<String, BoxError> {- tokio::time::sleep(self.delay).await;- Ok(self.rewrite.to_owned())- }-}--fn frank(slang_enough: f64) -> Arc<ScriptedJev> {- Arc::new(ScriptedJev {- frankness: 0.95,- playful: 0.95,- serious: 0.0,- slang_enough,- meme: None,- })-}--fn model(rewrite: &'static str) -> Arc<ScriptedModel> {- Arc::new(ScriptedModel {- rewrite,- delay: Duration::ZERO,- })-}--fn host(- dir: &tempfile::TempDir,- jev: Arc<dyn Evaluator>,- chat: Arc<dyn ChatModel>,- region: Option<Region>,-) -> Arc<host::Host> {- let mut builder = MemeEngine::builder(jev, chat).learn_inline(None);- if let Some(region) = region {- builder = builder.region(region);- }- Arc::new(host::Host::new(- builder.build(),- dir.path().to_path_buf(),- VecDeque::new(),- 0,- ))-}--fn config_in(dir: &std::path::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 turn(request_id: &str) -> TurnInfo<'_> {- TurnInfo {- request_id,- bucket: 7,- turn_ms: 1200,- }-}--fn msg(id: &str, sender: &str, content: &str) -> ConversationMessage {- ConversationMessage {- id: id.to_owned(),- content: content.to_owned(),- message_type: "text".to_owned(),- extra_metadata: serde_json::Value::Null,- sender: sender.to_owned(),- created_at: "2026-10-09T00:00:00Z".to_owned(),- }-}--fn thread() -> Vec<ConversationMessage> {- vec![- msg("u1", "user", "yo the deploy finally went green lmaooo"),- msg("r1", "agent", "Nice. Want me to tag the release?"),- ]-}--const REPLY: &str = "Done. Tagged the release.";-const REWRITE: &str = "Done bhai, release tagged, full send 🎉";--/// Let spawned research tasks run to completion.-async fn settle() {- for _ in 0..20 {- tokio::task::yield_now().await;- tokio::time::sleep(Duration::from_millis(5)).await;- }-}--#[test]-fn only_real_answers_are_remixed() {- let placeholder = "You've hit your inference budget.";- assert!(should_remix("Here's the fix.", placeholder));- assert!(!should_remix("", placeholder));- assert!(!should_remix(" \n", placeholder));- assert!(!should_remix(placeholder, placeholder));-}--#[test]-fn only_the_treatment_arm_passes_the_gate() {- let t = turn("req-gate");- assert!(!gate(Arm::Disabled, &t));- assert!(!gate(Arm::Control, &t));- assert!(gate(Arm::Treatment, &t));-}--#[test]-fn the_budget_defaults_to_twenty_seconds() {- if std::env::var(TIMEOUT_ENV).is_err() {- assert_eq!(budget(), DEFAULT_TIMEOUT);- }-}--#[tokio::test]-async fn a_disabled_flag_leaves_the_task_reply_alone() {- // The flag is unset in tests, so every thread is in the disabled arm.- if std::env::var(arm::FLAG_ENV).is_ok() {- return;- }- assert!(!holds_text_stream("thread-1"));- let dir = tempfile::TempDir::new().unwrap();- let config = config_in(dir.path());- let mut reply = REPLY.to_owned();- remix_task_reply(- &config,- "thread-1",- "req-1",- "tag it",- &mut reply,- "placeholder",- Duration::from_millis(5),- )- .await;- assert_eq!(reply, REPLY);-- let mut empty = String::new();- remix_task_reply(- &config,- "thread-1",- "req-1",- "tag it",- &mut empty,- "placeholder",- Duration::ZERO,- )- .await;- assert!(empty.is_empty());-}--#[tokio::test]-async fn load_builds_the_engine_once_per_workspace() {- let dir = tempfile::TempDir::new().unwrap();- let config = config_in(dir.path());- let (first, _messages) = load(&config, "thread-missing").await.expect("engine");- let (second, _) = load(&config, "thread-missing").await.expect("engine");- assert!(Arc::ptr_eq(&first, &second), "the engine was rebuilt");- assert!(dir.path().join("workspace").join("tinymemes").is_dir());-}--#[tokio::test]-async fn a_frank_chat_is_remixed_and_remembered() {- let dir = tempfile::TempDir::new().unwrap();- let host = host(&dir, frank(0.9), model(REWRITE), Some(Region::global()));- let out = remix_with(- &host,- &thread(),- &turn("req-remix"),- Instant::now(),- "ya send it",- REPLY,- Duration::from_secs(5),- )- .await- .expect("remixed");- assert_ne!(out.trim(), REPLY);- // The delivered message is remembered as remixed, and state is saved.- let id = crate::threads::store::run_reply_message_id("req-remix");- assert!(host.is_remixed(&id));- let remixed: Vec<String> =- serde_json::from_str(&std::fs::read_to_string(dir.path().join("remixed.json")).unwrap())- .unwrap();- assert_eq!(remixed, [id]);- assert!(dir.path().join("slang-index.json").exists());- assert!(dir.path().join("meme-index.json").exists());-}--#[tokio::test]-async fn a_short_slang_index_researches_after_delivery() {- let dir = tempfile::TempDir::new().unwrap();- // Jev judges the index short of slang; with no researcher configured the- // background task finds nothing to do and the reply still goes out.- let host = host(&dir, frank(0.05), model(REWRITE), Some(Region::global()));- let out = remix_with(- &host,- &thread(),- &turn("req-slang"),- Instant::now(),- "ya send it",- REPLY,- Duration::from_secs(5),- )- .await;- assert!(out.is_some());- settle().await;- assert!(dir.path().join("slang-index.json").exists());-}--#[tokio::test]-async fn no_fitting_meme_starts_meme_research() {- let dir = tempfile::TempDir::new().unwrap();- let jev = Arc::new(ScriptedJev {- meme: Some(tinymemes::reading::NONE_FIT),- ..*frank(0.9)- });- // The default (India) region offers catalog memes, so Jev is asked to- // pick one and answers that none fit.- let host = host(&dir, jev, model(REWRITE), None);- let _ = remix_with(- &host,- &thread(),- &turn("req-meme"),- Instant::now(),- "ya send it",- REPLY,- Duration::from_secs(5),- )- .await;- settle().await;- assert!(dir.path().join("meme-index.json").exists());-}--#[tokio::test]-async fn an_off_rated_chat_is_left_unchanged() {- let dir = tempfile::TempDir::new().unwrap();- let jev = Arc::new(ScriptedJev {- frankness: 0.0,- playful: 0.0,- serious: 0.9,- slang_enough: 0.9,- meme: None,- });- let host = host(&dir, jev, model(REWRITE), Some(Region::global()));- let out = remix_with(- &host,- &thread(),- &turn("req-off"),- Instant::now(),- "ya send it",- REPLY,- Duration::from_secs(5),- )- .await;- assert_eq!(out, None);- assert!(!dir.path().join("remixed.json").exists());-}--#[tokio::test]-async fn a_jev_failure_sends_the_original() {- let dir = tempfile::TempDir::new().unwrap();- let host = host(&dir, Arc::new(FailingJev), model(REWRITE), None);- let out = remix_with(- &host,- &thread(),- &turn("req-error"),- Instant::now(),- "ya send it",- REPLY,- Duration::from_secs(5),- )- .await;- assert_eq!(out, None);-}--#[tokio::test]-async fn a_slow_remix_times_out_to_the_original() {- let dir = tempfile::TempDir::new().unwrap();- let slow = Arc::new(ScriptedModel {- rewrite: REWRITE,- delay: Duration::from_secs(5),- });- let host = host(&dir, frank(0.9), slow, Some(Region::global()));- let out = remix_with(- &host,- &thread(),- &turn("req-timeout"),- Instant::now(),- "ya send it",- REPLY,- Duration::from_millis(50),- )- .await;- assert_eq!(out, None);-}--#[test]-fn the_log_line_handles_a_missing_outcome() {- // Exercised for its formatting paths; it must not panic without a reading.- log_outcome(&turn("req-log"), Instant::now(), "engine_unavailable", None);-}--#[tokio::test]-async fn the_turn_line_reports_the_outcome_without_user_content() {- let dir = tempfile::TempDir::new().unwrap();- let host = host(&dir, frank(0.9), model(REWRITE), Some(Region::global()));- let turns = host::history_turns(&thread(), "ya send it", |_| false);- let outcome = host.engine.process(&turns, REPLY).await;- let line = turn_line(&turn("req-line"), 42, "remixed", Some(&outcome));- assert!(line.starts_with("[tinymemes] turn arm=treatment bucket=7 request_id=req-line"));- assert!(line.contains("turn_ms=1200 remix_ms=42 outcome=remixed"));- assert!(line.contains("tier=unhinged"), "{line}");- assert!(!line.contains("send it") && !line.contains("Tagged"));-- let bare = turn_line(&turn("req-none"), 0, "timeout", None);- assert!(bare.contains("score=-1 tier=none mode=none memes=0 rewrite_kept=true dupes=0"));- assert!(bare.contains("meme_pick=none meme_p=none matches=none"));-}--#[tokio::test]-async fn every_arm_fails_open_without_working_providers() {- let dir = tempfile::TempDir::new().unwrap();- let config = config_in(dir.path());- for arm in [Arm::Disabled, Arm::Control, Arm::Treatment] {- // Treatment builds the real engine; with no provider configured every- // model call fails, so the original reply is delivered.- let out = remix_final_reply(- arm,- &config,- "thread-real",- "req-real",- "ya send it",- REPLY,- Duration::from_millis(5),- )- .await;- assert_eq!(out, None, "{arm:?}");- }-}diff --git a/crates/openhuman-core/src/tinymemes/remixed.rs b/crates/openhuman-core/src/tinymemes/remixed.rsnew file mode 100644index 0000000000..e4fbbd126c--- /dev/null+++ b/crates/openhuman-core/src/tinymemes/remixed.rs@@ -0,0 +1,89 @@+//! 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;