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/ops/documents.rs,crates/openhuman-core/src/mem

Steven Enamakela01254e46228
diff --git a/crates/openhuman-core/src/memory/ops/documents.rs b/crates/openhuman-core/src/memory/ops/documents.rs
index 4bc0b65ff0..00cb167ea9 100644
--- a/crates/openhuman-core/src/memory/ops/documents.rs
+++ b/crates/openhuman-core/src/memory/ops/documents.rs
@@ -18,6 +18,7 @@ use crate::memory::{
use crate::rpc::RpcOutcome;
use super::envelope::{envelope, error_envelope, memory_counts};
+use super::fallback;
use super::guard::active_memory_guard;
use super::helpers::{
build_retrieval_context, current_workspace_dir, filter_hits_by_document_ids,
@@ -165,13 +166,13 @@ pub struct PutDocResult {
/// Lists all namespaces in the memory system.
pub async fn namespace_list() -> Result<RpcOutcome<Vec<String>>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let namespaces = documents
- .list_namespaces()
- .await
- .map_err(|error| error.to_string())?;
+ let namespaces = match guard.as_documents() {
+ Some(documents) => documents
+ .list_namespaces()
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::namespace_names(&guard).await?,
+ };
Ok(RpcOutcome::single_log(
namespaces,
"memory namespaces listed",
@@ -282,13 +283,14 @@ pub async fn doc_list(
params: Option<NamespaceOnlyParams>,
) -> Result<RpcOutcome<serde_json::Value>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let docs = documents
- .list_documents(params.as_ref().map(|value| value.namespace.as_str()))
- .await
- .map_err(|error| error.to_string())?;
+ let namespace = params.as_ref().map(|value| value.namespace.as_str());
+ let docs = match guard.as_documents() {
+ Some(documents) => documents
+ .list_documents(namespace)
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::document_list(&guard, namespace).await?,
+ };
Ok(RpcOutcome::single_log(docs, "memory documents listed"))
}
@@ -418,13 +420,13 @@ pub async fn memory_list_documents(
request: ListDocumentsRequest,
) -> Result<RpcOutcome<ApiEnvelope<ListDocumentsResponse>>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let raw = documents
- .list_documents(request.namespace.as_deref())
- .await
- .map_err(|error| error.to_string())?;
+ let raw = match guard.as_documents() {
+ Some(documents) => documents
+ .list_documents(request.namespace.as_deref())
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::document_list(&guard, request.namespace.as_deref()).await?,
+ };
let documents = parse_memory_document_summaries(raw)?;
let count = documents.len();
Ok(envelope(
@@ -478,13 +480,13 @@ pub async fn memory_list_namespaces(
_request: EmptyRequest,
) -> Result<RpcOutcome<ApiEnvelope<ListNamespacesResponse>>, String> {
let guard = active_memory_guard().await?;
- let documents = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?;
- let namespaces = documents
- .list_namespaces()
- .await
- .map_err(|error| error.to_string())?;
+ let namespaces = match guard.as_documents() {
+ Some(documents) => documents
+ .list_namespaces()
+ .await
+ .map_err(|error| error.to_string())?,
+ None => fallback::namespace_names(&guard).await?,
+ };
let count = namespaces.len();
Ok(envelope(
ListNamespacesResponse { namespaces, count },
@@ -551,17 +553,26 @@ pub async fn memory_query_namespace(
// (`recall_namespace_memories`), which is a different code path with no
// bus twin — an empty query does not degrade to recency. See the gap
// note in `memory::direct_engine_refs_tests`.
- let hits = guard
- .as_retrieval()
- .ok_or_else(|| "memory driver does not support the retrieval family".to_string())?
- .recall_namespace_scored(
- &request.namespace,
- &request.query,
- retrieval_limit as usize,
- None,
- )
- .await
- .map_err(|error| error.to_string())?;
+ let hits = match guard.as_retrieval() {
+ Some(retrieval) => retrieval
+ .recall_namespace_scored(
+ &request.namespace,
+ &request.query,
+ retrieval_limit as usize,
+ None,
+ )
+ .await
+ .map_err(|error| error.to_string())?,
+ None => {
+ fallback::recall_hits(
+ &guard,
+ &request.namespace,
+ &request.query,
+ retrieval_limit as usize,
+ )
+ .await?
+ }
+ };
let mut context = NamespaceRetrievalContext {
namespace: request.namespace.clone(),
query: Some(request.query.clone()),
@@ -615,12 +626,16 @@ pub async fn memory_recall_context(
// own from the hits.
let result = async {
let guard = active_memory_guard().await?;
- guard
- .as_retrieval()
- .ok_or_else(|| "memory driver does not support the retrieval family".to_string())?
- .recall_namespace_recent(&request.namespace, request.resolved_limit() as usize)
- .await
- .map_err(|e| format!("memory.recall_context: {e}"))
+ let limit = request.resolved_limit() as usize;
+ match guard.as_retrieval() {
+ Some(retrieval) => retrieval
+ .recall_namespace_recent(&request.namespace, limit)
+ .await
+ .map_err(|e| format!("memory.recall_context: {e}")),
+ None => fallback::recent_hits(&guard, &request.namespace, limit)
+ .await
+ .map_err(|e| format!("memory.recall_context: {e}")),
+ }
}
.await;
@@ -652,12 +667,16 @@ pub async fn memory_recall_memories(
) -> Result<RpcOutcome<ApiEnvelope<RecallMemoriesResponse>>, String> {
let result = async {
let guard = active_memory_guard().await?;
- guard
- .as_retrieval()
- .ok_or_else(|| "memory driver does not support the retrieval family".to_string())?
- .recall_namespace_recent(&request.namespace, request.resolved_limit() as usize)
- .await
- .map_err(|e| format!("memory.recall_memories: {e}"))
+ let limit = request.resolved_limit() as usize;
+ match guard.as_retrieval() {
+ Some(retrieval) => retrieval
+ .recall_namespace_recent(&request.namespace, limit)
+ .await
+ .map_err(|e| format!("memory.recall_memories: {e}")),
+ None => fallback::recent_hits(&guard, &request.namespace, limit)
+ .await
+ .map_err(|e| format!("memory.recall_memories: {e}")),
+ }
}
.await;
diff --git a/crates/openhuman-core/src/memory/ops/fallback.rs b/crates/openhuman-core/src/memory/ops/fallback.rs
new file mode 100644
index 0000000000..46edfd7b31
--- /dev/null
+++ b/crates/openhuman-core/src/memory/ops/fallback.rs
@@ -0,0 +1,171 @@
+//! Engine-neutral fallbacks for the user-facing memory RPCs.
+//!
+//! Remote memory engines implement only the mandatory families
+//! (`MemoryCore`, `MemoryRecall`, `MemoryPortability`). The RPCs below used to
+//! require an optional family (`documents`, `retrieval`) and errored out when
+//! bound to such an engine. Each helper here answers the same question from the
+//! mandatory surface, so the core memory experience works on any engine:
+//!
+//! - namespaces: `MemoryCore::namespaces`
+//! - ranked recall: `MemoryRecall::recall`
+//! - recency recall: `MemoryCore::list`, newest first
+//! - document list: `MemoryCore::list`, mapped to document summaries
+//!
+//! Graph and tree stay capability-gated; [`unsupported_family`] builds the
+//! stable error they return, and [`is_unsupported_family_error`] is the
+//! matching detector.
+
+use chrono::{DateTime, Utc};
+use serde_json::{json, Value};
+
+use crate::memory::api::provider::{MemoryCore, MemoryRecall};
+use crate::memory::api::recall::OwnedRecallOpts;
+use crate::memory::api::types::{
+ MemoryEntry, MemoryItemKind, NamespaceMemoryHit, RetrievalScoreBreakdown,
+};
+use crate::memory::guard::MemoryGuard;
+
+/// Stable prefix of every capability-gate error. The UI matches on
+/// `does not support the <family> family`; never reword it.
+pub(crate) const UNSUPPORTED_FAMILY_PREFIX: &str = "memory driver does not support the ";
+
+/// The capability-gate error for `family`.
+pub(crate) fn unsupported_family(family: &str) -> String {
+ format!("{UNSUPPORTED_FAMILY_PREFIX}{family} family")
+}
+
+/// Whether `message` is a capability-gate error built by [`unsupported_family`].
+#[allow(dead_code)]
+pub(crate) fn is_unsupported_family_error(message: &str) -> bool {
+ message.contains(UNSUPPORTED_FAMILY_PREFIX) && message.contains(" family")
+}
+
+fn entry_epoch(entry: &MemoryEntry) -> f64 {
+ DateTime::parse_from_rfc3339(&entry.timestamp)
+ .map(|t| t.with_timezone(&Utc).timestamp() as f64)
+ .unwrap_or(0.0)
+}
+
+/// Map a mandatory-surface entry into the retrieval hit shape the RPC
+/// responses are built from.
+pub(crate) fn entry_to_hit(entry: MemoryEntry, namespace: &str) -> NamespaceMemoryHit {
+ let updated_at = entry_epoch(&entry);
+ let score = entry.score.unwrap_or(0.0);
+ NamespaceMemoryHit {
+ id: entry.id,
+ kind: MemoryItemKind::Kv,
+ namespace: entry.namespace.unwrap_or_else(|| namespace.to_string()),
+ title: Some(entry.key.clone()),
+ key: entry.key,
+ content: entry.content,
+ category: entry.category.to_string(),
+ source_type: Some("recall".to_string()),
+ updated_at,
+ score,
+ score_breakdown: RetrievalScoreBreakdown {
+ keyword_relevance: 0.0,
+ vector_similarity: 0.0,
+ graph_relevance: 0.0,
+ episodic_relevance: 0.0,
+ freshness: 0.0,
+ final_score: score,
+ },
+ document_id: None,
+ chunk_id: None,
+ supporting_relations: Vec::new(),
+ taint: entry.taint,
+ }
+}
+
+/// Namespace names via `MemoryCore::namespaces`.
+pub(crate) async fn namespace_names(guard: &MemoryGuard) -> Result<Vec<String>, String> {
+ log::debug!("[memory:fallback] list_namespaces via MemoryCore::namespaces");
+ let summaries = guard
+ .namespaces()
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(summaries.into_iter().map(|s| s.namespace).collect())
+}
+
+/// Ranked hits via `MemoryRecall::recall`, scoped to `namespace`.
+pub(crate) async fn recall_hits(
+ guard: &MemoryGuard,
+ namespace: &str,
+ query: &str,
+ limit: usize,
+) -> Result<Vec<NamespaceMemoryHit>, String> {
+ log::debug!(
+ "[memory:fallback] ranked recall via MemoryRecall::recall namespace={namespace} limit={limit}"
+ );
+ let opts = OwnedRecallOpts {
+ namespace: Some(namespace.to_string()),
+ ..Default::default()
+ };
+ let entries = guard
+ .recall(query, limit, &opts, None)
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(entries
+ .into_iter()
+ .take(limit)
+ .map(|entry| entry_to_hit(entry, namespace))
+ .collect())
+}
+
+/// Most recently updated hits via `MemoryCore::list`, newest first.
+///
+/// There is no query, so a ranked `recall` cannot answer this: the contract
+/// says an empty query yields nothing.
+pub(crate) async fn recent_hits(
+ guard: &MemoryGuard,
+ namespace: &str,
+ limit: usize,
+) -> Result<Vec<NamespaceMemoryHit>, String> {
+ log::debug!(
+ "[memory:fallback] recency recall via MemoryCore::list namespace={namespace} limit={limit}"
+ );
+ let mut entries = guard
+ .list(Some(namespace), None, None)
+ .await
+ .map_err(|error| error.to_string())?;
+ entries.sort_by(|a, b| entry_epoch(b).total_cmp(&entry_epoch(a)));
+ entries.truncate(limit);
+ Ok(entries
+ .into_iter()
+ .map(|entry| entry_to_hit(entry, namespace))
+ .collect())
+}
+
+/// Document list in the `{"documents": [...]}` shape `list_documents`
+/// returns, built from `MemoryCore::list`.
+pub(crate) async fn document_list(
+ guard: &MemoryGuard,
+ namespace: Option<&str>,
+) -> Result<Value, String> {
+ log::debug!("[memory:fallback] doc_list via MemoryCore::list namespace={namespace:?}");
+ let entries = guard
+ .list(namespace, None, None)
+ .await
+ .map_err(|error| error.to_string())?;
+ let documents = entries
+ .into_iter()
+ .map(|entry| {
+ let ts = entry_epoch(&entry);
+ json!({
+ "document_id": entry.id,
+ "namespace": entry.namespace.or_else(|| namespace.map(str::to_string)).unwrap_or_default(),
+ "key": entry.key,
+ "title": entry.key,
+ "source_type": "memory",
+ "priority": "medium",
+ "created_at": ts,
+ "updated_at": ts,
+ })
+ })
+ .collect::<Vec<_>>();
+ Ok(json!({ "documents": documents }))
+}
+
+#[cfg(test)]
+#[path = "fallback_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/ops/helpers.rs b/crates/openhuman-core/src/memory/ops/helpers.rs
index c9a0bb85c1..4ff175b91c 100644
--- a/crates/openhuman-core/src/memory/ops/helpers.rs
+++ b/crates/openhuman-core/src/memory/ops/helpers.rs
@@ -487,12 +487,13 @@ pub(crate) async fn query_limit_for_request(
return Ok(requested);
}
- let raw = guard
- .as_documents()
- .ok_or_else(|| "memory driver does not support the documents family".to_string())?
- .list_documents(Some(&request.namespace))
- .await
- .map_err(|error| error.to_string())?;
+ let raw = match guard.as_documents() {
+ Some(documents) => documents
+ .list_documents(Some(&request.namespace))
+ .await
+ .map_err(|error| error.to_string())?,
+ None => super::fallback::document_list(guard, Some(&request.namespace)).await?,
+ };
let documents = parse_memory_document_summaries(raw)?;
let total_documents = u32::try_from(documents.len()).unwrap_or(u32::MAX);
Ok(requested.max(total_documents))
diff --git a/crates/openhuman-core/src/memory/ops/kv_graph.rs b/crates/openhuman-core/src/memory/ops/kv_graph.rs
index 17d3f19079..c6d2ae12d5 100644
--- a/crates/openhuman-core/src/memory/ops/kv_graph.rs
+++ b/crates/openhuman-core/src/memory/ops/kv_graph.rs
@@ -164,7 +164,7 @@ pub async fn graph_query(
let guard = active_memory_guard().await?;
let graph = guard
.as_graph()
- .ok_or_else(|| "memory driver does not support the graph family".to_string())?;
+ .ok_or_else(|| super::fallback::unsupported_family("graph"))?;
let rows = graph
.relations(
params.namespace.as_deref(),
diff --git a/crates/openhuman-core/src/memory/ops/mod.rs b/crates/openhuman-core/src/memory/ops/mod.rs
index 4cff527735..1fb1346d43 100644
--- a/crates/openhuman-core/src/memory/ops/mod.rs
+++ b/crates/openhuman-core/src/memory/ops/mod.rs
@@ -27,6 +27,7 @@ pub mod documents;
pub mod engine;
pub mod engine_migrate;
pub mod envelope;
+pub(crate) mod fallback;
pub mod files;
pub mod guard;
#[cfg(test)]