Skip to content

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

chore: files changed crates/openhuman-core/src/memory/engine.rs,crates/openhuman-core/src/memory/gua

Steven Enamakelb9cd21896ad6
diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rs
index f949e649a5..b825fd2e25 100644
--- a/crates/openhuman-core/src/memory/engine.rs
+++ b/crates/openhuman-core/src/memory/engine.rs
@@ -26,8 +26,8 @@
//! it then wins over the configured one for every config in the process — one
//! OpenHuman runtime per process — so a host with its own store, or a test
//! binary with an in-memory engine, runs the whole lifecycle without a
-//! TinyHumans credential or a CortexDB key. It is wrapped in the same
-//! scrubber as a configured engine.
+//! TinyHumans credential or a CortexDB key. It is wrapped by TinyMemory's
+//! native binder under the same host scrub policy as a configured engine.
//!
//! The core never holds a TinyHumans credential of its own: the bearer comes
//! from the host's credential seam on every request, so a refreshed session is
diff --git a/crates/openhuman-core/src/memory/guard.rs b/crates/openhuman-core/src/memory/guard.rs
deleted file mode 100644
index 17112b4f41..0000000000
--- a/crates/openhuman-core/src/memory/guard.rs
+++ /dev/null
@@ -1,229 +0,0 @@
-//! The host's write guard around every bound engine.
-//!
-//! Every write leaves the process through [`ScrubbingEngine`]: each text a
-//! `StoreItem` carries is scrubbed of secrets and PII under the host policy
-//! (`security::scrub::host_policy`) before the engine sees it. Wrapping the
-//! engine, rather than scrubbing at each call site, covers the paths that
-//! write through TinyMemory's own types (`AgentMemory::pre_turn` /
-//! `post_turn`, `Brain::ingest`, background ingests) as well as the host's.
-//! Reads pass through untouched.
-//!
-//! The same wrapper times every engine call: one `[memory:timing]` debug
-//! line with the op, engine, `elapsed_ms`, outcome (`ok` or the error code)
-//! and a result count, never user content (tinyhumansai/backend#1405).
-
-use std::future::Future;
-use std::sync::Arc;
-use std::time::Instant;
-
-use async_trait::async_trait;
-use tinymemory_api::{
- BeliefsRequest, ConsolidateReceipt, ConsolidateRequest, EngineDescriptor, EngineHealth,
- EraseReport, EraseRequest, ExplorePage, ExploreRequest, ExportPage, FetchPage, FetchRequest,
- ForgetReport, ForgetTarget, GetRequest, Hit, ItemId, ListPage, ListRequest, MemoryEngine,
- Reach, RecallAnswer, RecallRequest, Result, StoreItem, StoreReceipt, WaitFor, WriteOptions,
-};
-
-/// `inner` with every stored item scrubbed first, and every call timed.
-pub struct ScrubbingEngine {
- inner: Arc<dyn MemoryEngine>,
- id: String,
-}
-
-impl ScrubbingEngine {
- /// Guards `inner`.
- #[must_use]
- pub fn wrap(inner: Arc<dyn MemoryEngine>) -> Arc<dyn MemoryEngine> {
- let id = inner.descriptor().id.to_string();
- Arc::new(Self { inner, id })
- }
-
- /// Runs `call` and logs its timing; `count` sizes a success.
- async fn timed<T>(
- &self,
- op: &'static str,
- call: impl Future<Output = Result<T>>,
- count: impl FnOnce(&T) -> usize,
- ) -> Result<T> {
- let started = Instant::now();
- let result = call.await;
- let elapsed_ms = started.elapsed().as_millis() as u64;
- let outcome = outcome(&result);
- let count = result.as_ref().map_or(0, count);
- tracing::debug!(
- op,
- engine = %self.id,
- elapsed_ms,
- outcome,
- count,
- "[memory:timing]"
- );
- result
- }
-}
-
-/// `ok`, or the stable code of the error a call failed with.
-fn outcome<T>(result: &Result<T>) -> &'static str {
- match result {
- Ok(_) => "ok",
- Err(error) => error.code(),
- }
-}
-
-/// `item` scrubbed under the host policy.
-#[must_use]
-pub fn scrub(item: StoreItem) -> StoreItem {
- let kind = item.kind();
- let scrubbed = tinymemory_integrations::safety::scrub_item_with(
- item,
- crate::security::scrub::host_policy(),
- );
- if scrubbed.report.changed() {
- tracing::debug!(
- kind = kind.as_str(),
- "[memory:guard] item scrubbed before store"
- );
- }
- scrubbed.value
-}
-
-#[async_trait]
-impl MemoryEngine for ScrubbingEngine {
- fn descriptor(&self) -> &EngineDescriptor {
- self.inner.descriptor()
- }
-
- async fn health(&self) -> EngineHealth {
- let started = Instant::now();
- let health = self.inner.health().await;
- let outcome = match &health {
- EngineHealth::Ok => "ok",
- EngineHealth::Degraded(_) => "degraded",
- EngineHealth::Down(_) => "down",
- };
- tracing::debug!(
- op = "health",
- engine = %self.id,
- elapsed_ms = started.elapsed().as_millis() as u64,
- outcome,
- "[memory:timing]"
- );
- health
- }
-
- async fn recall(&self, req: RecallRequest) -> Result<RecallAnswer> {
- self.timed("recall", self.inner.recall(req), |answer| {
- answer.citations.len()
- })
- .await
- }
-
- async fn fetch(&self, req: FetchRequest) -> Result<FetchPage> {
- self.timed("fetch", self.inner.fetch(req), |page| page.hits.len())
- .await
- }
-
- async fn store(&self, item: StoreItem) -> Result<StoreReceipt> {
- self.timed("store", self.inner.store(scrub(item)), |_| 1)
- .await
- }
-
- async fn store_with(&self, item: StoreItem, options: WriteOptions) -> Result<StoreReceipt> {
- let op = match options.wait {
- WaitFor::Accepted => "store_accepted",
- WaitFor::Visible => "store",
- };
- self.timed(op, self.inner.store_with(scrub(item), options), |_| 1)
- .await
- }
-
- async fn store_many(&self, items: Vec<StoreItem>) -> Result<Vec<StoreReceipt>> {
- let items = items.into_iter().map(scrub).collect();
- self.timed("store_many", self.inner.store_many(items), Vec::len)
- .await
- }
-
- async fn store_many_with(
- &self,
- items: Vec<StoreItem>,
- options: WriteOptions,
- ) -> Result<Vec<StoreReceipt>> {
- let op = match options.wait {
- WaitFor::Accepted => "store_many_accepted",
- WaitFor::Visible => "store_many",
- };
- let items = items.into_iter().map(scrub).collect();
- self.timed(op, self.inner.store_many_with(items, options), Vec::len)
- .await
- }
-
- async fn forget(&self, target: ForgetTarget) -> Result<ForgetReport> {
- self.timed("forget", self.inner.forget(target), |report| {
- report.forgotten
- })
- .await
- }
-
- // Forwarded, not left to the default: the default reads back through
- // this wrapper's `get` and then calls `forget(ForgetTarget::Ids)`, which
- // on the inner engine sweeps the whole tree for the ids.
- async fn forget_within(&self, ids: Vec<ItemId>, reach: Reach) -> Result<ForgetReport> {
- self.timed(
- "forget_within",
- self.inner.forget_within(ids, reach),
- |report| report.forgotten,
- )
- .await
- }
-
- async fn list(&self, req: ListRequest) -> Result<ListPage> {
- self.timed("list", self.inner.list(req), |page| page.items.len())
- .await
- }
-
- async fn list_preview(&self, req: ListRequest) -> Result<ListPage> {
- self.timed("list_preview", self.inner.list_preview(req), |page| {
- page.items.len()
- })
- .await
- }
-
- async fn export(&self, req: ListRequest) -> Result<ExportPage> {
- self.timed("export", self.inner.export(req), |page| page.items.len())
- .await
- }
-
- async fn erase(&self, req: EraseRequest) -> Result<EraseReport> {
- self.timed("erase", self.inner.erase(req), |report| {
- report.erased_scopes
- })
- .await
- }
-
- async fn explore(&self, req: ExploreRequest) -> Result<ExplorePage> {
- self.timed("explore", self.inner.explore(req), |page| {
- page.buckets.len()
- })
- .await
- }
-
- async fn get(&self, req: GetRequest) -> Result<Vec<Hit>> {
- self.timed("get", self.inner.get(req), Vec::len).await
- }
-
- async fn consolidate(&self, req: ConsolidateRequest) -> Result<ConsolidateReceipt> {
- self.timed("consolidate", self.inner.consolidate(req), |receipt| {
- receipt.jobs.len()
- })
- .await
- }
-
- async fn beliefs(&self, req: BeliefsRequest) -> Result<Vec<Hit>> {
- self.timed("beliefs", self.inner.beliefs(req), Vec::len)
- .await
- }
-}
-
-#[cfg(test)]
-#[path = "guard_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/guard_tests.rs b/crates/openhuman-core/src/memory/guard_tests.rs
index 6b1483b1fe..e8989172ba 100644
--- a/crates/openhuman-core/src/memory/guard_tests.rs
+++ b/crates/openhuman-core/src/memory/guard_tests.rs
@@ -23,7 +23,7 @@ async fn texts(engine: &ReferenceEngine) -> Vec<String> {
#[tokio::test]
async fn every_write_path_is_scrubbed() {
let reference = Arc::new(ReferenceEngine::new());
- let guarded = ScrubbingEngine::wrap(reference.clone());
+ let guarded = wrap(reference.clone());
let item =
|text: &str| StoreItem::document(format!("{text} key={SECRET}"), MemoryMeta::default());
@@ -50,17 +50,10 @@ async fn every_write_path_is_scrubbed() {
assert_eq!(guarded.descriptor().id, reference.descriptor().id);
}
-#[test]
-fn a_timed_call_reports_ok_or_the_error_code() {
- assert_eq!(outcome(&Ok::<(), _>(())), "ok");
- let refused: Result<()> = Err(tinymemory_api::Error::Unauthorized("bad key".into()));
- assert_eq!(outcome(&refused), "UNAUTHORIZED");
-}
-
#[tokio::test]
async fn every_read_passes_through_the_timer_unchanged() {
let reference = Arc::new(ReferenceEngine::new());
- let guarded = ScrubbingEngine::wrap(reference.clone());
+ let guarded = wrap(reference.clone());
let id = guarded
.store(StoreItem::document("oolong tea", MemoryMeta::default()))
.await
@@ -140,7 +133,7 @@ fn scrubbing_keeps_the_page_breaks_a_document_is_chunked_by() {
#[tokio::test]
async fn export_and_erase_reach_the_wrapped_engine() {
let reference = Arc::new(ReferenceEngine::new());
- let guarded = ScrubbingEngine::wrap(reference.clone());
+ let guarded = wrap(reference.clone());
let namespace: tinymemory_api::Namespace = "agent:a".parse().unwrap();
guarded
.store(StoreItem::document(
@@ -217,7 +210,7 @@ impl MemoryEngine for Recording {
#[tokio::test]
async fn forget_within_reaches_the_wrapped_engine_with_its_reach() {
let recording = Arc::new(Recording::default());
- let guarded = ScrubbingEngine::wrap(recording.clone());
+ let guarded = wrap(recording.clone());
let reach = Reach::subtree("agent:ann".parse::<tinymemory_api::Namespace>().unwrap());
guarded
.forget_within(vec![ItemId::new("a")], reach.clone())
@@ -233,7 +226,7 @@ async fn forget_within_reaches_the_wrapped_engine_with_its_reach() {
#[tokio::test]
async fn a_bulk_store_keeps_its_wait_through_the_guard() {
let recording = Arc::new(Recording::default());
- let guarded = ScrubbingEngine::wrap(recording.clone());
+ let guarded = wrap(recording.clone());
let items = || vec![StoreItem::document("tea", MemoryMeta::default())];
guarded
.store_many_with(items(), WriteOptions::accepted())
@@ -288,7 +281,7 @@ impl MemoryEngine for MarkedPreview {
#[tokio::test]
async fn a_preview_listing_reaches_the_wrapped_engine() {
- let guarded = ScrubbingEngine::wrap(Arc::new(MarkedPreview(ReferenceEngine::new())));
+ let guarded = wrap(Arc::new(MarkedPreview(ReferenceEngine::new())));
guarded
.store(StoreItem::document("oolong tea", MemoryMeta::default()))
.await
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index f274192d4c..0b4b1acf12 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -3,8 +3,8 @@
//!
//! | Module | Role |
//! | --- | --- |
-//! | [`engine`] | Binds the `[memory]` engine (`tinyhumans` over the host's backend credential, or `cortexdb` with a stored key); memory is **off** without one |
-//! | [`guard`] | Scrubs secrets and PII from every write, whichever path it takes |
+//! | [`engine`] | Maps `[memory]` configuration and host credentials into TinyMemory's native engine binder |
+//! | native engine binder | Scrubs writes under the host policy and times every operation |
//! | [`scope`] | Config-to-identity pins and the account layout migration hooks |
//! | [`lifecycle`] | The turn hooks (pre-turn pack, post-turn log, compaction recall) and the background job queue |
//! | [`ops`] | Engine selection, recall, fetch, learn, forget, list, the pack preview |
@@ -27,7 +27,32 @@ pub mod engine;
pub mod error;
pub mod explore;
pub(crate) mod files;
-pub mod guard;
+#[cfg(test)]
+mod guard {
+ use std::sync::Arc;
+
+ use tinymemory_api::{MemoryEngine, StoreItem};
+ use tinymemory_integrations::safety::{Policy, scrub_item_with};
+ use tinymemory_integrations::EngineBinder;
+
+ fn wrap(engine: Arc<dyn MemoryEngine>) -> Arc<dyn MemoryEngine> {
+ EngineBinder::default()
+ .bind_external(engine, "test://engine", Policy::corroborated())
+ .engine
+ }
+
+ fn scrub(item: StoreItem) -> StoreItem {
+ scrub_item_with(item, Policy::corroborated()).value
+ }
+
+ mod tests {
+ use super::*;
+ use async_trait::async_trait;
+ use tinymemory_api::*;
+
+ include!("guard_tests.rs");
+ }
+}
pub mod import;
pub mod layout_migration;
pub mod lifecycle;
diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rs
index c2cd655b4e..d64d36e2a4 100644
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@ -4,7 +4,7 @@
//! Every operation takes the [`Config`] it runs against, so the RPC handlers
//! (which load config per call) and the agent tool (which carries its
//! session's config) share one implementation. Every write is
-//! scrubbed of secrets and PII by the bound engine itself ([`super::guard`]).
+//! scrubbed of secrets and PII by TinyMemory's native engine binder.
#[cfg(feature = "channels")]
use std::collections::{BTreeMap, BTreeSet};
diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rs
index 1334ef5f8f..ff43e09299 100644
--- a/crates/openhuman-core/src/memory/tool_writes.rs
+++ b/crates/openhuman-core/src/memory/tool_writes.rs
@@ -184,7 +184,11 @@ pub(super) fn enqueue(
));
}
WriteOperation::Learn {
- item: super::guard::scrub(item),
+ item: tinymemory_integrations::safety::scrub_item_with(
+ item,
+ crate::security::scrub::host_policy(),
+ )
+ .value,
}
}
Some("forget") => {