Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(memory): use engine and tinymemory types directly

Steven Enamakel669744d7b780
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index 5a7c4c4496..cd02bc0344 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -39,7 +39,6 @@ use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::memory::engine::{self, BoundEngine};
use crate::memory::error::{MemoryError, MemoryResult};
-use crate::memory::ops::store_many_on_with;
use crate::memory::scope::{MemoryIdentity, ResolvedIdentity};
use crate::memory::types::ImportPhase;
use crate::threads::store::blocking as threads;
@@ -300,7 +299,7 @@ async fn run(
} else {
tinymemory_api::WriteOptions::accepted()
};
- let stored = store_many_on_with(bound, items, options).await;
+ let stored = bound.engine.store_many_with(items, options).await;
if let Err(error) = stored {
tracing::warn!(
code = error.code(),
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 0aacb2a924..80093ff33e 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -13,7 +13,7 @@ use std::sync::{Arc, LazyLock, Mutex};
use std::time::Duration;
use tinymemory_integrations::import::{
- Begun, CheckpointStore, ImportError, ImportFile, Importer, Pacer,
+ Begun, CheckpointStore, ImportError, ImportFile, ImportPhase, ImportState, Importer, Pacer,
};
use crate::config::Config;
@@ -21,7 +21,7 @@ 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};
/// Whether background work is paused right now. An automatic resume asks
/// before it starts and again before every batch it stores.
@@ -129,21 +129,12 @@ fn importer(
Arc::new(importer)
}
-/// Counts what a legacy store at `workspace_dir` holds, or `None` when there
-/// is no v1 store there. Blocking (SQLite, and memory-tree chunk files).
-pub fn count_legacy(workspace_dir: &Path) -> Option<ImportCounts> {
- let counts = tinymemory_integrations::import::count_legacy(workspace_dir)?;
- Some(ImportCounts {
- documents: counts.documents,
- conversations: counts.conversations,
- learnings: counts.learnings,
- })
-}
-
/// `memory_import_scan`.
pub async fn scan(config: &Config) -> MemoryResult<ImportScanView> {
let workspace_dir = config.workspace_dir.clone();
- let counts = tokio::task::spawn_blocking(move || count_legacy(&workspace_dir))
+ let counts = tokio::task::spawn_blocking(move || {
+ tinymemory_integrations::import::count_legacy(&workspace_dir)
+ })
.await
.map_err(|error| MemoryError::Engine(format!("import scan failed: {error}")))?;
Ok(ImportScanView {
diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs.rs b/crates/openhuman-core/src/memory/lifecycle/jobs.rs
index 27f78bd9e3..e3cd91e636 100644
--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs
@@ -25,7 +25,7 @@ use tinymemory_api::Namespace;
use tinymemory_tools::queue::{JobQueue as Queue, QueueError, QueueState, QueueStore};
use tinymemory_tools::BackgroundJob;
-pub use tinymemory_tools::queue::{JobRun, QueuedJob, Selection, MAX_ATTEMPTS, MAX_HISTORY};
+use tinymemory_tools::queue::{JobRun, QueuedJob, Selection, MAX_ATTEMPTS, MAX_HISTORY};
use crate::config::Config;
use crate::memory::engine;
@@ -37,9 +37,6 @@ pub const BACKGROUND_JOB: &str = "memory_background";
/// Minutes between queue runs.
pub const BACKGROUND_INTERVAL_MINS: u64 = 5;
-/// The persisted queue as the UI reads it.
-pub type JobQueue = QueueState;
-
/// The queue file of a workspace.
fn path(workspace_dir: &Path) -> PathBuf {
workspace_dir.join("memory").join("jobs.json")
@@ -108,7 +105,7 @@ pub fn has_pending(workspace_dir: &Path) -> bool {
}
/// The queue as it stands.
-pub async fn snapshot(config: &Config) -> JobQueue {
+pub async fn snapshot(config: &Config) -> QueueState {
queue_of(&config.workspace_dir).snapshot().await
}
diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
index 2f63f62617..b62a3f0fa7 100644
--- a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use tinymemory_tools::queue::QueueState;
use tinymemory_api::{ConsolidateRequest, ItemKind, Reach};
@@ -139,7 +140,7 @@ async fn the_build_delay_comes_from_the_recall_config_and_the_file_store_is_the_
config.memory.recall.build_delay_secs = 3600;
enqueue(&config, &Namespace::ROOT, vec![build("a")]).await;
assert!(has_pending(&config.workspace_dir));
- let on_disk: JobQueue =
+ let on_disk: QueueState =
serde_json::from_str(&std::fs::read_to_string(path(&config.workspace_dir)).unwrap())
.unwrap();
assert_eq!(on_disk.pending.len(), 1, "persisted in memory/jobs.json");
diff --git a/crates/openhuman-core/src/memory/lifecycle/views.rs b/crates/openhuman-core/src/memory/lifecycle/views.rs
index 8b65794a48..76f637c73e 100644
--- a/crates/openhuman-core/src/memory/lifecycle/views.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/views.rs
@@ -10,7 +10,8 @@ use crate::config::Config;
use crate::memory::error::{MemoryError, MemoryResult};
use crate::memory::scope::{self, MemoryIdentity};
-use super::jobs::{self, JobQueue, JobRun, Selection};
+use super::jobs::{self};
+use tinymemory_tools::queue::{JobRun, QueueState, Selection};
/// `memory_policy_get` / `_set` result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -277,7 +278,7 @@ pub async fn agents_list(config: &Config, identity: &MemoryIdentity) -> MemoryRe
}
/// `memory_jobs_list` result.
-pub type JobsView = JobQueue;
+pub type JobsView = QueueState;
/// `memory_jobs_list`.
pub async fn jobs_list(config: &Config) -> JobsView {
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index 78efe893e1..cf665108ec 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -60,4 +60,3 @@ pub use schemas::{
pub use tools::{MemoryTool, MEMORY_TOOL_NAME};
/// Host-specific connector prefix configuration for memory provenance.
-pub mod provenance;
diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rs
index 27089a9f35..cb0152a560 100644
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@ -339,7 +339,7 @@ pub async fn learn_with(
super::user_scope::clamp_item(&mut item, &root);
}
let bound = bound(config)?;
- let receipt = store_on_with(&bound, item, options).await?;
+ let receipt = bound.engine.store_with(item, options).await?;
super::lifecycle::prefetch::invalidate(config);
Ok(LearnView { id: receipt.id.0 })
}
@@ -361,58 +361,11 @@ pub async fn store_item_with(
super::user_scope::clamp_item(&mut item, &root);
}
let bound = bound(config)?;
- let receipt = store_on_with(&bound, 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
-}
-
-/// [`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?;
- tracing::debug!(
- engine = %bound.id,
- kind = kind.as_str(),
- wait = ?options.wait,
- replayed = receipt.replayed,
- "[memory:ops] item stored"
- );
+ super::lifecycle::prefetch::invalidate(config);
Ok(receipt)
}
-/// 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?;
- tracing::debug!(
- engine = %bound.id,
- count,
- wait = ?options.wait,
- replayed = receipts.iter().filter(|r| r.replayed).count(),
- "[memory:ops] batch stored"
- );
- Ok(receipts)
-}
-
/// `memory_forget`.
pub async fn forget(config: &Config, params: ForgetParams) -> MemoryResult<ForgetView> {
let ids: Vec<ItemId> = params
diff --git a/crates/openhuman-core/src/memory/provenance.rs b/crates/openhuman-core/src/memory/provenance.rs
deleted file mode 100644
index 98fbc9b197..0000000000
--- a/crates/openhuman-core/src/memory/provenance.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-//! OpenHuman's connector vocabulary for TinyMemory provenance classification.
-//!
-//! Classification and escaped prompt markers belong to `tinymemory_api`.
-//! This host supplies only the key prefixes used by its ingestion adapters.
-
-/// Builds the memory provenance policy with OpenHuman's connector prefixes.
-pub fn connector_provenance_policy() -> tinymemory_api::ProvenancePolicy {
- let connector_prefixes = &[
- "chat:",
- "email:",
- "notion:",
- "drive:",
- "discord:",
- "telegram:",
- "whatsapp:",
- "slack:",
- "gmail:",
- "outlook:",
- "imap:",
- "meeting:",
- "web:",
- ];
- tinymemory_api::ProvenancePolicy::new(connector_prefixes)
-}
-
-#[cfg(test)]
-#[path = "provenance_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/provenance_tests.rs b/crates/openhuman-core/src/memory/provenance_tests.rs
deleted file mode 100644
index bbc74aefd5..0000000000
--- a/crates/openhuman-core/src/memory/provenance_tests.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-use super::*;
-#[test]
-fn locally_authored_namespaces_are_trusted() {
- for ns in [
- "working", "agent", "local", "core", "global", "default", "user",
- ] {
- assert!(
- !connector_provenance_policy().is_potentially_untrusted(Some(ns), "k"),
- "namespace '{ns}' must be trusted"
- );
- }
-}
-
-#[test]
-fn prefixed_subspaces_are_trusted() {
- for ns in ["working.user.123", "agent.session.foo", "tree.discord.456"] {
- assert!(
- !connector_provenance_policy().is_potentially_untrusted(Some(ns), "k"),
- "namespace '{ns}' must be trusted"
- );
- }
-}
-
-#[test]
-fn unknown_namespace_is_untrusted() {
- // Default-deny — any unrecognised namespace flips to untrusted so
- // a future connector that lands without explicit allowlisting is
- // wrapped by default.
- assert!(connector_provenance_policy().is_potentially_untrusted(Some("scraped"), "k"));
- assert!(connector_provenance_policy().is_potentially_untrusted(Some("composio"), "k"));
-}
-
-#[test]
-fn connector_key_prefix_is_untrusted_even_without_namespace() {
- assert!(connector_provenance_policy().is_potentially_untrusted(None, "chat:discord:42"));
- assert!(connector_provenance_policy().is_potentially_untrusted(None, "gmail:thread:xyz"));
- assert!(connector_provenance_policy().is_potentially_untrusted(None, "notion:page:abc"));
-}
-
-#[test]
-fn no_namespace_plain_key_is_trusted() {
- // No namespace + no connector prefix = locally authored by
- // default (the bare-key tooling path doesn't reach this code).
- assert!(!connector_provenance_policy().is_potentially_untrusted(None, "user_pref:theme"));
-}
diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rs
index c5618a35f5..579f559d2a 100644
--- a/crates/openhuman-core/src/memory/tool_writes.rs
+++ b/crates/openhuman-core/src/memory/tool_writes.rs
@@ -580,9 +580,10 @@ impl WriteExecutor for Executor<'_> {
match operation {
WriteOperation::Learn { item } => {
let bound = super::engine::resolve(config).engine()?;
- let receipt =
- super::ops::store_on_with(&bound, item.clone(), WriteOptions::accepted())
- .await?;
+ let receipt = bound
+ .engine
+ .store_with(item.clone(), WriteOptions::accepted())
+ .await?;
let category = match item {
StoreItem::Learning { kind, .. } => kind.as_str(),
_ => "learning",
diff --git a/crates/openhuman-core/src/memory/types.rs b/crates/openhuman-core/src/memory/types.rs
index 1874407dd3..26c6fc8dbc 100644
--- a/crates/openhuman-core/src/memory/types.rs
+++ b/crates/openhuman-core/src/memory/types.rs
@@ -8,10 +8,6 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
-pub use tinymemory_api::{
- Citation, EngineDescriptor, FetchMode, Hit, ItemKind, LearningKind, MemoryMeta, MetaFilter,
-};
-
use crate::config::schema::MemorySourceKind;
/// Default `limit` of recall, fetch and list.
@@ -383,8 +379,6 @@ pub struct ImportStartParams {
/// Where an import stands, and its progress (`memory_import_*` state): the
/// module's own types, so the persisted file and the wire share one shape.
-pub use tinymemory_integrations::import::{ImportPhase, ImportState};
-
/// `memory_import_start` / `_status` result.
#[derive(Debug, Clone, Serialize)]
pub struct ImportStateView {
diff --git a/crates/openhuman-core/src/profiles/background.rs b/crates/openhuman-core/src/profiles/background.rs
index d67e6455d8..4feee00056 100644
--- a/crates/openhuman-core/src/profiles/background.rs
+++ b/crates/openhuman-core/src/profiles/background.rs
@@ -25,7 +25,8 @@ use std::time::Duration;
use super::host::ProfileHost;
use crate::core::runtime::CoreContext;
-use crate::memory::lifecycle::jobs::{self, Selection};
+use crate::memory::lifecycle::jobs;
+use tinymemory_tools::queue::Selection;
/// How often the loop visits the profiles.
pub const TICK_INTERVAL: Duration = Duration::from_secs(60);