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
Merge remote-tracking branch 'refs/remotes/prereq97/host97-merged' into epic-8055-prereq97-integration
Steven Enamakel2f52d0cca6ea
diff --cc Cargo.lockindex 7cda7ed566,42155e2b6c..6dbb7c336e--- a/Cargo.lock+++ b/Cargo.lock@@@ -5559,8 -5558,8 +5559,9 @@@ dependencies ="tinyinference-local","tinyinference-voice","tinymcp-bus",+ "tinymemory-tools","tinysearch-bus",+ "tinystoragedrivers","tinystoragedrivers-core","tinytools","tinytools-agent",diff --cc crates/openhuman-core/src/channels/controllers/ops/connect/memory_tests.rsindex 8bf030eb22,6dc580d807..03a2f86a8d--- a/crates/openhuman-core/src/channels/controllers/ops/connect/memory_tests.rs+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/memory_tests.rs@@@ -1,11 -1,20 +1,21 @@@use super::*;+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};+ use crate::threads::store::{+ ConversationMessage, ConversationMessagePatch, CreateConversationThread,+ };+ use serde_json::json;++use std::collections::{BTreeMap, BTreeSet};use std::sync::Arc;use tinymemory_api::conformance::ReferenceEngine;- use tinymemory_api::{MemoryEngine, MemoryMeta, Role, SourceKind, StoreItem, Turn};+ use tinymemory_api::{+ ItemKind, LearningKind, ListRequest, MemoryEngine, MemoryMeta, MetaFilter, Role, SourceKind,+ StoreItem, Turn,+ };- fn conversation(thread: &str) -> StoreItem {+ fn conversation(thread: &str, channel: Option<&str>) -> StoreItem {let mut meta = MemoryMeta::from_source(SourceKind::Conversation, Some(thread.to_string()));meta.thread_id = Some(thread.to_string());+ meta.channel = channel.map(str::to_string);StoreItem::Conversation {turns: vec![Turn::new(Role::User, format!("hello from {thread}"))],meta,@@@ -17,16 -105,452 +106,477 @@@ async fn clears_stamped_and_legacy_chanlet tmp = tempfile::TempDir::new().unwrap();let mut config = Config::default();config.workspace_dir = tmp.path().to_path_buf();+ use_linked_channel_module(&mut config).await;let engine = Arc::new(ReferenceEngine::new());crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());- engine.store(conversation("discord-1")).await.unwrap();- engine.store(conversation("telegram-1")).await.unwrap();- crate::memory::channels::record(&config.workspace_dir, "Discord", "discord-1");- crate::memory::channels::record(&config.workspace_dir, "telegram", "telegram-1");+ let discord_thread = store_channel_thread(+ DispatchCtx::ambient(),+ &config.workspace_dir,+ "discord",+ "discord-current",+ )+ .await;+ store_channel_thread(+ DispatchCtx::ambient(),+ &config.workspace_dir,+ "telegram",+ "telegram-current",+ )+ .await;+ engine+ .store(conversation(&discord_thread, Some("discord")))+ .await+ .unwrap();+ engine+ .store(conversation("discord-legacy", None))+ .await+ .unwrap();+ engine+ .store(StoreItem::learning(+ "durable preference",+ LearningKind::Preference,+ 0.9,+ MemoryMeta {+ thread_id: Some(discord_thread.clone()),+ channel: Some("discord".into()),+ ..MemoryMeta::default()+ },+ ))+ .await+ .unwrap();+ engine+ .store(StoreItem::document(+ "durable brain document",+ MemoryMeta {+ thread_id: Some(discord_thread.clone()),+ channel: Some("discord".into()),+ ..MemoryMeta::default()+ },+ ))+ .await+ .unwrap();+ engine+ .store(conversation("telegram-current", Some("telegram")))+ .await+ .unwrap();+ let legacy_file = config.workspace_dir.join("memory/channel_threads.json");+ std::fs::create_dir_all(legacy_file.parent().unwrap()).unwrap();+ let legacy_bytes = br#"{"discord":["discord-legacy"]}"#;+ std::fs::write(&legacy_file, legacy_bytes).unwrap();++ assert_eq!(clear_channel_memory(&config, "discord").await.unwrap(), 2);+ assert_eq!(+ engine.len(),+ 3,+ "other-channel and non-conversation items remain"+ );+ let remaining = engine+ .list(ListRequest {+ filter: MetaFilter::default(),+ limit: 100,+ cursor: None,+ })+ .await+ .unwrap()+ .items;+ assert!(remaining+ .iter()+ .any(|item| { item.kind == ItemKind::Learning && item.text == "durable preference" }));+ assert!(remaining+ .iter()+ .any(|item| { item.kind == ItemKind::Document && item.text == "durable brain document" }));+ assert!(remaining.iter().any(|item| {+ item.kind == ItemKind::Conversation+ && item.meta.thread_id.as_deref() == Some("telegram-current")+ }));+ assert_eq!(std::fs::read(&legacy_file).unwrap(), legacy_bytes);+ }+++#[tokio::test]++async fn channel_cleanup_reads_legacy_threads_after_state_migration() {++ let tmp = tempfile::TempDir::new().unwrap();++ let mut config = Config::default();++ config.workspace_dir = tmp.path().to_path_buf();++ use_linked_channel_module(&mut config).await;++ let engine = Arc::new(ReferenceEngine::new());++ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());++ engine++ .store(conversation("discord-legacy", None))++ .await++ .unwrap();++++ let legacy_file = config.workspace_dir.join("memory/channel_threads.json");++ std::fs::create_dir_all(legacy_file.parent().unwrap()).unwrap();++ std::fs::write(&legacy_file, br#"{"discord":["discord-legacy"]}"#).unwrap();++ let imported: Option<BTreeMap<String, BTreeSet<String>>> =++ crate::memory::state_store::load(&config.workspace_dir, "channel_threads").unwrap();++ assert!(imported.is_some());++ std::fs::remove_file(&legacy_file).unwrap();++ assert_eq!(clear_channel_memory(&config, "discord").await.unwrap(), 1);++ assert!(engine.is_empty());++}+++ #[tokio::test]+ async fn stamped_channel_forget_isolated_to_the_configured_account() {+ let current_tmp = tempfile::TempDir::new().unwrap();+ let other_tmp = tempfile::TempDir::new().unwrap();+ let mut current = Config::default();+ current.workspace_dir = current_tmp.path().to_path_buf();+ current.memory.engine.clear();+ use_linked_channel_module(&mut current).await;+ let mut other = Config::default();+ other.workspace_dir = other_tmp.path().to_path_buf();+ other.memory.engine.clear();+ let current_ctx = account_context(¤t.workspace_dir, "account-a");+ let other_ctx = account_context(&other.workspace_dir, "account-b");+ let current_thread = store_channel_thread(+ current_ctx.clone(),+ ¤t.workspace_dir,+ "discord",+ "current-account",+ )+ .await;+ let other_thread = store_channel_thread(+ other_ctx.clone(),+ &other.workspace_dir,+ "discord",+ "other-account",+ )+ .await;++ assert_eq!(+ CoreContext::scope(current_ctx.into_core().unwrap(), async {+ clear_channel_memory(¤t, "discord").await.unwrap()+ })+ .await,+ 0+ );+ assert_eq!(+ crate::memory::deletion::pending(¤t.workspace_dir),+ vec![crate::memory::deletion::PendingDeletion::Thread {+ thread_id: current_thread.clone()+ }]+ );+ assert!(crate::memory::deletion::pending(&other.workspace_dir).is_empty());+ assert_ne!(current_thread, other_thread);+ }++ #[tokio::test]+ async fn missing_or_corrupt_legacy_map_does_not_block_stamped_forget() {+ for corrupt in [false, true] {+ let tmp = tempfile::TempDir::new().unwrap();+ let mut config = Config::default();+ config.workspace_dir = tmp.path().to_path_buf();+ use_linked_channel_module(&mut config).await;+ let engine = Arc::new(ReferenceEngine::new());+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());+ let thread_id = store_channel_thread(+ DispatchCtx::ambient(),+ &config.workspace_dir,+ "discord",+ "discord-current",+ )+ .await;+ engine+ .store(conversation(&thread_id, Some("discord")))+ .await+ .unwrap();+ let legacy_file = config.workspace_dir.join("memory/channel_threads.json");+ let corrupt_bytes = b"{not-json";+ if corrupt {+ std::fs::create_dir_all(legacy_file.parent().unwrap()).unwrap();+ std::fs::write(&legacy_file, corrupt_bytes).unwrap();+ }++ assert_eq!(clear_channel_memory(&config, "discord").await.unwrap(), 1);+ assert!(engine.is_empty());+ if corrupt {+ assert!(!legacy_file.exists());+ assert_eq!(+ std::fs::read(legacy_file.with_extension("json.corrupt")).unwrap(),+ corrupt_bytes+ );+ } else {+ assert!(!legacy_file.exists());+ }+ }+ }++ #[tokio::test]+ async fn memory_off_queues_channel_threads_from_the_canonical_thread_store() {+ let tmp = tempfile::TempDir::new().unwrap();+ let mut config = Config::default();+ config.workspace_dir = tmp.path().to_path_buf();+ config.memory.engine.clear();+ use_linked_channel_module(&mut config).await;+ let thread_id = store_channel_thread(+ DispatchCtx::ambient(),+ &config.workspace_dir,+ "discord",+ "discord-offline",+ )+ .await;++ assert_eq!(clear_channel_memory(&config, "discord").await.unwrap(), 0);+ assert_eq!(+ crate::memory::deletion::pending(&config.workspace_dir),+ vec![crate::memory::deletion::PendingDeletion::Thread { thread_id }]+ );+ }++ #[tokio::test]+ async fn reserved_channel_thread_id_survives_metadata_edit_without_prefix_collision() {+ let tmp = tempfile::TempDir::new().unwrap();+ let mut config = Config::default();+ config.workspace_dir = tmp.path().to_path_buf();+ config.memory.engine.clear();+ use_linked_channel_module(&mut config).await;+ let ctx = DispatchCtx::ambient();+ let target = store_channel_thread(+ ctx.clone(),+ &config.workspace_dir,+ "discord",+ "stripped-channel-meta",+ )+ .await;+ let collision = store_channel_thread(+ ctx.clone(),+ &config.workspace_dir,+ "discordish",+ "prefix-collision",+ )+ .await;+ for (thread_id, message_id) in [+ (&target, "user:stripped-channel-meta"),+ (&collision, "user:prefix-collision"),+ ] {+ crate::threads::store::blocking::update_message(+ ctx.clone(),+ config.workspace_dir.clone(),+ thread_id.clone(),+ message_id.into(),+ ConversationMessagePatch {+ extra_metadata: Some(json!({"scope": "web"})),+ },+ )+ .await+ .unwrap();+ }+ let messages = crate::threads::store::blocking::get_messages(+ ctx,+ config.workspace_dir.clone(),+ target.clone(),+ )+ .await+ .unwrap();+ assert!(messages[0].extra_metadata.get("channel").is_none());++ assert_eq!(clear_channel_memory(&config, "discord").await.unwrap(), 0);+ assert_eq!(+ crate::memory::deletion::pending(&config.workspace_dir),+ vec![crate::memory::deletion::PendingDeletion::Thread { thread_id: target }]+ );+ }++ #[tokio::test]+ async fn offline_snapshot_scans_every_thread_and_message_page() {+ let tmp = tempfile::TempDir::new().unwrap();+ let mut config = Config::default();+ config.workspace_dir = tmp.path().to_path_buf();+ config.memory.engine.clear();+ use_linked_channel_module(&mut config).await;+ let workspace = config.workspace_dir.clone();+ let ctx = DispatchCtx::ambient();+ let params = crate::channels::providers::relay::RelayInboundParams::new(+ "discord",+ "chat-old-channel-message",+ "sender-old-channel-message",+ "old-channel-message",+ "hello from discord",+ );+ let target_thread = "zz-legacy-channel-thread".to_owned();+ crate::threads::store::blocking::ensure_thread(+ ctx.clone(),+ workspace.clone(),+ CreateConversationThread {+ id: target_thread.clone(),+ title: params.thread_title(),+ created_at: "2026-01-01T00:00:00Z".into(),+ parent_thread_id: None,+ labels: Some(vec!["general".into()]),+ personality_id: None,+ working_dir: None,+ },+ )+ .await+ .unwrap();++ for index in 0..64 {+ crate::threads::store::blocking::append_message(+ ctx.clone(),+ workspace.clone(),+ target_thread.clone(),+ ConversationMessage {+ id: format!("web-before-{index}"),+ content: "unrelated web row before channel marker".into(),+ message_type: "text".into(),+ extra_metadata: json!({"scope": "web"}),+ sender: "user".into(),+ created_at: "2099-01-01T00:00:00Z".into(),+ },+ )+ .await+ .unwrap();+ }+ crate::threads::store::blocking::append_message(+ ctx.clone(),+ workspace.clone(),+ target_thread.clone(),+ ConversationMessage {+ id: "user:old-channel-message".into(),+ content: "hello from discord".into(),+ message_type: "text".into(),+ extra_metadata: json!({"scope": "channel", "channel": "discord"}),+ sender: "user".into(),+ created_at: "2099-01-01T00:00:00Z".into(),+ },+ )+ .await+ .unwrap();+ crate::threads::store::blocking::append_message(+ ctx.clone(),+ workspace.clone(),+ target_thread.clone(),+ ConversationMessage {+ id: "web-after-channel".into(),+ content: "later unrelated web row".into(),+ message_type: "text".into(),+ extra_metadata: json!({"scope": "web"}),+ sender: "user".into(),+ created_at: "2099-01-01T00:00:00Z".into(),+ },+ )+ .await+ .unwrap();+ for index in 0..65 {+ crate::threads::store::blocking::ensure_thread(+ ctx.clone(),+ workspace.clone(),+ CreateConversationThread {+ id: format!("web-thread-{index}"),+ title: format!("web {index}"),+ created_at: "2099-01-01T00:00:00Z".into(),+ parent_thread_id: None,+ labels: None,+ personality_id: None,+ working_dir: None,+ },+ )+ .await+ .unwrap();+ }++ let threads = crate::threads::store::blocking::list_threads(ctx.clone(), workspace.clone())+ .await+ .unwrap();+ assert_eq!(threads.len(), 66);+ assert!(threads[..64]+ .iter()+ .all(|thread| thread.id != target_thread));+ assert!(+ threads+ .iter()+ .position(|thread| thread.id == target_thread)+ .unwrap()+ >= 64+ );++ let messages = crate::threads::store::blocking::get_messages(+ ctx.clone(),+ workspace.clone(),+ target_thread.clone(),+ )+ .await+ .unwrap();+ assert_eq!(messages.len(), 66);+ assert!(messages[..64]+ .iter()+ .all(|message| message.extra_metadata.get("channel").is_none()));+ assert_eq!(messages[64].extra_metadata["channel"], "discord");+ assert!(messages[65].extra_metadata.get("channel").is_none());+ assert!(+ !workspace.join("memory/channel_threads.json").exists(),+ "the historical fallback fixture must not depend on the legacy map"+ );++ assert_eq!(clear_channel_memory(&config, "discord").await.unwrap(), 0);+ assert_eq!(+ crate::memory::deletion::pending(&config.workspace_dir),+ vec![crate::memory::deletion::PendingDeletion::Thread {+ thread_id: target_thread+ }]+ );+ }++ #[tokio::test]+ async fn filter_failure_is_visible_and_queued_snapshot_does_not_catch_reconnected_threads() {+ let tmp = tempfile::TempDir::new().unwrap();+ let mut config = Config::default();+ config.workspace_dir = tmp.path().to_path_buf();+ use_linked_channel_module(&mut config).await;+ let old_thread = store_channel_thread(+ DispatchCtx::ambient(),+ &config.workspace_dir,+ "discord",+ "before-disconnect",+ )+ .await;+ crate::memory::test_fixtures::RefusingEngine::with(tinymemory_api::Error::Engine(+ "forget failed".into(),+ ))+ .bind(&config);++ let error = clear_channel_memory(&config, "discord")+ .await+ .expect_err("a failed filter forget stays visible to disconnect");+ assert!(error.to_string().contains("clear_channel_memory"));+ assert_eq!(+ crate::memory::deletion::pending(&config.workspace_dir),+ vec![crate::memory::deletion::PendingDeletion::Thread {+ thread_id: old_thread.clone()+ }]+ );++ let new_thread = store_channel_thread(+ DispatchCtx::ambient(),+ &config.workspace_dir,+ "discord",+ "after-reconnect",+ )+ .await;+ let engine = Arc::new(ReferenceEngine::new());+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());+ engine+ .store(conversation(&old_thread, Some("discord")))+ .await+ .unwrap();+ engine+ .store(conversation(&new_thread, Some("discord")))+ .await+ .unwrap();++ assert_eq!(crate::memory::deletion::drain(&config).await, 1);assert_eq!(engine.len(), 1);- assert!(crate::memory::channels::threads_of(&config.workspace_dir, "discord").is_empty());+ let remaining = crate::memory::test_fixtures::stored(+ &engine,+ tinymemory_api::MetaFilter::kinds([tinymemory_api::ItemKind::Conversation]),+ )+ .await;+ assert_eq!(+ remaining[0].meta.thread_id.as_deref(),+ Some(new_thread.as_str())+ );}#[tokio::test]diff --cc crates/openhuman-core/src/flows/tinyflows/memory_adapter.rsindex 1f263bfe7f,8e0f6e7295..90bd57447d--- a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs+++ b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs@@@ -54,9 -53,10 +53,10 @@@ use crate::security::approval::use crate::security::SecurityPolicy;use tinybox_bus::CommandClass;use tinymemory_api::wrap_untrusted_for_agent;+ use tinymemory_api::Error;use tinymemory_api::{Hit, LearningKind, MemoryMeta, MetaFilter, SourceKind};-use super::caps::{enforce_node_tier_gate, gate_call_for_tier};+use super::caps::{enforce_current_node_tier_gate, gate_call_for_tier};/// Stable `tracing` grep prefix for every log line this adapter emits. Never/// logs memory *content* or PII — only operation names, scopes, resolveddiff --cc crates/openhuman-core/src/memory/deletion.rsindex 25a4be5af9,ce54723247..8912d6f05f--- a/crates/openhuman-core/src/memory/deletion.rs+++ b/crates/openhuman-core/src/memory/deletion.rs@@@ -4,7 -4,7 +4,7 @@@//! thread it owned) or removing a source asks the engine to delete for good. When memory is off//! (signed out, no credential) the engine cannot be reached, and when it//! fails the deletion has not happened. Either way the deletion is recorded--//! here, in `<workspace>/memory/pending_deletions.json`, and [`drain`] runs++//! here, in the workspace's `pending_deletions` state value, and [`drain`] runs//! it again on the next sign-in ([`super::bus`], on `CredentialChanged`) and//! on every background tick, until it succeeds.//!@@@ -25,33 -25,52 +25,33 @@@ pub use tinymemory_tools::deletion::Penuse crate::config::Config;use super::engine;- use super::error::{MemoryError, MemoryResult};+ use tinymemory_api::Error;-fn path(workspace_dir: &Path) -> PathBuf {- workspace_dir.join("memory").join("pending_deletions.json")-}+const STATE: &str = "pending_deletions";-/// `<workspace>/memory/pending_deletions.json`: owner-only, written through a-/// temporary file and a rename so a stop mid-write never loses the queue. An-/// unparsable file is set aside; an empty queue removes the file.+/// The workspace's `pending_deletions` state value: a stop mid-write never+/// loses the queue (the storage write is atomic). An unparsable value is+/// dropped and logged; an empty queue removes the value.struct FileStore {- file: PathBuf,+ workspace_dir: PathBuf,}impl ListStore<PendingDeletion> for FileStore {- fn load(&self) -> Result<Vec<PendingDeletion>, StoreError> {+ fn load(&self) -> std::result::Result<Vec<PendingDeletion>, StoreError> {- let Ok(text) = std::fs::read_to_string(&self.file) else {- return Ok(Vec::new());- };- Ok(serde_json::from_str(&text).unwrap_or_else(|error| {- tracing::warn!(%error, "[memory:deletion] pending deletions unparsable; set aside");- if let Err(error) =- std::fs::rename(&self.file, self.file.with_extension("json.corrupt"))- {- tracing::warn!(%error, "[memory:deletion] could not set the file aside");- }- Vec::new()- }))+ super::state_store::load(&self.workspace_dir, STATE)+ .map(Option::unwrap_or_default)- .or_else(|error| {- tracing::warn!(%error, "[memory:deletion] pending deletions unreadable; dropped");- Ok(Vec::new())++ .map_err(|error| {++ tracing::warn!(%error, "[memory:deletion] pending deletions unreadable");++ StoreError(error.to_string())+ })}- fn save(&self, all: &[PendingDeletion]) -> Result<(), StoreError> {+ fn save(&self, all: &[PendingDeletion]) -> std::result::Result<(), StoreError> {if all.is_empty() {- return match std::fs::remove_file(&self.file) {- Ok(()) => Ok(()),- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),- Err(error) => Err(StoreError(error.to_string())),- };+ return super::state_store::remove(&self.workspace_dir, STATE)+ .map_err(|error| StoreError(error.to_string()));}- let temp = self.file.with_extension("json.tmp");- self.file- .parent()- .map_or(Ok(()), super::files::create_private_dir_all)- .and_then(|()| {- let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;- super::files::write_private(&temp, &json)?;- std::fs::rename(&temp, &self.file)- })+ super::state_store::save(&self.workspace_dir, STATE, &all).map_err(|error| StoreError(error.to_string()))}}diff --cc crates/openhuman-core/src/memory/import.rsindex 72ae15e249,e54be80494..f6e4ea7f45--- a/crates/openhuman-core/src/memory/import.rs+++ b/crates/openhuman-core/src/memory/import.rs@@@ -3,7 -3,7 +3,7 @@@//! The driver (batching, checkpoints, backoff, failed-item list, retry) is//! `tinymemory_integrations::import::Importer`. This file is the host//! adapter around it: the consent gate, the one-run-per-workspace registry,--//! the atomic state file `<workspace>/memory/import_state.json`, the tokio++//! the `memory`/`state`/`import_state` storage value, the tokio//! clock, the scheduler pause, the credits resume policy, and what follows a//! finished import (organizing the tree).@@@ -17,10 -18,11 +18,10 @@@ use tinymemory_integrations::import::};use crate::config::Config;-use crate::security::secret_storage::file_store::write_atomic;use super::engine;- use super::error::{MemoryError, MemoryResult};- use super::types::{ImportCounts, ImportPhase, ImportScanView, ImportState};+ use super::types::{ImportCounts, ImportScanView};+ use tinymemory_api::{Error, Result};/// Whether background work is paused right now. An automatic resume asks/// before it starts and again before every batch it stores.@@@ -52,15 -54,13 +53,14 @@@ fn release(workspace_dir: &Path).remove(workspace_dir);}--/// The state file, written atomically (staged, synced, renamed): a crash--/// mid-write leaves the previous state, never a torn file that reads back as--/// a fresh start and re-sends everything.++/// The state value: storage writes are atomic, so a crash mid-write leaves++/// the previous state or the new state rather than a fresh start.pub(crate) struct FileCheckpointStore {- path: PathBuf,+ workspace_dir: PathBuf,}+const STATE: &str = "import_state";+impl FileCheckpointStore {pub(crate) fn new(workspace_dir: &Path) -> Self {Self {diff --cc crates/openhuman-core/src/memory/layout_migration/state.rsindex 6734c7248a,4c45af42e3..18d71e8781--- a/crates/openhuman-core/src/memory/layout_migration/state.rs+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs@@@ -7,20 -6,15 +7,20 @@@use std::path::{Path, PathBuf};- use tinymemory_tools::layout_migration::{Error, Result};+ use tinymemory_tools::layout_migration::{Error as MigrationError, Result as MigrationResult};use super::{MigrationState, MigrationStateStore};- use crate::memory::error::{MemoryError, MemoryResult};+ use tinymemory_api::{Error, Result};-/// The state file of `workspace_dir`.+const STATE: &str = "layout_migration";++/// Whether a migration state exists in `workspace_dir`: the migration has+/// begun there (a state that cannot be read counts: it was begun).#[must_use]-pub fn path(workspace_dir: &Path) -> PathBuf {- workspace_dir.join("memory").join("layout_migration.json")+pub fn exists(workspace_dir: &Path) -> bool {+ crate::memory::state_store::load_strict::<serde_json::Value>(workspace_dir, STATE)+ .map(|state| state.is_some())+ .unwrap_or(true)}/// The migration state kept in one workspace.@@@ -60,26 -54,39 +60,23 @@@ fn detail(error: Error) -> String////// # Errors///-/// A state file that cannot be read or parsed: the migration must not start-/// over and copy everything again on a damaged file.+/// A state that cannot be read or parsed: the migration must not start+/// over and copy everything again on a damaged value.- pub fn load(workspace_dir: &Path) -> MemoryResult<MigrationState> {+ pub fn load(workspace_dir: &Path) -> Result<MigrationState> {- let file = path(workspace_dir);- match std::fs::read(&file) {- Ok(bytes) => serde_json::from_slice(&bytes)- .map_err(|error| Error::Engine(format!("layout migration state unreadable: {error}"))),- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(MigrationState::default()),- Err(error) => Err(Error::Engine(format!(- "layout migration state unreadable: {error}"- ))),- }+ crate::memory::state_store::load_strict(workspace_dir, STATE)+ .map(Option::unwrap_or_default)- .map_err(|error| {- MemoryError::Engine(format!("layout migration state unreadable: {error:#}"))- })++ .map_err(|error| Error::Engine(format!("layout migration state unreadable: {error:#}")))}-/// Saves `state` whole: a temporary file, synced, then renamed over the old.+/// Saves `state` whole (one storage write, so a crash leaves the previous+/// state or the new one).////// # Errors///-/// When the file cannot be written.+/// When the state cannot be written.- pub fn save(workspace_dir: &Path, state: &MigrationState) -> MemoryResult<()> {- crate::memory::state_store::save(workspace_dir, STATE, state).map_err(|error| {- MemoryError::Engine(format!("layout migration state not saved: {error:#}"))- })+ pub fn save(workspace_dir: &Path, state: &MigrationState) -> Result<()> {- let file = path(workspace_dir);- let write = || -> std::io::Result<()> {- if let Some(dir) = file.parent() {- crate::memory::files::create_private_dir_all(dir)?;- }- let temp = file.with_extension("json.tmp");- let bytes = serde_json::to_vec_pretty(state).map_err(std::io::Error::other)?;- let mut out = crate::memory::files::create_private(&temp)?;- std::io::Write::write_all(&mut out, &bytes)?;- out.sync_all()?;- std::fs::rename(&temp, &file)- };- write().map_err(|error| Error::Engine(format!("layout migration state not saved: {error}")))++ crate::memory::state_store::save(workspace_dir, STATE, state)++ .map_err(|error| Error::Engine(format!("layout migration state not saved: {error:#}")))}#[cfg(test)]diff --cc crates/openhuman-core/src/memory/lifecycle/jobs.rsindex 69288a4853,6cf8f903a2..c9a5bc1e64--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs@@@ -1,14 -1,14 +1,15 @@@//! The background job queue: the slow memory work TinyMemory hands back.//!//! The queue itself (dedupe, retry, history) is `tinymemory_tools::queue`;--//! this module is the host adapter: one queue per workspace over a file- //! store (the `memory`/`state`/`jobs` storage value), the engine and `[memory.recall]-//! store (`<workspace>/memory/jobs.json`), the engine and `[memory.recall]--//! build_delay_secs` it runs against, and the `memory_background` cron hook.++//! this module is the host adapter: one queue per workspace over the++//! `memory`/`state`/`jobs` storage value, the engine and++//! `[memory.recall] build_delay_secs` it runs against, and the++//! `memory_background` cron hook.//!//! `post_turn` and brain ingests return `BackgroundJob` values (belief builds,//! deferred ingests) instead of running them. They are queued here, persisted- //! in the `memory`/`state`/`jobs` storage value so a restart loses none, de-duplicated-//! in `<workspace>/memory/jobs.json` so a restart loses none, de-duplicated--//! (two builds of one scope are one build), and run by the++//! in the `memory`/`state`/`jobs` storage value so a restart loses none,++//! de-duplicated (two builds of one scope are one build), and run by the//! `memory_background` cron job ([`run_due`]) once they are at least//! `[memory.recall] build_delay_secs` old — a belief build reads the facts the//! engine extracts from the writes, and that extraction lags behind them.@@@ -49,17 -49,27 +50,17 @@@ struct FileQueueStoreimpl QueueStore for FileQueueStore {fn load(&self) -> QueueState {- let Ok(text) = std::fs::read_to_string(&self.file) else {- return QueueState::default();- };- serde_json::from_str(&text).unwrap_or_else(|error| {- tracing::warn!(%error, "[memory:jobs] queue unparsable; set aside");- if let Err(error) =- std::fs::rename(&self.file, self.file.with_extension("json.corrupt"))- {- tracing::warn!(%error, "[memory:jobs] could not set queue file aside");- }- QueueState::default()- })+ crate::memory::state_store::load(&self.workspace_dir, STATE)+ .unwrap_or_else(|error| {+ tracing::warn!(%error, "[memory:jobs] reading the queue failed");+ None+ })+ .unwrap_or_default()}- fn save(&self, state: &QueueState) -> Result<(), String> {+ fn save(&self, state: &QueueState) -> std::result::Result<(), String> {- serde_json::to_vec_pretty(state)+ crate::memory::state_store::save(&self.workspace_dir, STATE, state).map_err(|error| error.to_string())- .and_then(|json| {- crate::security::secret_storage::file_store::write_atomic(&self.file, &json)- .map_err(|error| error.to_string())- })}}@@@ -71,14 -81,15 +72,15 @@@ static QUEUES: LazyLock<Mutex<HashMap<Pfn queue_of(workspace_dir: &Path) -> Arc<WorkspaceQueue> {let mut queues = QUEUES.lock().unwrap_or_else(|e| e.into_inner());- queues- .entry(workspace_dir.to_path_buf())- .or_insert_with(|| {- Arc::new(Queue::new(FileQueueStore {- workspace_dir: workspace_dir.to_path_buf(),- }))- })- .clone()+ queues.retain(|_, queue| queue.strong_count() > 0);+ if let Some(queue) = queues.get(workspace_dir).and_then(Weak::upgrade) {+ return queue;+ }+ let queue = Arc::new(Queue::new(FileQueueStore {- file: path(workspace_dir),++ workspace_dir: workspace_dir.to_path_buf(),+ }));+ queues.insert(workspace_dir.to_path_buf(), Arc::downgrade(&queue));+ queue}/// Queues `jobs` under `root`; a job already queued is kept once, at itsdiff --cc crates/openhuman-core/src/memory/lifecycle/jobs_tests.rsindex 29d31f175d,749431e52a..3fa4344b5b--- a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs@@@ -11,6 -35,25 +35,24 @@@ fn build(agent: &str) -> BackgroundJob}}+ #[test]-fn corrupt_job_queue_file_is_set_aside() {++fn corrupt_legacy_job_queue_is_skipped_without_replacing_the_file() {+ let tmp = tempfile::tempdir().unwrap();- let file = path(tmp.path());++ let file = crate::memory::state_store::legacy_path(tmp.path(), "jobs");+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(&file, b"{\"pending\":[").unwrap();- let store = FileQueueStore { file: file.clone() };++ let store = FileQueueStore {++ workspace_dir: tmp.path().to_path_buf(),++ };++ assert_eq!(store.load(), QueueState::default());+ assert!(- !file.exists(),- "corrupt queue must not be silently replaced"- );- assert_eq!(- std::fs::read(file.with_extension("json.corrupt")).unwrap(),- b"{\"pending\":["++ file.exists(),++ "the one-time state import must leave the legacy file untouched"+ );++ assert_eq!(std::fs::read(file).unwrap(), b"{\"pending\":[");+ }+#[tokio::test]async fn duplicates_merge_and_the_queue_survives_a_reload() {let tmp = tempfile::tempdir().unwrap();diff --cc crates/openhuman-core/src/memory/ops.rsindex 872cd1f678,4176ff451f..4d0bcd5c36--- a/crates/openhuman-core/src/memory/ops.rs+++ b/crates/openhuman-core/src/memory/ops.rs@@@ -355,100 -347,264 +347,274 @@@ pub async fn store_item(config: &Config/// engine indexing the item.pub async fn store_item_with(config: &Config,- mut item: StoreItem,+ item: StoreItem,options: WriteOptions,- ) -> MemoryResult<StoreReceipt> {- if let Some(root) = super::user_scope::confinement(config)? {- super::user_scope::clamp_item(&mut item, &root);- }+ ) -> Result<StoreReceipt> {+ let ops = memory_ops(config)?;let bound = bound(config)?;- store_on_with(&bound, item, options).await+ let item = ops.store_item(item)?;+ let receipt = bound.engine.store_with(item, options).await?;+ super::lifecycle::prefetch::invalidate(config);+ Ok(receipt)}- /// Stores `item` on `bound`; the bound engine scrubs it ([`super::guard`]).- pub async fn store_on(bound: &BoundEngine, item: StoreItem) -> MemoryResult<StoreReceipt> {- store_on_with(bound, item, WriteOptions::visible()).await+ /// `memory_forget`.+ pub async fn forget(config: &Config, params: ForgetParams) -> Result<ForgetView> {+ if !params.ids.iter().any(|id| !id.trim().is_empty()) {+ return Err(Error::InvalidRequest(+ ("forget needs at least one id").into(),+ ));+ }+ let bound = bound(config)?;+ let report = memory_ops(config)?+ .forget(bound.engine.as_ref(), params.ids, params.reach)+ .await?;+ tracing::debug!(engine = %bound.id, forgotten = report.forgotten, "[memory:ops] forget");+ super::lifecycle::prefetch::invalidate(config);+ Ok(ForgetView {+ forgotten: report.forgotten,+ })}- /// [`store_on`], returning as soon as `options` allows.- pub async fn store_on_with(- bound: &BoundEngine,- item: StoreItem,- options: WriteOptions,- ) -> MemoryResult<StoreReceipt> {- let kind = item.kind();- let receipt = bound.engine.store_with(item, options).await?;+ /// Forgets every item matching a non-empty metadata filter through the bound+ /// engine, applying the host-selected confinement.+ ///+ /// # Errors+ ///+ /// Returns an error if memory is unavailable, the filter is invalid, or the+ /// engine cannot complete the deletion.+ pub async fn forget_filter(config: &Config, filter: MetaFilter) -> Result<usize> {+ let bound = bound(config)?;+ let report = memory_ops(config)?+ .forget_filter(bound.engine.as_ref(), filter)+ .await?;tracing::debug!(engine = %bound.id,- kind = kind.as_str(),- wait = ?options.wait,- replayed = receipt.replayed,- "[memory:ops] item stored"+ forgotten = report.forgotten,+ "[memory:ops] filtered forget");- Ok(receipt)+ super::lifecycle::prefetch::invalidate(config);+ Ok(report.forgotten)}- /// Stores `items` on `bound` in one bulk call, returning as soon as- /// `options` allows. With [`WriteOptions::visible`] each item is listed on- /// return, and ranked recall may lag behind for all but the last. A backfill- /// or an import that reads nothing back until it ends passes- /// [`WriteOptions::accepted`]: an engine that supports it (CortexDB) returns- /// once the items are durably accepted, before they are indexed, and any- /// other stores them as with `visible`.- pub async fn store_many_on_with(- bound: &BoundEngine,- items: Vec<StoreItem>,- options: WriteOptions,- ) -> MemoryResult<Vec<StoreReceipt>> {- let count = items.len();- let receipts = bound.engine.store_many_with(items, options).await?;+ /// Forgets conversation memory owned by an external channel on disconnect.+ ///+ /// The engine filter removes stamped turns in one operation. A bounded+ /// snapshot of canonical thread IDs plus the previous release's read-only+ /// channel map supplies thread-level fallback for turns that predate channel+ /// metadata. New turns never write that map; remove the compatibility reader+ /// after one release.+ #[cfg(feature = "channels")]+ pub async fn forget_channel(config: &Config, channel: &str) -> Result<usize> {+ let channel = channel.trim().to_ascii_lowercase();+ if channel.is_empty() {+ return Ok(0);+ }+ let legacy_threads = legacy_channel_threads(&config.workspace_dir, &channel);+ let bound = match engine::resolve(config).engine() {+ Ok(bound) => Some(bound),+ Err(Error::Off(_)) => None,+ Err(error) => return Err(error),+ };++ // Capture the request's tenant/profile before the module call and the+ // thread-store wrappers move work off the caller's task.+ let ctx = crate::core::runtime::DispatchCtx::ambient();+ let identity = crate::modules::channel_controller::prepare_identity(+ &crate::modules::client(config.clone()),+ tinychannels_bus::module_inbound::PrepareChannelIdentityRequest {+ channel: channel.clone(),+ sender: None,+ reply_target: None,+ thread_ts: None,+ },+ )+ .await;+ let base_thread_id = match identity {+ Ok(identity) => identity.thread_id,+ Err(error) => {+ enqueue_channel_threads(config, &legacy_threads);+ return Err(Error::Engine(format!(+ "channel identity preparation failed: {error}"+ )));+ }+ };+ let threads =+ channel_thread_snapshot(&ctx, config, &channel, &base_thread_id, legacy_threads).await?;+ let Some(bound) = bound else {+ enqueue_channel_threads(config, &threads);+ tracing::debug!(channel = %channel, queued = threads.len(), "[memory:channels] channel forget queued");+ return Ok(0);+ };++ let filter = MetaFilter {+ channel: Some(channel.clone()),+ ..MetaFilter::kinds([ItemKind::Conversation])+ };+ let mut forgotten = match bound.engine.forget(ForgetTarget::Filter(filter)).await {+ Ok(report) => report.forgotten,+ Err(Error::Off(_)) => {+ enqueue_channel_threads(config, &threads);+ return Ok(0);+ }+ Err(error) => {+ enqueue_channel_threads(config, &threads);+ return Err(error);+ }+ };++ let mut failure = None;+ for thread_id in &threads {+ match forget_channel_thread(&bound, thread_id).await {+ Ok(count) => forgotten += count,+ Err(error) => {+ super::deletion::enqueue(+ &config.workspace_dir,+ super::deletion::PendingDeletion::Thread {+ thread_id: thread_id.clone(),+ },+ );+ if !matches!(error, Error::Off(_)) && failure.is_none() {+ failure = Some(error);+ }+ }+ }+ }+tracing::debug!(- engine = %bound.id,- count,- wait = ?options.wait,- replayed = receipts.iter().filter(|r| r.replayed).count(),- "[memory:ops] batch stored"+ channel = %channel,+ forgotten,+ queued = super::deletion::pending(&config.workspace_dir).len(),+ "[memory:channels] channel forgotten");- Ok(receipts)+ match failure {+ Some(error) => Err(error),+ None => Ok(forgotten),+ }}- /// `memory_forget`.- pub async fn forget(config: &Config, params: ForgetParams) -> MemoryResult<ForgetView> {- let ids: Vec<ItemId> = params- .ids- .into_iter()- .map(|id| id.trim().to_string())- .filter(|id| !id.is_empty())- .map(ItemId)- .collect();- if ids.is_empty() {- return Err(MemoryError::invalid("forget needs at least one id"));+ #[cfg(feature = "channels")]+ fn channel_key(channel: &str) -> String {+ channel.trim().to_ascii_lowercase()+ }++ /// Reads only the legacy map written by prior releases. Corrupt JSON keeps the+ /// existing quarantine behavior; current code never creates or updates it.+ #[cfg(feature = "channels")]+ fn legacy_channel_threads(workspace: &Path, channel: &str) -> BTreeSet<String> {++ // Prefer the state-store value: layout migration may already have++ // removed the legacy file after importing it. The direct file fallback++ // below preserves quarantine behavior for malformed legacy JSON and++ // remains available when storage cannot be opened.++ if let Ok(Some(all)) = crate::memory::state_store::load::<BTreeMap<String, BTreeSet<String>>>(++ workspace,++ "channel_threads",++ ) {++ return all.get(&channel_key(channel)).cloned().unwrap_or_default();+ }- let bound = bound(config)?;- // A SaaS user forgets only what lies in their own tree.- let reach = match super::user_scope::confinement(config)? {- Some(root) => Some(super::user_scope::clamp_reach(params.reach, &root)),- None => params.reach,+ let file = workspace.join("memory").join("channel_threads.json");+ let Ok(text) = std::fs::read_to_string(&file) else {+ return BTreeSet::new();+ };+ let all: BTreeMap<String, BTreeSet<String>> =+ serde_json::from_str(&text).unwrap_or_else(|error| {+ tracing::warn!(%error, "[memory:channels] legacy channel map unparsable; set aside");+ if let Err(error) = std::fs::rename(&file, file.with_extension("json.corrupt")) {+ tracing::warn!(%error, "[memory:channels] could not set legacy map aside");+ }+ BTreeMap::new()+ });+ all.get(&channel_key(channel)).cloned().unwrap_or_default()+ }++ #[cfg(feature = "channels")]+ fn is_channel_thread_id(thread_id: &str, base_thread_id: &str) -> bool {+ if thread_id == base_thread_id {+ return true;+ }+ thread_id+ .strip_prefix(base_thread_id)+ .is_some_and(|suffix| suffix.starts_with('/') || suffix.starts_with("#thread:"))+ }++ #[cfg(feature = "channels")]+ fn enqueue_channel_threads(config: &Config, threads: &BTreeSet<String>) {+ for thread_id in threads {+ super::deletion::enqueue(+ &config.workspace_dir,+ super::deletion::PendingDeletion::Thread {+ thread_id: thread_id.clone(),+ },+ );+ }+ }++ #[cfg(feature = "channels")]+ async fn channel_thread_snapshot(+ ctx: &crate::core::runtime::DispatchCtx,+ config: &Config,+ channel: &str,+ base_thread_id: &str,+ mut owned: BTreeSet<String>,+ ) -> Result<BTreeSet<String>> {+ let threads = match crate::threads::store::blocking::list_threads(+ ctx.clone(),+ config.workspace_dir.clone(),+ )+ .await+ {+ Ok(threads) => threads,+ Err(error) => {+ enqueue_channel_threads(config, &owned);+ return Err(Error::Engine(format!(+ "reading channel thread snapshot failed: {error}"+ )));+ }};- let report = match reach {- // With a reach the engine forgets by id inside it: `forget_within`- // never looks beyond the reach for an id, where `ForgetTarget::Ids`- // sweeps every scope of the tree to find one.- Some(reach) => {- let ids = within_reach(&bound, ids, reach.clone()).await?;- if ids.is_empty() {- tracing::debug!(engine = %bound.id, "[memory:ops] forget: nothing in reach");- return Ok(ForgetView { forgotten: 0 });+ for thread in threads {+ if owned.contains(&thread.id) || is_channel_thread_id(&thread.id, base_thread_id) {+ owned.insert(thread.id);+ continue;+ }+ let messages = match crate::threads::store::blocking::get_messages(+ ctx.clone(),+ config.workspace_dir.clone(),+ thread.id.clone(),+ )+ .await+ {+ Ok(messages) => messages,+ Err(error) => {+ enqueue_channel_threads(config, &owned);+ return Err(Error::Engine(format!(+ "reading channel message snapshot failed: {error}"+ )));}- bound.engine.forget_within(ids, reach).await?+ };+ if messages.iter().any(|message| {+ message+ .extra_metadata+ .get("channel")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|value| channel_key(value) == channel)+ }) {+ owned.insert(thread.id);}- None => bound.engine.forget(ForgetTarget::Ids(ids)).await?,+ }+ Ok(owned)+ }++ #[cfg(feature = "channels")]+ async fn forget_channel_thread(bound: &BoundEngine, thread_id: &str) -> Result<usize> {+ let filter = MetaFilter {+ thread_id: Some(thread_id.to_string()),+ ..MetaFilter::kinds([ItemKind::Conversation])};- tracing::debug!(engine = %bound.id, forgotten = report.forgotten, "[memory:ops] forget");- super::lifecycle::prefetch::invalidate(config);- Ok(ForgetView {- forgotten: report.forgotten,- })+ Ok(bound+ .engine+ .forget(ForgetTarget::Filter(filter))+ .await?+ .forgotten)}/// `memory_erase_all`: erases everything the bound engine holds, the wholediff --cc crates/openhuman-core/src/memory/sources/state.rsindex 17331c165e,29046fdacd..bc4dbd0a80--- a/crates/openhuman-core/src/memory/sources/state.rs+++ b/crates/openhuman-core/src/memory/sources/state.rs@@@ -6,43 -6,30 +6,23 @@@//! a run the previous process never finished, and reads as `idle`.use std::collections::BTreeMap;-use std::path::{Path, PathBuf};+use std::path::Path;use std::sync::{LazyLock, Mutex};- use chrono::{DateTime, Utc};- use serde::{Deserialize, Serialize};-- use crate::memory::types::SourceStatus;+ use tinymemory_integrations::sources::{SourceState, SourceStatus};/// Serialises state-file read-modify-writes in this process.static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));- /// What the last sync of one source left behind.- #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]- pub struct SourceState {- /// When the last sync finished.- #[serde(default)]- pub last_sync_at: Option<DateTime<Utc>>,- /// Current status.- #[serde(default)]- pub status: SourceStatus,- /// Why the last sync failed.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub error: Option<String>,- /// Items stored by the last successful sync.- #[serde(default)]- pub items: u64,-fn path(workspace_dir: &Path) -> PathBuf {- workspace_dir.join("memory").join("sources_state.json")--}-+const STATE: &str = "sources_state";fn read_all(workspace_dir: &Path) -> BTreeMap<String, SourceState> {- let file = path(workspace_dir);- let Ok(text) = std::fs::read_to_string(&file) else {- return BTreeMap::new();- };- serde_json::from_str(&text).unwrap_or_else(|error| {- tracing::warn!(%error, "[memory:sources] sync state unparsable; set aside");- if let Err(error) = std::fs::rename(&file, file.with_extension("json.corrupt")) {- tracing::warn!(%error, "[memory:sources] could not set sync state file aside");- }- BTreeMap::new()- })+ crate::memory::state_store::load(workspace_dir, STATE)+ .unwrap_or_else(|error| {+ tracing::warn!(error = %error, "[memory:sources] reading sync state failed");+ None+ })+ .unwrap_or_default()}fn write_all(workspace_dir: &Path, all: &BTreeMap<String, SourceState>) {diff --cc crates/openhuman-core/src/memory/sources/state_tests.rsindex 0000000000,fab1ef3af4..709db41e62mode 000000,100644..100644--- a/crates/openhuman-core/src/memory/sources/state_tests.rs+++ b/crates/openhuman-core/src/memory/sources/state_tests.rs@@@ -1,0 -1,42 +1,39 @@@+ use super::*;+ use tinymemory_integrations::sources::SourceStatus;++ #[test]-fn corrupt_source_state_file_is_set_aside() {++fn corrupt_legacy_source_state_is_skipped_and_left_in_place() {+ let tmp = tempfile::tempdir().unwrap();- let file = path(tmp.path());++ let file = crate::memory::state_store::legacy_path(tmp.path(), "sources_state");+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(&file, b"{\"source-1\":").unwrap();++ assert!(load(tmp.path()).is_empty());+ assert!(- !file.exists(),- "corrupt state must not be silently replaced"- );- assert_eq!(- std::fs::read(file.with_extension("json.corrupt")).unwrap(),- b"{\"source-1\":"++ file.exists(),++ "state import leaves the legacy file in place"+ );++ assert_eq!(std::fs::read(file).unwrap(), b"{\"source-1\":");+ }++ #[test]+ fn native_source_state_keeps_the_persisted_host_shape() {+ let tmp = tempfile::tempdir().unwrap();- let file = path(tmp.path());++ let file = crate::memory::state_store::legacy_path(tmp.path(), "sources_state");+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ let saved = serde_json::json!({+ "src-1": {+ "last_sync_at": "2025-01-02T03:04:05Z",+ "status": "error",+ "error": "reader failed",+ "items": 7+ }+ });+ std::fs::write(&file, serde_json::to_vec(&saved).unwrap()).unwrap();++ let all = load(tmp.path());+ assert_eq!(all["src-1"].status, SourceStatus::Error);+ assert_eq!(all["src-1"].error.as_deref(), Some("reader failed"));+ assert_eq!(all["src-1"].items, 7);+ assert_eq!(serde_json::to_value(all).unwrap(), saved);+ }diff --cc crates/openhuman-core/src/memory/tool_writes.rsindex bd7609dddd,1334ef5f8f..b265619c25--- a/crates/openhuman-core/src/memory/tool_writes.rs+++ b/crates/openhuman-core/src/memory/tool_writes.rs@@@ -12,8 -11,9 +12,8 @@@//! the remote engine.use std::collections::HashMap;-use std::io::{Read, Write};use std::path::{Path, PathBuf};- use std::sync::{Arc, LazyLock, Mutex};+ use std::sync::{Arc, LazyLock, Mutex, Weak};use std::time::Duration;use async_trait::async_trait;@@@ -210,9 -210,8 +210,9 @@@ pub(super) fn enqueuelet _guard = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- if !file.exists() && partitions(config)?.len() >= MAX_PENDING {+ let known = partitions(config)?;+ if !known.contains(&file) && known.len() >= MAX_PENDING {- return Err(MemoryError::Unavailable(+ return Err(Error::Unavailable("memory write queue full; nothing was queued".into(),));}@@@ -344,25 -339,42 +345,31 @@@ fn owner_state(config: &Config) -> Arc<let mut owners = OWNERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- owners.entry(key).or_insert_with(|| {- Box::leak(Box::new(OwnerState {- gate: WriteGate::new(PROCESS_EPOCH.clone()),- barrier: Arc::default(),- }))- })+ owners.retain(|_, owner| owner.strong_count() > 0);+ if let Some(owner) = owners.get(&key).and_then(Weak::upgrade) {+ return owner;+ }+ let owner = Arc::new(OwnerState {+ // A new gate starts at generation zero, so it needs a distinct epoch+ // identity to make entries from a released gate stale after eviction.+ gate: WriteGate::new(uuid::Uuid::new_v4().to_string()),+ barrier: Arc::default(),+ });+ owners.insert(key, Arc::downgrade(&owner));+ owner}- fn partitions(config: &Config) -> MemoryResult<Vec<PathBuf>> {+ fn partitions(config: &Config) -> Result<Vec<PathBuf>> {let prefix = format!("{}-", owner_prefix(config));- let entries = match std::fs::read_dir(config.workspace_dir.join("memory")) {- Ok(entries) => entries,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),- Err(_) => return Err(unavailable()),- };- let mut files = Vec::new();- for entry in entries {- let file = entry.map_err(|_| unavailable())?.path();- if file- .file_name()- .and_then(|name| name.to_str())- .is_some_and(|name| name.starts_with(&prefix) && name.ends_with(".json"))- {- files.push(file);- if files.len() > MAX_PENDING {- return Err(unavailable());- }- }+ let names =+ super::state_store::names(&config.workspace_dir, &prefix).map_err(|_| unavailable())?;+ if names.len() > MAX_PENDING {+ return Err(unavailable());}- Ok(files)+ Ok(names+ .into_iter()+ .map(|name| super::state_store::legacy_path(&config.workspace_dir, &name))+ .collect())}/// Owner epoch captured when automatic turn work is admitted, before it can