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
refactor(memory): restructure query and raw store modules
Steven Enamakel1b4e56e3e18e
diff --git a/crates/openhuman-core/src/memory/query/backend.rs b/crates/openhuman-core/src/memory/query/backend.rsdeleted file mode 100644index 4c4db6bfa8..0000000000--- a/crates/openhuman-core/src/memory/query/backend.rs+++ /dev/null@@ -1,111 +0,0 @@-//! High-level memory query backend.-//!-//! This module is the orchestration-facing read surface over the summary tree.-//! It deliberately lives under `memory/query` rather than `memory_tree/tree`-//! so the tree module can stay focused on generic structure, policy,-//! summarisation, and read/write mechanics.-//!-//! # Everything here goes through the bound driver-//!-//! These were direct calls into `tinymemory_core::tree::retrieval`, which-//! opened the workspace store in this process. They now resolve the guarded-//! driver and use the `MemoryRetrieval` family, so the loaded module is the-//! only reader — see `docs/specs/2026-08-13-memory-module-port.md` §2.1.-//!-//! `None` is passed for every `scope` argument, and that is not "unrestricted":-//! the guard intersects it with the ambient per-turn allowlist before the call-//! reaches the driver, so naming a scope here could only ever narrow what the-//! turn may see.--use anyhow::Result;--use crate::memory::api::chunks::SourceKind;-use crate::memory::api::provider::{- MemoryProvider, RetrievalHit, RetrievalResponse, SourceRetrievalQuery,-};-use crate::memory::guard::MemoryGuard;-use crate::memory::ops::guard::active_memory_guard;--/// The retrieval family on the active driver, or a caller-facing error.-async fn retrieval() -> Result<std::sync::Arc<MemoryGuard>> {- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory query: {e}"))?;- if guard.as_retrieval().is_none() {- return Err(anyhow::anyhow!(- "memory query: memory driver does not support the retrieval family"- ));- }- Ok(guard)-}--/// Query the per-source summary trees. The global (time-axis) and topic-/// (subject-axis) trees were removed; source trees plus the entity index are-/// the substrate, so this is the only remaining tree-query backend.-pub async fn query_source_scope(- scope: Option<&str>,- time_window_days: Option<u32>,- query: Option<&str>,- limit: usize,-) -> Result<RetrievalResponse> {- let guard = retrieval().await?;- let request = SourceRetrievalQuery {- source_id: scope.map(str::to_string),- source_kind: None,- time_window_days,- query: query.map(str::to_string),- limit,- };- Ok(guard- .as_retrieval()- .expect("checked above")- .retrieve_source(&request, None)- .await?)-}--pub async fn query_source_kind(- source_kind: Option<SourceKind>,- time_window_days: Option<u32>,- query: Option<&str>,- limit: usize,-) -> Result<RetrievalResponse> {- let guard = retrieval().await?;- let request = SourceRetrievalQuery {- source_id: None,- source_kind,- time_window_days,- query: query.map(str::to_string),- limit,- };- Ok(guard- .as_retrieval()- .expect("checked above")- .retrieve_source(&request, None)- .await?)-}--pub async fn drill_down(- node_id: &str,- max_depth: u32,- query: Option<&str>,- limit: Option<usize>,-) -> Result<Vec<RetrievalHit>> {- let guard = retrieval().await?;- Ok(guard- .as_retrieval()- .expect("checked above")- // `None` here is not "unrestricted": the guard resolves the ambient- // task-local scope for a caller that names none, and forwards it- // explicitly. This is host-side code, so the task-local is present.- .retrieve_children(node_id, max_depth, query, limit, None)- .await?)-}--pub async fn fetch_leaves(chunk_ids: &[String]) -> Result<Vec<RetrievalHit>> {- let guard = retrieval().await?;- Ok(guard- .as_retrieval()- .expect("checked above")- .retrieve_leaves(chunk_ids, None)- .await?)-}diff --git a/crates/openhuman-core/src/memory/query/cover_window.rs b/crates/openhuman-core/src/memory/query/cover_window.rsdeleted file mode 100644index 548bfa8989..0000000000--- a/crates/openhuman-core/src/memory/query/cover_window.rs+++ /dev/null@@ -1,123 +0,0 @@-use crate::memory::api::chunks::SourceKind;-use crate::memory::api::provider::{CoverWindowQuery, MemoryProvider};-use crate::memory::ops::guard::active_memory_guard;-use crate::memory::tree::retrieval::rpc::CoverWindowRequest;-use async_trait::async_trait;-use serde_json::json;-use tinytools::{Tool, ToolResult};--/// Agent-facing wrapper for the windowed minimum-cover retrieval. Returns the-/// smallest set of nodes (summaries + raw chunks) covering all memory in-/// `[since_ms, until_ms]`. Built for time-bounded recaps like the morning-/// brief's "last 24h" — see `memory_tree::retrieval::cover`.-pub struct MemoryTreeCoverWindowTool;--#[async_trait]-impl Tool for MemoryTreeCoverWindowTool {- fn name(&self) -> &str {- "memory_tree_cover_window"- }-- fn description(&self) -> &str {- "Return the MINIMUM set of memory nodes covering a time window \- [since_ms, until_ms] (epoch-milliseconds): condensed summaries where a \- whole stretch is in-window, raw recent chunks otherwise. Grouped by \- source, ordered oldest→newest. Use for time-bounded recaps (e.g. a \- last-24h morning brief) instead of `query_source` (which is all-time)."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "since_ms": {- "type": "integer",- "description": "Inclusive window start, epoch-milliseconds."- },- "until_ms": {- "type": "integer",- "description": "Inclusive window end, epoch-milliseconds."- },- "source_id": {- "type": "string",- "description": "Exact source id (e.g. `slack:#eng`, `gmail:abc`)."- },- "source_kind": {- "type": "string",- "enum": ["chat", "email", "document"],- "description": "Source kind filter when no exact id is known."- },- "limit": {- "type": "integer",- "minimum": 0,- "description": "Max hits to return (default 200)."- }- },- "required": ["since_ms", "until_ms"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][memory_tree] cover_window invoked");- let req: CoverWindowRequest = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_tree_cover_window: {e}"))?;- // Correlation fields only — source_id can carry PII, so log its presence,- // not its value.- log::debug!(- "[tool][memory_tree] cover_window parsed since_ms={} until_ms={} has_source_id={} has_source_kind={} has_limit={}",- req.since_ms,- req.until_ms,- req.source_id.is_some(),- req.source_kind.is_some(),- req.limit.is_some()- );- // Validate arguments before touching config/disk — `SourceKind::parse`- // is pure, so a bad `source_kind` must fail with the parse error- // regardless of workspace state.- let source_kind = match req.source_kind.as_deref() {- Some(s) => {- log::trace!("[tool][memory_tree] cover_window parse_source_kind");- Some(- SourceKind::parse(s)- .map_err(|e| anyhow::anyhow!("memory_tree_cover_window: {e}"))?,- )- }- None => None,- };- log::trace!(- "[tool][memory_tree] cover_window dispatch limit={}",- req.limit.unwrap_or(0)- );- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_tree_cover_window: {e}"))?;- let window = CoverWindowQuery {- since_ms: req.since_ms,- until_ms: req.until_ms,- source_id: req.source_id.clone(),- source_kind,- limit: req.limit,- };- let resp = guard- .as_retrieval()- .ok_or_else(|| {- anyhow::anyhow!(- "memory_tree_cover_window: memory driver does not support the retrieval family"- )- })?- .cover_window(&window, None)- .await- .map_err(|e| anyhow::anyhow!("memory_tree_cover_window: {e}"))?;- log::debug!(- "[tool][memory_tree] cover_window returning hits={} total={}",- resp.hits.len(),- resp.total- );- let json = serde_json::to_string(&resp)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "cover_window_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/query/cover_window_tests.rs b/crates/openhuman-core/src/memory/query/cover_window_tests.rsdeleted file mode 100644index c63b88157e..0000000000--- a/crates/openhuman-core/src/memory/query/cover_window_tests.rs+++ /dev/null@@ -1,35 +0,0 @@-use super::*;-use serde_json::json;-use tinytools::Tool;--#[test]-fn parameters_schema_requires_window_bounds() {- let schema = MemoryTreeCoverWindowTool.parameters_schema();- let required = schema.get("required").and_then(|r| r.as_array()).unwrap();- assert!(required.iter().any(|v| v.as_str() == Some("since_ms")));- assert!(required.iter().any(|v| v.as_str() == Some("until_ms")));-}--#[tokio::test]-async fn execute_rejects_missing_window_bounds() {- let err = MemoryTreeCoverWindowTool- .execute(json!({ "source_kind": "chat" }))- .await- .expect_err("missing since_ms/until_ms should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tree_cover_window"));-}--#[tokio::test]-async fn execute_rejects_invalid_source_kind() {- let err = MemoryTreeCoverWindowTool- .execute(json!({ "since_ms": 0, "until_ms": 1, "source_kind": "not-real" }))- .await- .expect_err("invalid source kind should fail");- let msg = err.to_string();- assert!(- msg.contains("memory_tree_cover_window:") && !msg.contains("load config failed"),- "expected a source-kind parse error, got: {msg}"- );-}diff --git a/crates/openhuman-core/src/memory/query/drill_down.rs b/crates/openhuman-core/src/memory/query/drill_down.rsdeleted file mode 100644index 9dfc2313cf..0000000000--- a/crates/openhuman-core/src/memory/query/drill_down.rs+++ /dev/null@@ -1,77 +0,0 @@-use crate::memory::query::backend;-use crate::memory::tree::retrieval::rpc::DrillDownRequest;-use async_trait::async_trait;-use serde_json::json;-use tinytools::{Tool, ToolResult};--pub struct MemoryTreeDrillDownTool;--#[async_trait]-impl Tool for MemoryTreeDrillDownTool {- fn name(&self) -> &str {- "memory_tree_drill_down"- }-- fn description(&self) -> &str {- "Walk a summary node's children one step (or more if `max_depth > \- 1`). Returns leaf chunks for an L1 summary, or lower-level \- summaries for L2+. Use this when a `query_*` summary is too coarse \- and you want to expand it. Pass `query` to rerank children by \- cosine similarity."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "node_id": {- "type": "string",- "description": "Id of the summary (or leaf) to expand."- },- "max_depth": {- "type": "integer",- "minimum": 1,- "description": "How many levels down to walk (default 1)."- },- "query": {- "type": "string",- "description": "Optional natural-language query — when set, children are reranked by cosine similarity."- },- "limit": {- "type": "integer",- "minimum": 0,- "description": "Optional cap on returned hits, applied after rerank."- }- },- "required": ["node_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][memory_tree] drill_down invoked");- let req: DrillDownRequest = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_tree_drill_down: {e}"))?;- if matches!(req.max_depth, Some(0)) {- return Err(anyhow::anyhow!(- "memory_tree_drill_down: max_depth must be >= 1"- ));- }- let hits = backend::drill_down(- &req.node_id,- req.max_depth.unwrap_or(1),- req.query.as_deref(),- req.limit,- )- .await?;- log::debug!(- "[tool][memory_tree] drill_down returning hits={}",- hits.len()- );- let json = serde_json::to_string(&hits)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "drill_down_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/query/drill_down_tests.rs b/crates/openhuman-core/src/memory/query/drill_down_tests.rsdeleted file mode 100644index 6f59695691..0000000000--- a/crates/openhuman-core/src/memory/query/drill_down_tests.rs+++ /dev/null@@ -1,134 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use serde_json::json;-use tinytools::Tool;--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- std::env::set_var("OPENHUMAN_WORKSPACE", path);- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn parameters_schema_requires_node_id() {- let tool = MemoryTreeDrillDownTool;- let schema = tool.parameters_schema();- assert_eq!(schema["required"], json!(["node_id"]));- assert_eq!(schema["properties"]["max_depth"]["minimum"], 1);-}--#[test]-fn drill_down_request_deserializes_optional_fields() {- let req: DrillDownRequest = serde_json::from_value(json!({- "node_id": "summary-1",- "max_depth": 2,- "query": "deployment blockers",- "limit": 7- }))- .unwrap();- assert_eq!(req.node_id, "summary-1");- assert_eq!(req.max_depth, Some(2));- assert_eq!(req.query.as_deref(), Some("deployment blockers"));- assert_eq!(req.limit, Some(7));-}--#[tokio::test]-async fn execute_rejects_missing_node_id() {- let tool = MemoryTreeDrillDownTool;- let err = tool- .execute(json!({}))- .await- .expect_err("missing node_id should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tree_drill_down"));-}--#[tokio::test]-async fn execute_rejects_zero_max_depth() {- let tool = MemoryTreeDrillDownTool;- let err = tool- .execute(json!({- "node_id": "summary-1",- "max_depth": 0- }))- .await- .expect_err("max_depth=0 should fail at tool boundary");- assert!(err.to_string().contains("max_depth must be >= 1"));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the summary tree through the bound driver, not the in-process engine"]-async fn execute_success_path_returns_empty_json_array_for_isolated_workspace() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeDrillDownTool;- let result = tool- .execute(json!({- "node_id": "summary-does-not-exist",- "max_depth": 1- }))- .await- .expect("valid drill_down request should succeed in isolated workspace");- assert!(!result.is_error);- let payload = result.text();- let parsed: serde_json::Value =- serde_json::from_str(&payload).expect("result should be valid json");- assert!(- parsed.is_array(),- "drill_down should serialize a JSON array"- );- assert_eq!(parsed, json!([]));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the summary tree through the bound driver, not the in-process engine"]-async fn execute_accepts_query_and_limit_together() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeDrillDownTool;- let result = tool- .execute(json!({- "node_id": "summary-does-not-exist",- "max_depth": 2,- "query": "deployment blockers",- "limit": 5- }))- .await- .expect("query+limit drill_down should succeed");- assert!(!result.is_error);-}diff --git a/crates/openhuman-core/src/memory/query/fast_walk.rs b/crates/openhuman-core/src/memory/query/fast_walk.rsdeleted file mode 100644index 90dfcb2b78..0000000000--- a/crates/openhuman-core/src/memory/query/fast_walk.rs+++ /dev/null@@ -1,76 +0,0 @@-//! Deterministic replacement for the former agentic `walk` / `smart_walk`-//! tool modes.-//!-//! Both modes now resolve to [`fast_retrieve`] — the E2GraphRAG, LLM-free-//! retriever. It returns a structured [`QueryResponse`] of ranked evidence-//! (no synthesized prose); a higher-level context agent composes the answer.--use crate::memory::api::provider::{FastRetrieveQuery, MemoryProvider};-use crate::memory::ops::guard::active_memory_guard;-use tinytools::ToolResult;--/// Parse the shared `memory_tree` args and run deterministic retrieval.-/// Accepts `query` (required), `limit`, `time_window_days`, and `max_hops`.-pub async fn run_fast_walk(args: serde_json::Value) -> anyhow::Result<ToolResult> {- let query = args- .get("query")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();- if query.trim().is_empty() {- return Err(anyhow::anyhow!("memory_tree walk: `query` is required"));- }-- let limit = args- .get("limit")- .and_then(|v| v.as_u64())- .map(|n| n as usize)- .unwrap_or(10);- let time_window_days = args- .get("time_window_days")- .and_then(|v| v.as_u64())- .map(|n| n as u32);- let max_hops = args- .get("max_hops")- .and_then(|v| v.as_u64())- .map(|n| n as u32)- .unwrap_or(2);-- log::debug!(- "[tool][memory_tree] walk (deterministic) query_len={} limit={} max_hops={} window={:?}",- query.len(),- limit,- max_hops,- time_window_days- );-- // Routed through the bound driver. `None` for the scope is not- // "unrestricted": the guard intersects it with the ambient per-turn- // allowlist, so the source gate still applies.- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_tree walk: {e}"))?;- let opts = FastRetrieveQuery {- limit,- max_hops,- time_window_days,- };- let resp = guard- .as_retrieval()- .ok_or_else(|| {- anyhow::anyhow!("memory_tree walk: memory driver does not support the retrieval family")- })?- .fast_retrieve(&query, opts, None)- .await?;- log::debug!(- "[tool][memory_tree] walk returning hits={} total={}",- resp.hits.len(),- resp.total- );- let json = serde_json::to_string(&resp)?;- Ok(ToolResult::success(json))-}--#[cfg(test)]-#[path = "fast_walk_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/query/fast_walk_tests.rs b/crates/openhuman-core/src/memory/query/fast_walk_tests.rsdeleted file mode 100644index b9cee31da7..0000000000--- a/crates/openhuman-core/src/memory/query/fast_walk_tests.rs+++ /dev/null@@ -1,14 +0,0 @@-use super::*;-use serde_json::json;--#[tokio::test]-async fn missing_query_errors() {- let err = run_fast_walk(json!({})).await.unwrap_err();- assert!(err.to_string().contains("`query` is required"));-}--#[tokio::test]-async fn blank_query_errors() {- let err = run_fast_walk(json!({"query": " "})).await.unwrap_err();- assert!(err.to_string().contains("`query` is required"));-}diff --git a/crates/openhuman-core/src/memory/query/fetch_leaves.rs b/crates/openhuman-core/src/memory/query/fetch_leaves.rsdeleted file mode 100644index 8b8c56df5e..0000000000--- a/crates/openhuman-core/src/memory/query/fetch_leaves.rs+++ /dev/null@@ -1,68 +0,0 @@-use crate::memory::query::backend;-use crate::memory::tree::retrieval::rpc::FetchLeavesRequest;-use async_trait::async_trait;-use serde_json::json;-use tinytools::{Tool, ToolResult};--/// Hard cap on `chunk_ids` enforced at the tool boundary so the tool's-/// behaviour matches the schema description. The retrieval RPC also-/// truncates internally; we mirror that here so excess ids are dropped-/// rather than silently passed through.-const MAX_CHUNK_IDS_PER_CALL: usize = 20;--pub struct MemoryTreeFetchLeavesTool;--#[async_trait]-impl Tool for MemoryTreeFetchLeavesTool {- fn name(&self) -> &str {- "memory_tree_fetch_leaves"- }-- fn description(&self) -> &str {- "Batch-fetch raw chunk rows by id (max 20 per call). Use this when \- you need verbatim content for a citation — the `content` and \- `source_ref` fields on each hit are the authoritative quote source."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "chunk_ids": {- "type": "array",- "items": {"type": "string"},- "description": "Chunk ids to hydrate. Capped at 20 per call."- }- },- "required": ["chunk_ids"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let req: FetchLeavesRequest = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_tree_fetch_leaves: {e}"))?;- log::debug!(- "[rpc][memory_tree] fetch_leaves invoked requested_ids={}",- req.chunk_ids.len()- );- let take = req.chunk_ids.len().min(MAX_CHUNK_IDS_PER_CALL);- if req.chunk_ids.len() > MAX_CHUNK_IDS_PER_CALL {- log::debug!(- "[rpc][memory_tree] fetch_leaves truncating requested_ids={} truncated_to={}",- req.chunk_ids.len(),- MAX_CHUNK_IDS_PER_CALL- );- }- let hits = backend::fetch_leaves(&req.chunk_ids[..take]).await?;- log::debug!(- "[rpc][memory_tree] fetch_leaves completed hits={}",- hits.len()- );- let json = serde_json::to_string(&hits)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "fetch_leaves_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/query/fetch_leaves_tests.rs b/crates/openhuman-core/src/memory/query/fetch_leaves_tests.rsdeleted file mode 100644index ff7978cb56..0000000000--- a/crates/openhuman-core/src/memory/query/fetch_leaves_tests.rs+++ /dev/null@@ -1,131 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use serde_json::json;-use tinytools::Tool;--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- std::env::set_var("OPENHUMAN_WORKSPACE", path);- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn parameters_schema_requires_chunk_ids() {- let tool = MemoryTreeFetchLeavesTool;- let schema = tool.parameters_schema();- assert_eq!(schema["required"], json!(["chunk_ids"]));- assert_eq!(schema["properties"]["chunk_ids"]["type"], "array");-}--#[test]-fn max_chunk_ids_per_call_matches_description() {- assert_eq!(MAX_CHUNK_IDS_PER_CALL, 20);-}--#[test]-fn request_slice_is_truncated_to_cap() {- let ids: Vec<String> = (0..25).map(|i| format!("chunk-{i}")).collect();- let take = ids.len().min(MAX_CHUNK_IDS_PER_CALL);- assert_eq!(take, 20);- assert_eq!(ids[..take].len(), 20);- assert_eq!(ids[..take].first().map(String::as_str), Some("chunk-0"));- assert_eq!(ids[..take].last().map(String::as_str), Some("chunk-19"));-}--#[tokio::test]-async fn execute_rejects_missing_chunk_ids() {- let tool = MemoryTreeFetchLeavesTool;- let err = tool- .execute(json!({}))- .await- .expect_err("missing chunk_ids should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tree_fetch_leaves"));-}--#[tokio::test]-async fn execute_rejects_wrong_type_for_chunk_ids() {- let tool = MemoryTreeFetchLeavesTool;- let err = tool- .execute(json!({"chunk_ids": "not-an-array"}))- .await- .expect_err("wrong chunk_ids type should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tree_fetch_leaves"));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the summary tree through the bound driver, not the in-process engine"]-async fn execute_success_path_returns_empty_json_array_for_isolated_workspace() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeFetchLeavesTool;- let result = tool- .execute(json!({- "chunk_ids": ["chunk-does-not-exist-1", "chunk-does-not-exist-2"]- }))- .await- .expect("valid fetch_leaves request should succeed in isolated workspace");- assert!(!result.is_error);- let payload = result.text();- let parsed: serde_json::Value =- serde_json::from_str(&payload).expect("result should be valid json");- assert!(- parsed.is_array(),- "fetch_leaves should serialize a JSON array"- );- assert_eq!(parsed, json!([]));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the summary tree through the bound driver, not the in-process engine"]-async fn execute_truncates_requests_to_twenty_ids() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeFetchLeavesTool;- let ids: Vec<String> = (0..25).map(|i| format!("chunk-{i}")).collect();- let result = tool- .execute(json!({ "chunk_ids": ids }))- .await- .expect("over-cap request should still succeed");- assert!(!result.is_error);- let parsed: serde_json::Value =- serde_json::from_str(&result.text()).expect("result should be valid json");- assert_eq!(parsed, json!([]));-}diff --git a/crates/openhuman-core/src/memory/query/mod_memory_tree_dispatcher_tests_tests.rs b/crates/openhuman-core/src/memory/query/mod_memory_tree_dispatcher_tests_tests.rsdeleted file mode 100644index 5fcd813cee..0000000000--- a/crates/openhuman-core/src/memory/query/mod_memory_tree_dispatcher_tests_tests.rs+++ /dev/null@@ -1,97 +0,0 @@-use super::*;-use crate::memory::query::test_workspace::isolated_config;-use serde_json::json;-use tempfile::TempDir;-use tinytools::Tool;--#[test]-fn memory_tree_tool_name_is_correct() {- assert_eq!(MemoryTreeTool.name(), "memory_tree");-}--#[test]-fn memory_tree_schema_requires_mode() {- let schema = MemoryTreeTool.parameters_schema();- let required = schema.get("required").and_then(|r| r.as_array()).unwrap();- assert!(required.iter().any(|v| v.as_str() == Some("mode")));-}--#[test]-fn memory_tree_schema_mode_enum_has_all_modes() {- let schema = MemoryTreeTool.parameters_schema();- let modes: Vec<&str> = schema- .get("properties")- .unwrap()- .get("mode")- .unwrap()- .get("enum")- .unwrap()- .as_array()- .unwrap()- .iter()- .filter_map(|v| v.as_str())- .collect();- assert!(modes.contains(&"search_entities"));- assert!(modes.contains(&"query_source"));- assert!(modes.contains(&"drill_down"));- assert!(modes.contains(&"cover_window"));- assert!(modes.contains(&"fetch_leaves"));- assert!(modes.contains(&"ingest_document"));- assert!(modes.contains(&"walk"));- assert!(modes.contains(&"smart_walk"));- // Removed with the global/topic trees.- assert!(!modes.contains(&"query_topic"));- assert!(!modes.contains(&"query_global"));-}--#[test]-fn memory_tree_schema_exposes_source_window_days() {- let schema = MemoryTreeTool.parameters_schema();- let properties = schema- .get("properties")- .and_then(|p| p.as_object())- .unwrap();- assert!(properties.contains_key("time_window_days"));-}--#[tokio::test]-async fn memory_tree_unknown_mode_returns_error() {- let result = MemoryTreeTool- .execute(json!({"mode": "invalid_mode"}))- .await;- assert!(result.is_err());- let msg = result.unwrap_err().to_string();- assert!(- msg.contains("unknown mode"),- "Expected 'unknown mode' in: {msg}"- );-}--#[tokio::test]-async fn memory_tree_missing_mode_returns_error() {- let result = MemoryTreeTool.execute(json!({})).await;- assert!(result.is_err());-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the summary tree through the bound driver, not the in-process engine"]-async fn memory_tree_fetch_leaves_mode_dispatches_successfully() {- // `fetch_leaves` loads config from `OPENHUMAN_WORKSPACE`. Without an- // isolated workspace this races sibling tests whose `TempDir` is- // deleted mid-call ("Failed to create temporary config file ... No- // such file or directory").- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let result = MemoryTreeTool- .execute(json!({- "mode": "fetch_leaves",- "chunk_ids": ["chunk-does-not-exist"]- }))- .await- .expect("fetch_leaves mode should dispatch successfully");- assert!(!result.is_error);- let parsed: serde_json::Value =- serde_json::from_str(&result.text()).expect("result should be valid json");- assert!(parsed.is_array());-}diff --git a/crates/openhuman-core/src/memory/query/query_source.rs b/crates/openhuman-core/src/memory/query/query_source.rsdeleted file mode 100644index 072ef2b867..0000000000--- a/crates/openhuman-core/src/memory/query/query_source.rs+++ /dev/null@@ -1,101 +0,0 @@-use crate::memory::api::chunks::SourceKind;-use crate::memory::query::backend;-use crate::memory::tree::retrieval::rpc::QuerySourceRequest;-use async_trait::async_trait;-use serde_json::json;-use tinytools::{Tool, ToolResult};--pub struct MemoryTreeQuerySourceTool;--#[async_trait]-impl Tool for MemoryTreeQuerySourceTool {- fn name(&self) -> &str {- "memory_tree_query_source"- }-- fn description(&self) -> &str {- "Return summaries from per-source memory trees, optionally filtered \- by `source_id` (exact), `source_kind` (chat/email/document) and/or \- `time_window_days`. Use this for intents like \"in my email last \- week...\" or \"summarise our slack #eng activity\". Newest-first \- by default; pass `query` for semantic rerank."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "source_id": {- "type": "string",- "description": "Exact source id (e.g. `slack:#eng`, `gmail:abc`)."- },- "source_kind": {- "type": "string",- "enum": ["chat", "email", "document"],- "description": "Source kind filter when no exact id is known."- },- "time_window_days": {- "type": "integer",- "minimum": 0,- "description": "Only return summaries whose time range overlaps the last N days."- },- "query": {- "type": "string",- "description": "Optional natural-language query for cosine-similarity rerank."- },- "limit": {- "type": "integer",- "minimum": 0,- "description": "Max hits to return (default 10)."- }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][memory_tree] query_source invoked");- let req: QuerySourceRequest = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_tree_query_source: {e}"))?;- // Validate arguments before touching config/disk — `SourceKind::parse`- // is pure, so a bad `source_kind` must fail with the parse error- // regardless of workspace state.- let source_kind = match req.source_kind.as_deref() {- Some(s) => Some(- SourceKind::parse(s)- .map_err(|e| anyhow::anyhow!("memory_tree_query_source: {e}"))?,- ),- None => None,- };- let resp = match req.source_id.as_deref() {- Some(source_id) => {- backend::query_source_scope(- Some(source_id),- req.time_window_days,- req.query.as_deref(),- req.limit.unwrap_or(10),- )- .await?- }- None => {- backend::query_source_kind(- source_kind,- req.time_window_days,- req.query.as_deref(),- req.limit.unwrap_or(10),- )- .await?- }- };- log::debug!(- "[tool][memory_tree] query_source returning hits={} total={}",- resp.hits.len(),- resp.total- );- let json = serde_json::to_string(&resp)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "query_source_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/query/query_source_tests.rs b/crates/openhuman-core/src/memory/query/query_source_tests.rsdeleted file mode 100644index c9f5c7a1b1..0000000000--- a/crates/openhuman-core/src/memory/query/query_source_tests.rs+++ /dev/null@@ -1,128 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use serde_json::json;-use tinytools::Tool;--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- std::env::set_var("OPENHUMAN_WORKSPACE", path);- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn parameters_schema_exposes_supported_source_filters() {- let tool = MemoryTreeQuerySourceTool;- let schema = tool.parameters_schema();- assert_eq!(schema["type"], "object");- assert_eq!(- schema["properties"]["source_kind"]["enum"],- json!(["chat", "email", "document"])- );- assert_eq!(schema["properties"]["time_window_days"]["minimum"], 0);-}--#[tokio::test]-async fn execute_rejects_invalid_source_kind() {- let tool = MemoryTreeQuerySourceTool;- let err = tool- .execute(json!({- "source_kind": "not-real"- }))- .await- .expect_err("invalid source kind should fail");- let msg = err.to_string();- assert!(- msg.contains("memory_tree_query_source:") && !msg.contains("load config failed"),- "expected a source-kind parse error, got: {msg}"- );-}--#[tokio::test]-async fn execute_rejects_wrong_type_for_limit() {- let tool = MemoryTreeQuerySourceTool;- let err = tool- .execute(json!({- "limit": "five"- }))- .await- .expect_err("wrong limit type should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tree_query_source"));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the summary tree through the bound driver, not the in-process engine"]-async fn execute_success_path_returns_empty_payload_for_isolated_workspace() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeQuerySourceTool;- let result = tool- .execute(json!({- "source_kind": "document",- "limit": 2- }))- .await- .expect("valid query_source should succeed in isolated workspace");- assert!(!result.is_error);- let payload = result.text();- let parsed: serde_json::Value =- serde_json::from_str(&payload).expect("result should be valid json");- assert!(parsed.get("hits").is_some(), "payload should include hits");- assert!(- parsed.get("total").is_some(),- "payload should include total"- );- assert_eq!(parsed["hits"], json!([]));- assert_eq!(parsed["total"], json!(0));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the summary tree through the bound driver, not the in-process engine"]-async fn execute_accepts_exact_source_id_without_source_kind() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeQuerySourceTool;- let result = tool- .execute(json!({- "source_id": "slack:#eng",- "limit": 1- }))- .await- .expect("source_id-only query should succeed");- assert!(!result.is_error);-}diff --git a/crates/openhuman-core/src/memory/query/search_entities.rs b/crates/openhuman-core/src/memory/query/search_entities.rsdeleted file mode 100644index e9976b7b47..0000000000--- a/crates/openhuman-core/src/memory/query/search_entities.rs+++ /dev/null@@ -1,99 +0,0 @@-use crate::memory::api::provider::MemoryProvider;-use crate::memory::ops::guard::active_memory_guard;-use crate::memory::tree::retrieval::rpc::SearchEntitiesRequest;-use async_trait::async_trait;-use serde_json::json;-use tinytools::{Tool, ToolResult};--pub struct MemoryTreeSearchEntitiesTool;--#[async_trait]-impl Tool for MemoryTreeSearchEntitiesTool {- fn name(&self) -> &str {- "memory_tree_search_entities"- }-- fn description(&self) -> &str {- "Free-text LIKE search over the entity index — resolve a name or \- handle to a canonical id (e.g. \"alice\" -> \- `email:[email protected]`). ALWAYS call this first when the user \- mentions someone by name before a `memory_tree` retrieval \- (`query_source` / `smart_walk` / `walk`) keyed on that id."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "Substring to match (case-insensitive)."- },- "kinds": {- "type": "array",- "items": {- "type": "string",- "enum": [- "email", "url", "handle", "hashtag", "person",- "organization", "location", "event", "product",- "misc", "topic"- ]- },- "description": "Optional kind filter — restrict to these entity kinds only."- },- "limit": {- "type": "integer",- "minimum": 0,- "description": "Max matches (default 5, clamped to 100)."- }- },- "required": ["query"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][memory_tree] search_entities invoked");- let req: SearchEntitiesRequest = serde_json::from_value(args).map_err(|e| {- anyhow::anyhow!("invalid arguments for memory_tree_search_entities: {e}")- })?;- // `kinds` is **not** validated here any more, and that is a deliberate- // move rather than an omission.- //- // Entity kinds are an open vocabulary on the wire (see- // `memory::api::provider::retrieval`): the engine's own `EntityKind` is- // `#[non_exhaustive]` and has grown twice, so a closed host-side copy- // would either reject a kind the engine understands or drift silently- // out of date. The driver owns the vocabulary and rejects an unknown- // kind with `Invalid`.- //- // The cost is real and worth naming: a bad `kinds` value used to fail- // without a workspace, and now needs a bound driver to fail. The- // alternative — duplicating an open vocabulary host-side — is the- // failure mode this contract was shaped to avoid.- let limit = req.limit.unwrap_or(5).min(100);- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_tree_search_entities: {e}"))?;- let matches = guard- .as_retrieval()- .ok_or_else(|| {- anyhow::anyhow!(- "memory_tree_search_entities: memory driver does not support the \- retrieval family"- )- })?- .search_entities(&req.query, req.kinds.as_deref(), limit)- .await- .map_err(|e| anyhow::anyhow!("memory_tree_search_entities: {e}"))?;- log::debug!(- "[tool][memory_tree] search_entities returning matches={}",- matches.len()- );- let json = serde_json::to_string(&matches)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "search_entities_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/query/search_entities_tests.rs b/crates/openhuman-core/src/memory/query/search_entities_tests.rsdeleted file mode 100644index 4e86a78e61..0000000000--- a/crates/openhuman-core/src/memory/query/search_entities_tests.rs+++ /dev/null@@ -1,154 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use serde_json::json;-use tinytools::Tool;--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- std::env::set_var("OPENHUMAN_WORKSPACE", path);- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn parameters_schema_requires_query() {- let tool = MemoryTreeSearchEntitiesTool;- let schema = tool.parameters_schema();- assert_eq!(schema["required"], json!(["query"]));- assert_eq!(- schema["properties"]["limit"]["description"].is_string(),- true- );-}--#[test]-fn kind_enum_contains_expected_memory_entity_kinds() {- let tool = MemoryTreeSearchEntitiesTool;- let schema = tool.parameters_schema();- let kinds = schema["properties"]["kinds"]["items"]["enum"]- .as_array()- .unwrap();- for required in ["email", "person", "organization", "topic"] {- assert!(- kinds.iter().any(|v| v == required),- "missing kind {required}"- );- }-}--#[tokio::test]-async fn execute_rejects_missing_query() {- let tool = MemoryTreeSearchEntitiesTool;- let err = tool- .execute(json!({}))- .await- .expect_err("missing query should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tree_search_entities"));-}--/// An unknown `kinds` value is refused — by the **driver**, not the host.-///-/// This used to assert that validation happened before any workspace was-/// touched, because the host owned a closed copy of the engine's-/// `EntityKind`. It no longer does: the vocabulary is open on the wire and-/// the driver is its authority. With no module artifact bound, the failure-/// now surfaces as the driver being unable to serve the family, which is-/// still a refusal of the same request — but it is a weaker guarantee than-/// the pure-function check it replaced, so it is called out rather than-/// quietly relaxed.-#[tokio::test]-#[ignore = "needs a built tinymemory module (TINYMEMORY_TEST_MODULE) and its own process: \-kind validation moved into the driver with the open entity-kind vocabulary"]-async fn execute_rejects_invalid_kind_after_validation() {- let tool = MemoryTreeSearchEntitiesTool;- let err = tool- .execute(json!({- "query": "alice",- "kinds": ["not-a-real-kind"]- }))- .await- .expect_err("invalid kind should fail");- assert!(err.to_string().contains("memory_tree_search_entities:"));-}--/// The parity half of this test is gone with the split brain.-///-/// It used to run the tool and then call `retrieval::search_entities`-/// directly on the same workspace, asserting both saw an empty store. That-/// second call is exactly the in-process engine access this port removes —-/// there is no longer a second reader to agree with.-#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads entities through the bound driver, not the in-process engine"]-async fn execute_success_path_returns_empty_json_array_for_isolated_workspace() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeSearchEntitiesTool;- let result = tool- .execute(json!({- "query": "alice",- "limit": 3- }))- .await- .expect("valid search_entities request should succeed in isolated workspace");- assert!(!result.is_error);- let payload = result.text();- let parsed: serde_json::Value =- serde_json::from_str(&payload).expect("result should be valid json");- assert!(- parsed.is_array(),- "search_entities should serialize a JSON array"- );- assert_eq!(parsed, json!([]));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads entities through the bound driver, not the in-process engine"]-async fn execute_accepts_kind_filter_and_clamps_large_limit() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryTreeSearchEntitiesTool;- let result = tool- .execute(json!({- "query": "alice",- "kinds": ["email", "person"],- "limit": 999- }))- .await- .expect("filtered search_entities request should succeed");- assert!(!result.is_error);-}diff --git a/crates/openhuman-core/src/memory/tools/raw_store/kinds.rs b/crates/openhuman-core/src/memory/tools/raw_store/kinds.rsdeleted file mode 100644index 10f1fac56b..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/kinds.rs+++ /dev/null@@ -1,66 +0,0 @@-//! `memory_store_kinds` — introspection. Enumerate every storage shape the-//! bound driver persists, so an agent can plan a fan-out without hard-coding.-//!-//! The catalog comes from the driver rather than from a compiled-in list: it is-//! the engine's own vocabulary, and a host-side copy drifts. This one had —-//! the description below used to advertise `content`, `document` and `graph`,-//! none of which exist, while omitting `raw` and `entity`, which do.--use async_trait::async_trait;-use serde_json::{json, Value};--use crate::memory::api::provider::MemoryProvider;-use crate::memory::ops::guard::active_memory_guard;-use tinytools::{Tool, ToolExposure, ToolResult};--pub struct MemoryStoreKindsTool;--#[async_trait]-impl Tool for MemoryStoreKindsTool {- /// Superseded by the `memory` tool, which dispatches every memory- /// operation on one `action` field. Kept registered and dispatchable so a- /// replayed transcript or a saved skill naming `memory_*` keeps working;- /// hidden from the wire so eleven schemas do not ship where one does.- fn exposure(&self) -> ToolExposure {- ToolExposure::Hidden- }-- fn name(&self) -> &str {- "memory_store_kinds"- }-- fn description(&self) -> &str {- "Return the catalog of memory_store storage kinds the active memory \- driver persists. No arguments. Use when planning a multi-kind \- retrieval fan-out."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][memory_store] kinds start");- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_store_kinds: {e}"))?;- let kinds = guard- .as_chunks()- .ok_or_else(|| {- anyhow::anyhow!(- "memory_store_kinds: memory driver does not support the chunk family"- )- })?- .storage_kinds()- .await- .map_err(|e| anyhow::anyhow!("memory_store_kinds: {e}"))?;- log::debug!("[tool][memory_store] kinds success count={}", kinds.len());- Ok(ToolResult::success(serde_json::to_string(- &json!({ "kinds": kinds }),- )?))- }-}--#[cfg(test)]-#[path = "kinds_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/raw_store/kinds_tests.rs b/crates/openhuman-core/src/memory/tools/raw_store/kinds_tests.rsdeleted file mode 100644index 6df451bde0..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/kinds_tests.rs+++ /dev/null@@ -1,26 +0,0 @@-use super::*;--#[test]-fn parameters_schema_is_empty_object() {- let tool = MemoryStoreKindsTool;- let schema = tool.parameters_schema();- assert_eq!(schema["type"], "object");- assert_eq!(schema["properties"], json!({}));-}--/// The catalog is the driver's now, so this needs one bound.-///-/// It used to assert against `MemoryKind::ALL` compiled into this crate,-/// which is exactly the host-side copy that had drifted from the engine.-#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the catalog is read from the bound driver, not a compiled-in list"]-async fn execute_returns_the_drivers_storage_kinds() {- let tool = MemoryStoreKindsTool;- let result = tool.execute(Value::Null).await.unwrap();- let parsed: serde_json::Value = serde_json::from_str(&result.output()).unwrap();- assert!(- parsed["kinds"].as_array().is_some_and(|k| !k.is_empty()),- "a bound driver must report a non-empty catalog"- );-}diff --git a/crates/openhuman-core/src/memory/tools/raw_store/mod.rs b/crates/openhuman-core/src/memory/tools/raw_store/mod.rsdeleted file mode 100644index b7000aab39..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/mod.rs+++ /dev/null@@ -1,27 +0,0 @@-//! Raw search/retrieve tools surfaced to the agent harness.-//!-//! These tools expose the storage layer directly — no policy, no scoring-//! beyond what the underlying backend already applies. They exist so an agent-//! can drop one layer below the curated `memory_tree_*` tools when it needs-//! to inspect or operate on raw memory_store rows.-//!-//! Three tools, one per major access pattern:-//! - [`MemoryStoreRawSearchTool`] — hybrid (vector+keyword) namespace query.-//! - [`MemoryStoreRawChunksTool`] — structured chunk filter by source/owner/-//! time/tags.-//! - [`MemoryStoreKindsTool`] — introspection: enumerate every-//! [`MemoryKind`] the store supports.-//!-//! All three are async, return JSON, and follow the project Tool trait.--mod kinds;-mod raw_chunks;-mod raw_search;--pub use kinds::MemoryStoreKindsTool;-pub use raw_chunks::MemoryStoreRawChunksTool;-pub use raw_search::MemoryStoreRawSearchTool;--#[cfg(test)]-#[path = "mod_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/raw_store/mod_tests.rs b/crates/openhuman-core/src/memory/tools/raw_store/mod_tests.rsdeleted file mode 100644index 1bbc3ca20a..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/mod_tests.rs+++ /dev/null@@ -1,9 +0,0 @@-use super::*;-use tinytools::Tool;--#[test]-fn exports_memory_store_tools_with_stable_names() {- assert_eq!(MemoryStoreKindsTool.name(), "memory_store_kinds");- assert_eq!(MemoryStoreRawChunksTool.name(), "memory_store_raw_chunks");- assert_eq!(MemoryStoreRawSearchTool.name(), "memory_store_raw_search");-}diff --git a/crates/openhuman-core/src/memory/tools/raw_store/raw_chunks.rs b/crates/openhuman-core/src/memory/tools/raw_store/raw_chunks.rsdeleted file mode 100644index 4e4716fc2c..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/raw_chunks.rs+++ /dev/null@@ -1,148 +0,0 @@-//! `memory_store_raw_chunks` — structured chunk filter.-//!-//! Bypasses ranking entirely. Returns chunks (timestamp DESC) matching the-//! supplied source/owner/time/tag filters. Use when the agent knows the-//! exact subset of memory it wants to inspect.--use async_trait::async_trait;-use serde::Deserialize;-use serde_json::json;--use crate::memory::api::chunks::SourceKind;-use crate::memory::api::provider::{ChunkQuery, MemoryProvider};-use crate::memory::ops::guard::active_memory_guard;-use tinytools::{Tool, ToolExposure, ToolResult};--pub struct MemoryStoreRawChunksTool;--#[derive(Debug, Deserialize)]-struct Args {- #[serde(default)]- source_kind: Option<String>,- #[serde(default)]- source_id: Option<String>,- #[serde(default)]- owner: Option<String>,- #[serde(default)]- since_ms: Option<i64>,- #[serde(default)]- until_ms: Option<i64>,- #[serde(default)]- tags_all_of: Option<Vec<String>>,- #[serde(default)]- limit: Option<usize>,-}--#[async_trait]-impl Tool for MemoryStoreRawChunksTool {- /// Superseded by the `memory` tool, which dispatches every memory- /// operation on one `action` field. Kept registered and dispatchable so a- /// replayed transcript or a saved skill naming `memory_*` keeps working;- /// hidden from the wire so eleven schemas do not ship where one does.- fn exposure(&self) -> ToolExposure {- ToolExposure::Hidden- }-- fn name(&self) -> &str {- "memory_store_raw_chunks"- }-- fn description(&self) -> &str {- "List raw memory_store chunks (timestamp DESC) matching structured \- filters: source kind, source id, owner, time range, required tags. \- No scoring or rerank — use for exact-subset inspection, not search. \- Returns full Chunk rows with metadata and content."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "source_kind": { "type": "string", "enum": ["chat", "email", "document"] },- "source_id": { "type": "string", "description": "Exact source id." },- "owner": { "type": "string", "description": "Owner / account filter." },- "since_ms": { "type": "integer", "description": "Inclusive lower bound on timestamp_ms." },- "until_ms": { "type": "integer", "description": "Inclusive upper bound on timestamp_ms." },- "tags_all_of": {- "type": "array",- "items": { "type": "string" },- "description": "Post-filter: chunk.metadata.tags must contain every tag listed."- },- "limit": { "type": "integer", "minimum": 1, "maximum": 1000, "description": "Default 100." }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let parsed: Args = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_store_raw_chunks: {e}"))?;- log::debug!(- "[tool][memory_store] raw_chunks source_kind={:?} owner={:?} tags={:?} limit={:?}",- parsed.source_kind,- parsed.owner,- parsed.tags_all_of,- parsed.limit- );- let source_kind = match parsed.source_kind.as_deref() {- Some(s) => Some(- SourceKind::parse(s)- .map_err(|e| anyhow::anyhow!("memory_store_raw_chunks: {e}"))?,- ),- None => None,- };- if let Some(limit) = parsed.limit {- if !(1..=1000).contains(&limit) {- return Err(anyhow::anyhow!(- "memory_store_raw_chunks: limit must be between 1 and 1000"- ));- }- }- // The per-profile memory-source gate is applied inside `list_chunks`- // (before the row limit). None = unrestricted.- let query = ChunkQuery {- source_kind,- source_id: parsed.source_id,- owner: parsed.owner,- since_ms: parsed.since_ms,- until_ms: parsed.until_ms,- limit: parsed.limit,- offset: None,- exclude_dropped: false,- // The filtered-listing predicates this caller does not use. An- // empty predicate is unfiltered, so the defaults leave the query- // exactly as narrow as the fields above already make it.- ..Default::default()- };- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_store_raw_chunks: {e}"))?;- let mut rows = guard- .as_chunks()- .ok_or_else(|| {- anyhow::anyhow!(- "memory_store_raw_chunks: memory driver does not support the chunk family"- )- })?- .list_chunks(&query, None)- .await?;- if let Some(required) = parsed.tags_all_of.as_ref() {- if !required.is_empty() {- rows.retain(|c| {- required- .iter()- .all(|t| c.metadata.tags.iter().any(|ct| ct == t))- });- }- }- log::debug!(- "[tool][memory_store] raw_chunks returning rows={}",- rows.len()- );- let json = serde_json::to_string(&rows)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "raw_chunks_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/raw_store/raw_chunks_tests.rs b/crates/openhuman-core/src/memory/tools/raw_store/raw_chunks_tests.rsdeleted file mode 100644index 1c2fdae546..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/raw_chunks_tests.rs+++ /dev/null@@ -1,135 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use serde_json::json;-use tinytools::Tool;--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- unsafe {- std::env::set_var("OPENHUMAN_WORKSPACE", path);- }- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- unsafe {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn args_deserialize_optional_filters() {- let args: Args = serde_json::from_value(json!({- "source_kind": "chat",- "source_id": "slack:#eng",- "owner": "alice",- "since_ms": 10,- "until_ms": 20,- "tags_all_of": ["person:alice"],- "limit": 25- }))- .unwrap();-- assert_eq!(args.source_kind.as_deref(), Some("chat"));- assert_eq!(args.source_id.as_deref(), Some("slack:#eng"));- assert_eq!(args.owner.as_deref(), Some("alice"));- assert_eq!(args.since_ms, Some(10));- assert_eq!(args.until_ms, Some(20));- assert_eq!(args.tags_all_of, Some(vec!["person:alice".to_string()]));- assert_eq!(args.limit, Some(25));-}--#[test]-fn parameters_schema_exposes_supported_source_kinds() {- let tool = MemoryStoreRawChunksTool;- let schema = tool.parameters_schema();- assert_eq!(schema["type"], "object");- assert_eq!(- schema["properties"]["source_kind"]["enum"],- json!(["chat", "email", "document"])- );- assert_eq!(schema["properties"]["limit"]["maximum"], 1000);-}--#[tokio::test]-async fn execute_rejects_invalid_source_kind() {- let tool = MemoryStoreRawChunksTool;- let err = tool- .execute(json!({- "source_kind": "not-real"- }))- .await- .expect_err("invalid source kind should fail");- assert!(err.to_string().contains("memory_store_raw_chunks:"));-}--#[tokio::test]-async fn execute_rejects_wrong_type_for_limit() {- let tool = MemoryStoreRawChunksTool;- let err = tool- .execute(json!({- "limit": "ten"- }))- .await- .expect_err("wrong limit type should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_store_raw_chunks"));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the module bus belongs to the runtime that creates it, so run this test alone"]-// Was a pure-SQLite test: it opened the workspace store in-process and read-// an empty table. That is the split brain this port removes — the tool now-// reads chunks through the bound driver, so the success path needs a driver-// that advertises the chunk family. With no module artifact the binding-// falls back to the null driver and the tool refuses, which is the correct-// answer rather than a regression.-async fn execute_success_path_returns_json_array() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _config) = isolated_config(&tmp).await;- let tool = MemoryStoreRawChunksTool;- let result = tool- .execute(json!({- "source_kind": "document",- "limit": 2- }))- .await- .expect("valid raw_chunks request should succeed");- assert!(!result.is_error);- let parsed: serde_json::Value =- serde_json::from_str(&result.text()).expect("tool result should be json");- assert!(- parsed.is_array(),- "raw_chunks should serialize a JSON array"- );-}diff --git a/crates/openhuman-core/src/memory/tools/raw_store/raw_search.rs b/crates/openhuman-core/src/memory/tools/raw_store/raw_search.rsdeleted file mode 100644index 5d4751e1a0..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/raw_search.rs+++ /dev/null@@ -1,121 +0,0 @@-//! `memory_store_raw_search` — free-text search over the entity index.-//!-//! Thin wrapper around `memory_tree::retrieval::search_entities`. Returns canonical-//! entity ids ranked by mention count. This is the rawest of the raw search-//! paths: no narrative, no scoring beyond aggregate occurrence, no rerank.-//! Use it when an agent needs to discover what entities exist in the store-//! before drilling into trees.--use async_trait::async_trait;-use serde::Deserialize;-use serde_json::json;--use crate::memory::api::provider::MemoryProvider;-use crate::memory::ops::guard::active_memory_guard;-use tinytools::{Tool, ToolExposure, ToolResult};--pub struct MemoryStoreRawSearchTool;--#[derive(Debug, Deserialize)]-struct Args {- query: String,- #[serde(default)]- kinds: Option<Vec<String>>,- #[serde(default = "default_limit")]- limit: usize,-}--fn default_limit() -> usize {- 5-}--#[async_trait]-impl Tool for MemoryStoreRawSearchTool {- /// Superseded by the `memory` tool, which dispatches every memory- /// operation on one `action` field. Kept registered and dispatchable so a- /// replayed transcript or a saved skill naming `memory_*` keeps working;- /// hidden from the wire so eleven schemas do not ship where one does.- fn exposure(&self) -> ToolExposure {- ToolExposure::Hidden- }-- fn name(&self) -> &str {- "memory_store_raw_search"- }-- fn description(&self) -> &str {- "Free-text LIKE search over the canonical entity index. Returns \- entity ids ranked by total mention count across every tree. Use to \- discover what entities (people, channels, threads) exist in the \- memory store before drilling into a tree with the memory_tree_* \- tools. Pass `kinds` to narrow the result set (e.g. only people)."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["query"],- "properties": {- "query": {- "type": "string",- "description": "Substring matched against canonical entity id and surface form (case-insensitive)."- },- "kinds": {- "type": "array",- "items": { "type": "string" },- "description": "Optional entity kind filter (e.g. [\"person\", \"channel\"]). Empty/absent = all kinds."- },- "limit": {- "type": "integer",- "minimum": 1,- "maximum": 100,- "description": "Max matches to return (default 5, clamped 100)."- }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let parsed: Args = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_store_raw_search: {e}"))?;- log::debug!(- "[tool][memory_store] raw_search q_len={} kinds={:?} limit={}",- parsed.query.len(),- parsed.kinds,- parsed.limit- );- // An empty `kinds` list means "no filter", matching the previous- // behaviour — it is not forwarded as an empty allowlist, which the- // driver would read as "match no kind at all".- let kinds = parsed- .kinds- .as_ref()- .filter(|kinds| !kinds.is_empty())- .map(Vec::as_slice);- // Kind validation belongs to the driver now: the vocabulary is open on- // the wire. See the note in `memory/query/search_entities.rs`.- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_store_raw_search: {e}"))?;- let hits = guard- .as_retrieval()- .ok_or_else(|| {- anyhow::anyhow!(- "memory_store_raw_search: memory driver does not support the retrieval family"- )- })?- .search_entities(&parsed.query, kinds, parsed.limit)- .await- .map_err(|e| anyhow::anyhow!("memory_store_raw_search: {e}"))?;- log::debug!(- "[tool][memory_store] raw_search returning hits={}",- hits.len()- );- let json = serde_json::to_string(&hits)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "raw_search_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/raw_store/raw_search_tests.rs b/crates/openhuman-core/src/memory/tools/raw_store/raw_search_tests.rsdeleted file mode 100644index 41de5b4a76..0000000000--- a/crates/openhuman-core/src/memory/tools/raw_store/raw_search_tests.rs+++ /dev/null@@ -1,116 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use serde_json::json;-use tinytools::Tool;--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- unsafe {- std::env::set_var("OPENHUMAN_WORKSPACE", path);- }- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- unsafe {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn default_limit_is_five() {- assert_eq!(default_limit(), 5);-}--#[test]-fn args_deserialize_with_default_limit() {- let args: Args = serde_json::from_value(json!({ "query": "alice" })).unwrap();- assert_eq!(args.query, "alice");- assert_eq!(args.limit, 5);- assert!(args.kinds.is_none());-}--#[test]-fn parameters_schema_describes_required_query() {- let tool = MemoryStoreRawSearchTool;- let schema = tool.parameters_schema();- assert_eq!(schema["type"], "object");- assert_eq!(schema["required"], json!(["query"]));- assert_eq!(schema["properties"]["limit"]["maximum"], 100);-}--#[tokio::test]-async fn execute_rejects_missing_query() {- let tool = MemoryStoreRawSearchTool;- let err = tool- .execute(json!({}))- .await- .expect_err("missing query should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_store_raw_search"));-}--#[tokio::test]-async fn execute_rejects_invalid_kind() {- let tool = MemoryStoreRawSearchTool;- let err = tool- .execute(json!({- "query": "alice",- "kinds": ["not-a-kind"]- }))- .await- .expect_err("invalid kind should fail");- assert!(err.to_string().contains("memory_store_raw_search:"));-}--#[tokio::test]-#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \-the tool now reads the entity index through the bound driver, not the in-process engine"]-async fn execute_success_path_returns_json_array() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _config) = isolated_config(&tmp).await;- let tool = MemoryStoreRawSearchTool;- let result = tool- .execute(json!({- "query": "alice",- "limit": 3- }))- .await- .expect("valid raw_search request should succeed");- assert!(!result.is_error);- let parsed: serde_json::Value =- serde_json::from_str(&result.text()).expect("tool result should be json");- assert!(- parsed.is_array(),- "raw_search should serialize a JSON array"- );-}diff --git a/crates/openhuman-core/src/memory/tools/search/chunk_context.rs b/crates/openhuman-core/src/memory/tools/search/chunk_context.rsdeleted file mode 100644index 75826ea464..0000000000--- a/crates/openhuman-core/src/memory/tools/search/chunk_context.rs+++ /dev/null@@ -1,177 +0,0 @@-//! `memory_chunk_context` — expand a chunk with its neighbors from the same source.-//!-//! Given a chunk_id (from memory_vector_search, memory_store_raw_chunks, etc.),-//! returns the chunk's content plus surrounding chunks from the same source,-//! ordered by timestamp. Lets the agent see the full conversation/document flow.--use async_trait::async_trait;-use serde::Deserialize;-use serde_json::json;-use std::fmt::Write;--use crate::memory::api::provider::{ChunkQuery, MemoryProvider};-use crate::memory::ops::guard::active_memory_guard;-use tinytools::{Tool, ToolExposure, ToolResult};--pub struct MemoryChunkContextTool;--#[derive(Debug, Deserialize)]-struct Args {- chunk_id: String,- #[serde(default = "default_window")]- window: usize,-}--fn default_window() -> usize {- 2-}--#[async_trait]-impl Tool for MemoryChunkContextTool {- /// Superseded by the `memory` tool, which dispatches every memory- /// operation on one `action` field. Kept registered and dispatchable so a- /// replayed transcript or a saved skill naming `memory_*` keeps working;- /// hidden from the wire so eleven schemas do not ship where one does.- fn exposure(&self) -> ToolExposure {- ToolExposure::Hidden- }-- fn name(&self) -> &str {- "memory_chunk_context"- }-- fn description(&self) -> &str {- "Expand a chunk with its neighbors from the same source. Given a \- chunk_id from a prior search, returns the surrounding chunks in \- timestamp order — showing the full conversation/document context \- around a match."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["chunk_id"],- "properties": {- "chunk_id": {- "type": "string",- "description": "ID of the chunk to retrieve context for (from a prior search result)."- },- "window": {- "type": "integer",- "minimum": 1,- "maximum": 5,- "description": "Number of neighboring chunks to include before and after (default 2)."- }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let parsed: Args = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_chunk_context: {e}"))?;-- if parsed.chunk_id.trim().is_empty() {- return Err(anyhow::anyhow!(- "memory_chunk_context: chunk_id cannot be empty"- ));- }-- let window = parsed.window.clamp(1, 5);-- log::debug!(- "[tool][memory_chunk_context] chunk_id={} window={}",- parsed.chunk_id,- window,- );-- // Chunks are read through the bound driver rather than by opening the- // store in this process — see the note in `vector_search.rs`.- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_chunk_context: {e}"))?;- let chunk_reader = guard.as_chunks().ok_or_else(|| {- anyhow::anyhow!("memory_chunk_context: memory driver does not support the chunk family")- })?;-- // Look up the target chunk directly by ID- let target = chunk_reader- .get_chunk(&parsed.chunk_id)- .await- .map_err(|e| anyhow::anyhow!("memory_chunk_context: get_chunk failed: {e}"))?- .ok_or_else(|| anyhow::anyhow!("memory_chunk_context: chunk_id not found"))?;-- let source_id = target.metadata.source_id.clone();- let source_kind = target.metadata.source_kind;-- // Source-scope gate: if the target chunk belongs to a source that the- // active turn did not allow, surface nothing (its window shares the- // same source). Non-source chunks always pass.- if !crate::memory::source_scope::chunk_source_allowed(&target.metadata.tags, &source_id) {- return Ok(ToolResult::success(- "Chunk is from a memory source not available to this turn.",- ));- }-- // Get all chunks from the same source, ordered by timestamp. The- // source-scope gate also applies here (the target was already checked- // above; this keeps the window consistent). None = unrestricted.- let source_query = ChunkQuery {- source_kind: Some(source_kind),- source_id: Some(source_id.clone()),- limit: Some(500),- ..Default::default()- };- let mut source_chunks = chunk_reader- .list_chunks(&source_query, None)- .await- .map_err(|e| anyhow::anyhow!("memory_chunk_context: source query failed: {e}"))?;-- // Sort by seq_in_source (ascending) for natural reading order- source_chunks.sort_by_key(|c| c.seq_in_source);-- // Find the target's position- let target_pos = source_chunks- .iter()- .position(|c| c.id == parsed.chunk_id)- .ok_or_else(|| anyhow::anyhow!(- "memory_chunk_context: target chunk not found in source (source may have >500 chunks)"- ))?;-- // Compute window bounds- let start = target_pos.saturating_sub(window);- let end = (target_pos + window + 1).min(source_chunks.len());- let window_chunks = &source_chunks[start..end];-- let mut output = format!(- "Source: {}:{} ({} total chunks)\n\- Showing chunks {}-{} (target at position {}):\n\n",- source_kind.as_str(),- source_id,- source_chunks.len(),- start,- end - 1,- target_pos,- );-- for (i, chunk) in window_chunks.iter().enumerate() {- let abs_pos = start + i;- let marker = if abs_pos == target_pos { " <<<" } else { "" };- let _ = writeln!(- output,- "--- [seq={} | {}]{} ---\n{}",- chunk.seq_in_source,- chunk.metadata.timestamp.format("%Y-%m-%d %H:%M"),- marker,- chunk.content.trim(),- );- }-- log::debug!(- "[tool][memory_chunk_context] returning {} chunks from source {}",- window_chunks.len(),- source_id,- );-- Ok(ToolResult::success(output))- }-}diff --git a/crates/openhuman-core/src/memory/tools/search/hybrid_search.rs b/crates/openhuman-core/src/memory/tools/search/hybrid_search.rsdeleted file mode 100644index 4c5667ef10..0000000000--- a/crates/openhuman-core/src/memory/tools/search/hybrid_search.rs+++ /dev/null@@ -1,356 +0,0 @@-//! `memory_hybrid_search` — configurable multi-signal hybrid search.-//!-//! Exposes the existing hybrid retrieval engine (graph + vector + keyword +-//! freshness) with tunable weight profiles. The agent chooses a mode that-//! emphasizes the signal most relevant to its current need.--use async_trait::async_trait;-use serde::Deserialize;-use serde_json::json;-use std::fmt::Write;--use crate::memory::api::provider::MemoryProvider;-use crate::memory::api::types::MemoryItemKind;-use crate::memory::ops::guard::active_memory_guard;-use tinytools::{Tool, ToolCallOptions, ToolExposure, ToolResult, ToolRunContext};--pub struct MemoryHybridSearchTool;--// ── Weight profiles and the re-ranking sum, brought home (#5560) ─────────────-//-// `WeightProfile` was `tinycortex::memory::WeightProfile` and the fold below-// was `tinycortex::memory::retrieval::scoring::hybrid_score`. Both are ported-// here rather than routed at the module contract, for the same reason the-// vector tool's cosine is: they are pure arithmetic over four numbers the-// driver has *already sent*. `MemoryRetrieval::recall_namespace_scored`-// answers with each hit's `score_breakdown`, so the four raw signals are in-// hand; re-weighting them is this tool's ranking policy and needs no bus at-// all.-//-// This is the same split the engine already drew. Its own `scoring` module docs-// say the profiles "live in `memory::config` and are read from config — never-// hardcoded here", i.e. the weights were always the *caller's* input to a-// function that only multiplied and added. The `mode` argument on this tool is-// where that input comes from, so the table belongs beside it.--/// Named hybrid-retrieval weight profiles (graph / vector / keyword /-/// freshness), resolved from this tool's `mode` argument.-///-/// The final ranking score is the plain weighted sum `graph·graph_relevance +-/// vector·vector_similarity + keyword·keyword_relevance + freshness·freshness`.-/// Nothing here *enforces* that the four weights sum to-/// `1.0` — the four built-ins are chosen that way by convention so scores land-/// in a familiar `[0.0, 1.0]`-ish range when every signal is itself in-/// `[0.0, 1.0]`. The constants are the engine's, value for value, so a query-/// ranks exactly as it did before.-#[derive(Debug, Clone, Copy, PartialEq)]-struct WeightProfile {- /// Weight on graph/co-occurrence proximity signal.- graph: f64,- /// Weight on dense vector (cosine) similarity signal.- vector: f64,- /// Weight on lexical/keyword match signal.- keyword: f64,- /// Weight on recency; `0.0` disables freshness boosting.- freshness: f64,-}--impl WeightProfile {- /// `balanced`: graph 0.35, vector 0.35, keyword 0.15, freshness 0.15.- const BALANCED: Self = Self {- graph: 0.35,- vector: 0.35,- keyword: 0.15,- freshness: 0.15,- };- /// `semantic`: graph 0.15, vector 0.65, keyword 0.20.- const SEMANTIC: Self = Self {- graph: 0.15,- vector: 0.65,- keyword: 0.20,- freshness: 0.0,- };- /// `lexical`: graph 0.25, vector 0.15, keyword 0.60.- const LEXICAL: Self = Self {- graph: 0.25,- vector: 0.15,- keyword: 0.60,- freshness: 0.0,- };- /// `graph_first`: graph 0.55, vector 0.30, keyword 0.15.- const GRAPH_FIRST: Self = Self {- graph: 0.55,- vector: 0.30,- keyword: 0.15,- freshness: 0.0,- };-- /// Resolve a profile by its wire name, returning `None` for unknown names.- ///- /// The names are the `mode` enum in [`MemoryHybridSearchTool`]'s parameter- /// schema and are therefore a published surface — a rename here is a- /// breaking change to what the model may ask for, not a refactor.- fn by_name(name: &str) -> Option<Self> {- match name {- "balanced" => Some(Self::BALANCED),- "semantic" => Some(Self::SEMANTIC),- "lexical" => Some(Self::LEXICAL),- "graph_first" => Some(Self::GRAPH_FIRST),- _ => None,- }- }-}--/// Fold four raw signals into one ranking score under `profile`.-///-/// Each signal is expected in `[0.0, 1.0]`; the result is the weighted sum-/// `graph·g + vector·v + keyword·k + freshness·f`.-///-/// The engine's `hybrid_score` returned a whole `RetrievalScoreBreakdown` and-/// this call site read `.final_score` off it and dropped the rest — the other-/// five fields were the caller's own inputs echoed back, plus a hardcoded-/// `episodic_relevance: 0.0` carried for wire compatibility with a payload-/// nothing here serialises. So this returns the number instead of rebuilding a-/// breakdown to immediately discard; the arithmetic is unchanged.-fn hybrid_final_score(- profile: &WeightProfile,- graph_relevance: f64,- vector_similarity: f64,- keyword_relevance: f64,- freshness: f64,-) -> f64 {- profile.graph * graph_relevance- + profile.vector * vector_similarity- + profile.keyword * keyword_relevance- + profile.freshness * freshness-}--#[derive(Debug, Deserialize)]-struct Args {- query: String,- namespace: String,- #[serde(default = "default_mode")]- mode: String,- #[serde(default = "default_limit")]- limit: u32,- #[serde(default)]- include_breakdown: bool,-}--fn default_mode() -> String {- "balanced".to_string()-}--fn default_limit() -> u32 {- 10-}--fn kind_label(kind: &MemoryItemKind) -> &'static str {- match kind {- MemoryItemKind::Document => "doc",- MemoryItemKind::Kv => "kv",- MemoryItemKind::Episodic => "episodic",- MemoryItemKind::Event => "event",- }-}--#[async_trait]-impl Tool for MemoryHybridSearchTool {- fn name(&self) -> &str {- "memory_hybrid_search"- }-- fn description(&self) -> &str {- "Multi-signal hybrid search with configurable weight profiles. \- Combines graph relevance, vector similarity, keyword matching, \- and freshness into a unified score. Choose a mode to emphasize \- the signal most relevant to your query: 'balanced' (equal graph+vector), \- 'semantic' (vector-heavy), 'lexical' (keyword-heavy), \- 'graph_first' (relationship-heavy)."- }-- fn exposure(&self) -> ToolExposure {- ToolExposure::Hidden- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["query", "namespace"],- "properties": {- "query": {- "type": "string",- "description": "Natural-language search query."- },- "namespace": {- "type": "string",- "description": "Namespace to search (e.g. 'global', 'background')."- },- "mode": {- "type": "string",- "enum": ["balanced", "semantic", "lexical", "graph_first"],- "description": "Weight profile: 'balanced' (default), 'semantic' (vector-heavy), 'lexical' (keyword-heavy), 'graph_first' (relationship-heavy)."- },- "limit": {- "type": "integer",- "minimum": 1,- "maximum": 50,- "description": "Max results (default 10)."- },- "include_breakdown": {- "type": "boolean",- "description": "Show per-signal score breakdown for each result (default false)."- }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_with_context(args, ToolCallOptions::default(), None)- .await- }-- async fn execute_with_context(- &self,- args: serde_json::Value,- _options: ToolCallOptions,- tool_context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let parsed: Args = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_hybrid_search: {e}"))?;-- if parsed.query.trim().is_empty() {- return Err(anyhow::anyhow!(- "memory_hybrid_search: query cannot be empty"- ));- }- if parsed.namespace.trim().is_empty() {- return Err(anyhow::anyhow!(- "memory_hybrid_search: namespace cannot be empty"- ));- }-- let profile = WeightProfile::by_name(&parsed.mode).ok_or_else(|| {- log::warn!(- "[tool][memory_hybrid_search] rejected unknown mode={}",- parsed.mode- );- anyhow::anyhow!(- "memory_hybrid_search: unknown mode '{}'; expected balanced, semantic, lexical, or graph_first",- parsed.mode- )- })?;- let limit = parsed.limit.clamp(1, 50);-- log::debug!(- "[tool][memory_hybrid_search] query_len={} ns={} mode={} limit={}",- parsed.query.len(),- parsed.namespace,- parsed.mode,- limit,- );-- // Reads through the bound driver. This used to call- // `UnifiedMemory::new(&config.workspace_dir, …)` — constructing a- // *whole second engine* over the workspace the loaded module already- // owns, the most severe instance of the split brain this port removes.- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_hybrid_search: {e}"))?;- let retrieval = guard.as_retrieval().ok_or_else(|| {- anyhow::anyhow!(- "memory_hybrid_search: memory driver does not support the retrieval family"- )- })?;-- // Self-echo guard (agent-agnostic, mirrors `UnifiedMemory::recall`):- // exclude documents auto-saved for the caller chat thread so a search issued mid-turn- // never retrieves the very request that triggered it. `None`- // outside a chat turn — unchanged behavior for cron/CLI/tests.- let exclude_session_id = tool_context.and_then(ToolRunContext::thread_id);- if let Some(ref excluded) = exclude_session_id {- log::debug!(- "[tool][memory_hybrid_search] applying same-session exclusion exclude_session_id={excluded}"- );- }- let hits = retrieval- .recall_namespace_scored(- &parsed.namespace,- &parsed.query,- limit as usize,- exclude_session_id,- )- .await- .map_err(|e| anyhow::anyhow!("memory_hybrid_search: query failed: {e}"))?;-- if hits.is_empty() {- return Ok(ToolResult::success("No results found."));- }-- // Re-score using the selected weight profile- let mut rescored: Vec<(usize, f64)> = hits- .iter()- .enumerate()- .map(|(i, hit)| {- let bd = &hit.score_breakdown;- let score = hybrid_final_score(- &profile,- bd.graph_relevance,- bd.vector_similarity,- bd.keyword_relevance,- bd.freshness,- );- (i, score)- })- .filter(|(_, score)| *score > 0.0)- .collect();-- rescored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));- rescored.truncate(limit as usize);-- let mut output = format!(- "Found {} results (mode={}):\n\n",- rescored.len(),- parsed.mode,- );-- for (hit_idx, score) in &rescored {- let hit = &hits[*hit_idx];- let preview: String = hit.content.chars().take(200).collect();- let truncated = if hit.content.chars().count() > 200 {- "..."- } else {- ""- };- let _ = writeln!(- output,- "- [{:.0}%] [{}] {}: {}{}",- score * 100.0,- kind_label(&hit.kind),- hit.key,- preview,- truncated,- );-- if parsed.include_breakdown {- let bd = &hit.score_breakdown;- let _ = writeln!(- output,- " scores: graph={:.2} vector={:.2} keyword={:.2} freshness={:.2}",- bd.graph_relevance, bd.vector_similarity, bd.keyword_relevance, bd.freshness,- );- }- }-- log::debug!(- "[tool][memory_hybrid_search] returning {} results",- rescored.len(),- );-- Ok(ToolResult::success(output))- }-}--#[cfg(test)]-#[path = "hybrid_search_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/search/hybrid_search_tests.rs b/crates/openhuman-core/src/memory/tools/search/hybrid_search_tests.rsdeleted file mode 100644index ccc3783730..0000000000--- a/crates/openhuman-core/src/memory/tools/search/hybrid_search_tests.rs+++ /dev/null@@ -1,19 +0,0 @@-use super::*;--#[tokio::test]-async fn rejects_unknown_mode_before_opening_external_search_resources() {- let error = MemoryHybridSearchTool- .execute(json!({- "query": "release checklist",- "namespace": "global",- "mode": "mystery"- }))- .await- .expect_err("an unknown mode must fail validation");-- let message = error.to_string();- assert!(message.contains("unknown mode 'mystery'"), "{message}");- // Validation runs before config, provider, and store setup. Reaching any- // external search path would replace this precise validation error.- assert!(!message.contains("load config failed"), "{message}");-}diff --git a/crates/openhuman-core/src/memory/tools/search/vector_search.rs b/crates/openhuman-core/src/memory/tools/search/vector_search.rsdeleted file mode 100644index d162dc5a6a..0000000000--- a/crates/openhuman-core/src/memory/tools/search/vector_search.rs+++ /dev/null@@ -1,282 +0,0 @@-//! `memory_vector_search` — direct semantic search over chunk embeddings.-//!-//! Pure cosine similarity over stored chunk embeddings. No graph scoring,-//! no LLM loop. Fast, single embedding call. Supports metadata filtering,-//! cross-namespace search, similarity threshold, and MMR diversity.--use async_trait::async_trait;-use serde::Deserialize;-use serde_json::json;-use std::fmt::Write;--use crate::config::rpc as config_rpc;-use crate::inference::embedding_host::provider_from_config;-use crate::memory::api::chunks::SourceKind;-use crate::memory::api::provider::ChunkQuery;-use crate::memory::api::provider::MemoryProvider;-use crate::memory::ops::guard::active_memory_guard;-use tinyinference_embeddings::{cosine_similarity_f64, mmr_select, MmrCandidate};-use tinytools::{Tool, ToolExposure, ToolResult};--pub struct MemoryVectorSearchTool;--#[derive(Debug, Deserialize)]-struct Args {- query: String,- #[serde(default)]- namespace: Option<String>,- #[serde(default)]- source_kind: Option<String>,- #[serde(default)]- time_window_days: Option<u32>,- #[serde(default)]- min_score: Option<f64>,- #[serde(default = "default_limit")]- limit: usize,- #[serde(default)]- diverse: bool,-}--fn default_limit() -> usize {- 10-}--#[async_trait]-impl Tool for MemoryVectorSearchTool {- fn name(&self) -> &str {- "memory_vector_search"- }-- fn description(&self) -> &str {- "Direct semantic vector search over memory chunks. Embeds the query \- and finds the most similar stored content by cosine similarity. \- Fast (single embedding call, no LLM). Use for semantic lookup when \- you know roughly what you're looking for. Returns chunk-level results \- with scores."- }-- fn exposure(&self) -> ToolExposure {- ToolExposure::Hidden- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["query"],- "properties": {- "query": {- "type": "string",- "description": "Natural-language query to embed and search against stored memory chunks."- },- "source_kind": {- "type": "string",- "enum": ["chat", "email", "document"],- "description": "Filter to a specific source type."- },- "time_window_days": {- "type": "integer",- "minimum": 1,- "description": "Only include chunks from the last N days."- },- "min_score": {- "type": "number",- "minimum": 0.0,- "maximum": 1.0,- "description": "Minimum cosine similarity threshold (default 0.3)."- },- "limit": {- "type": "integer",- "minimum": 1,- "maximum": 50,- "description": "Max results to return (default 10)."- },- "diverse": {- "type": "boolean",- "description": "Apply MMR diversity to reduce redundancy among results (default false)."- }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let parsed: Args = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_vector_search: {e}"))?;-- if parsed.query.trim().is_empty() {- return Err(anyhow::anyhow!(- "memory_vector_search: query cannot be empty"- ));- }-- let limit = parsed.limit.clamp(1, 50);- let min_score = parsed.min_score.unwrap_or(0.3);-- log::debug!(- "[tool][memory_vector_search] query_len={} source_kind={:?} window={:?} min_score={} limit={} diverse={}",- parsed.query.len(),- parsed.source_kind,- parsed.time_window_days,- min_score,- limit,- parsed.diverse,- );-- let config = config_rpc::load_config_with_timeout()- .await- .map_err(|e| anyhow::anyhow!("memory_vector_search: load config failed: {e}"))?;-- // Chunks are read through the bound driver, not by opening the store- // in this process. Before the module port this called- // `list_chunks(&config, …)` directly, which resolved the workspace path- // and opened the same SQLite database the loaded module already had- // open — two engine instances over one file, with the module not- // authoritative. See `docs/specs/2026-08-13-memory-module-port.md` §2.1.- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_vector_search: {e}"))?;- let chunk_reader = guard.as_chunks().ok_or_else(|| {- anyhow::anyhow!("memory_vector_search: memory driver does not support the chunk family")- })?;-- let embedder = provider_from_config(&config)- .map_err(|e| anyhow::anyhow!("memory_vector_search: embedding provider failed: {e}"))?;-- let query_vec = embedder- .embed_one(&parsed.query)- .await- .map_err(|e| anyhow::anyhow!("memory_vector_search: embedding query failed: {e}"))?;-- let source_kind = match parsed.source_kind.as_deref() {- Some(s) => Some(- SourceKind::parse(s).map_err(|e| anyhow::anyhow!("memory_vector_search: {e}"))?,- ),- None => None,- };-- let since_ms = parsed.time_window_days.map(|days| {- let now_ms = chrono::Utc::now().timestamp_millis();- now_ms - (i64::from(days) * 86_400_000)- });-- // Fetch candidate chunks with metadata filters. The per-profile- // memory-source gate is applied inside the driver's query (before the- // row limit), so disallowed-source chunks can't starve permitted ones.- //- // `None` for the scope is not "unrestricted": the guard intersects it- // with the ambient per-turn allowlist and passes the result down, so- // naming a scope here could only ever *narrow* what the turn may see.- let query = ChunkQuery {- source_kind,- source_id: None,- owner: None,- since_ms,- until_ms: None,- limit: Some(1000),- offset: None,- exclude_dropped: false,- // The filtered-listing predicates this caller does not use. An- // empty predicate is unfiltered, so the defaults leave the query- // exactly as narrow as the fields above already make it.- ..Default::default()- };-- let chunks = chunk_reader- .list_chunks(&query, None)- .await- .map_err(|e| anyhow::anyhow!("memory_vector_search: list chunks failed: {e}"))?;-- if chunks.is_empty() {- return Ok(ToolResult::success("No chunks found matching filters."));- }-- // Get embeddings for these chunks- let chunk_ids: Vec<String> = chunks.iter().map(|c| c.id.clone()).collect();- let model_sig = embedder.signature();- let embeddings: std::collections::HashMap<String, Vec<f32>> = chunk_reader- .chunk_embeddings(&chunk_ids, &model_sig)- .await- .map_err(|e| anyhow::anyhow!("memory_vector_search: load embeddings failed: {e}"))?- .into_iter()- .map(|embedding| (embedding.chunk_id, embedding.vector))- .collect();-- // Score each chunk- let mut scored: Vec<(usize, f64, &[f32])> = Vec::new();-- for (idx, chunk) in chunks.iter().enumerate() {- let Some(emb) = embeddings.get(&chunk.id) else {- continue;- };- if emb.len() != query_vec.len() {- continue;- }- let score = cosine_similarity_f64(&query_vec, emb);- if score >= min_score {- scored.push((idx, score, emb.as_slice()));- }- }-- if scored.is_empty() {- return Ok(ToolResult::success(- "No chunks scored above the similarity threshold.",- ));- }-- let results = if parsed.diverse && scored.len() > limit {- let candidates: Vec<MmrCandidate<'_>> = scored- .iter()- .map(|(idx, score, emb)| MmrCandidate {- index: *idx,- embedding: emb,- relevance: *score,- })- .collect();- let mmr_results = mmr_select(&candidates, limit, 0.7);- mmr_results- .into_iter()- .map(|r| {- (- r.index,- scored.iter().find(|(i, _, _)| *i == r.index).unwrap().1,- )- })- .collect::<Vec<_>>()- } else {- scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));- scored.truncate(limit);- scored- .iter()- .map(|(idx, score, _)| (*idx, *score))- .collect()- };-- let mut output = format!("Found {} results:\n\n", results.len());- for (chunk_idx, score) in &results {- let chunk = &chunks[*chunk_idx];- let preview: String = chunk.content.chars().take(300).collect();- let truncated = if chunk.content.chars().count() > 300 {- "..."- } else {- ""- };- let _ = writeln!(- output,- "- [{:.0}%] source={}:{} id={}\n {}{}",- score * 100.0,- chunk.metadata.source_kind.as_str(),- chunk.metadata.source_id,- chunk.id,- preview,- truncated,- );- }-- log::debug!(- "[tool][memory_vector_search] returning {} results from {} candidates",- results.len(),- chunks.len(),- );-- Ok(ToolResult::success(output))- }-}diff --git a/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rs b/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rsindex 7b4fbc69b1..6ec3637156 100644--- a/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rs+++ b/crates/openhuman-core/src/memory/tools/tool_memory/guard_tests.rs@@ -7,6 +7,9 @@use super::*;use std::ffi::OsString;+use crate::memory::api::provider::MemoryProvider;+use crate::memory::api::tool_memory::{ToolMemoryPriority, ToolMemorySource};+use tempfile::TempDir;use crate::config::Config;diff --git a/crates/openhuman-core/src/memory/tools/tool_memory/list.rs b/crates/openhuman-core/src/memory/tools/tool_memory/list.rsdeleted file mode 100644index 59d6d2bdeb..0000000000--- a/crates/openhuman-core/src/memory/tools/tool_memory/list.rs+++ /dev/null@@ -1,79 +0,0 @@-//! `memory_tools_list` — list every stored rule for a given tool.-//!-//! Routed through [`MemoryGuard`](crate::memory::guard::MemoryGuard)-//! rather than a raw `ToolMemoryStore`. `MemoryToolMemory::tool_rules` on the-//! embedded driver is literally `tool_memory_store(self.memory()).list_rules(…)`,-//! and the wire type matches by identity, not conversion:-//! `memory::tool_memory::ToolMemoryRule` **is**-//! `crate::memory::api::tool_memory::ToolMemoryRule`. So the re-point is exact —-//! same rules, same order, same serialization — with `Capability::ToolMemory`-//! admitted first.--use crate::memory::api::provider::MemoryProvider;-use async_trait::async_trait;-use serde::Deserialize;-use serde_json::json;--use crate::memory::ops::guard::active_memory_guard;-use crate::memory::ops::tool_memory::NO_TOOL_MEMORY;-use tinytools::{Tool, ToolResult};--pub struct MemoryToolsListTool;--#[derive(Debug, Deserialize)]-struct Args {- tool_name: String,-}--#[async_trait]-impl Tool for MemoryToolsListTool {- fn name(&self) -> &str {- "memory_tools_list"- }-- fn description(&self) -> &str {- "List every stored memory rule for the given tool. Rules are durable \- learnings about how to use the tool — priorities, gotchas, user \- edicts. Returns the rules ordered by priority (Critical → Low) and \- updated_at DESC within each priority."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["tool_name"],- "properties": {- "tool_name": {- "type": "string",- "description": "Exact tool name (e.g. `bash`, `web_search`)."- }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let parsed: Args = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_tools_list: {e}"))?;- log::debug!("[tool][memory_tools] list tool_name={}", parsed.tool_name);- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_tools_list: {e}"))?;- let rules = guard- .as_tool_memory()- .ok_or_else(|| anyhow::anyhow!("memory_tools_list: {NO_TOOL_MEMORY}"))?- .tool_rules(&parsed.tool_name)- .await- .map_err(|e| anyhow::anyhow!("memory_tools_list: {e}"))?;- log::debug!(- "[tool][memory_tools] list via guard tool_name={} rules={}",- parsed.tool_name,- rules.len()- );- let json = serde_json::to_string(&rules)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "list_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/tool_memory/list_tests.rs b/crates/openhuman-core/src/memory/tools/tool_memory/list_tests.rsdeleted file mode 100644index edbdc39df2..0000000000--- a/crates/openhuman-core/src/memory/tools/tool_memory/list_tests.rs+++ /dev/null@@ -1,100 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use serde_json::json;-use tinytools::Tool;--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- std::env::set_var("OPENHUMAN_WORKSPACE", path);- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn args_require_tool_name() {- let args: Args = serde_json::from_value(json!({ "tool_name": "bash" })).unwrap();- assert_eq!(args.tool_name, "bash");-}--#[test]-fn parameters_schema_requires_tool_name() {- let tool = MemoryToolsListTool;- let schema = tool.parameters_schema();- assert_eq!(schema["type"], "object");- assert_eq!(schema["required"], json!(["tool_name"]));- assert_eq!(schema["properties"]["tool_name"]["type"], "string");-}--#[tokio::test]-async fn execute_rejects_missing_tool_name() {- let tool = MemoryToolsListTool;- let err = tool- .execute(json!({}))- .await- .expect_err("missing tool_name should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tools_list"));-}--#[tokio::test]-async fn execute_success_path_returns_json_array_for_isolated_workspace() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryToolsListTool;- let result = tool- .execute(json!({ "tool_name": "bash" }))- .await- .expect("valid tool list request should succeed in isolated workspace");- assert!(!result.is_error);- let payload = result.text();- let parsed: serde_json::Value =- serde_json::from_str(&payload).expect("result should be valid json");- assert!(- parsed.is_array(),- "list tool rules should serialize a JSON array"- );-}--#[tokio::test]-async fn execute_accepts_other_tool_names_without_rules() {- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryToolsListTool;- let result = tool- .execute(json!({ "tool_name": "web_search" }))- .await- .expect("arbitrary tool names should succeed even when empty");- assert!(!result.is_error);-}diff --git a/crates/openhuman-core/src/memory/tools/tool_memory/mod_tests.rs b/crates/openhuman-core/src/memory/tools/tool_memory/mod_tests.rsdeleted file mode 100644index bb9bb67093..0000000000--- a/crates/openhuman-core/src/memory/tools/tool_memory/mod_tests.rs+++ /dev/null@@ -1,8 +0,0 @@-use super::*;-use tinytools::Tool;--#[test]-fn exports_memory_tool_wrappers_with_stable_names() {- assert_eq!(MemoryToolsListTool.name(), "memory_tools_list");- assert_eq!(MemoryToolsPutTool.name(), "memory_tools_put");-}diff --git a/crates/openhuman-core/src/memory/tools/tool_memory/put.rs b/crates/openhuman-core/src/memory/tools/tool_memory/put.rsdeleted file mode 100644index e6a8098b41..0000000000--- a/crates/openhuman-core/src/memory/tools/tool_memory/put.rs+++ /dev/null@@ -1,146 +0,0 @@-//! `memory_tools_put` — upsert a tool-scoped memory rule.-//!-//! Routed through [`MemoryGuard`](crate::memory::guard::MemoryGuard).-//! `MemoryToolMemory::put_tool_rule` delegates to the same-//! `ToolMemoryStore::put_rule` this tool used to build by hand, with one-//! asymmetry: the contract method returns unit while the store returns the-//! *stored* rule (trim/lower-cased `tool_name`, `created_at` preserved on-//! upsert, `updated_at` refreshed) — which is what this tool answers with. The-//! asymmetry is recovered exactly by reading the rule back:-//! `ToolMemoryRule::new` always generates the id before the write, so there is-//! no server-assigned identity to lose, and `tool_memory_namespace` applies the-//! same `trim().to_lowercase()` the write normalised into, so reading back with-//! the caller's raw `tool_name` hits the same namespace.-//!-//! A concurrent delete between the write and the read-back yields no rule. That-//! answers with an error, never a fabricated rule — absence, not a lie.-//!-//! **Behaviour change, deliberate:** the write now takes-//! `SecurityPolicy::enforce_write_tier`, so the tool is refused under the-//! `readonly` autonomy tier with `"memory guard: "`-prefixed text, and-//! store-level validation errors arrive as `MemoryError::Invalid` rather than as-//! a raw string.--use crate::memory::api::provider::MemoryProvider;-use async_trait::async_trait;-use serde::Deserialize;-use serde_json::json;--use crate::memory::api::tool_memory::{ToolMemoryPriority, ToolMemoryRule, ToolMemorySource};-use crate::memory::ops::guard::active_memory_guard;-use crate::memory::ops::tool_memory::NO_TOOL_MEMORY;-use tinytools::{Tool, ToolResult};--pub struct MemoryToolsPutTool;--#[derive(Debug, Deserialize)]-struct Args {- tool_name: String,- rule: String,- #[serde(default)]- priority: Option<String>,- #[serde(default)]- tags: Vec<String>,-}--fn parse_priority(s: Option<&str>) -> ToolMemoryPriority {- match s.map(|x| x.to_ascii_lowercase()) {- Some(ref v) if v == "critical" => ToolMemoryPriority::Critical,- Some(ref v) if v == "high" => ToolMemoryPriority::High,- _ => ToolMemoryPriority::Normal,- }-}--#[async_trait]-impl Tool for MemoryToolsPutTool {- fn name(&self) -> &str {- "memory_tools_put"- }-- fn description(&self) -> &str {- "Record a durable rule / learning for the given tool. Use when the \- user gives a directive that should survive future sessions, or \- when a tool failure pattern is worth pinning. Returns the stored \- rule with its assigned id and timestamps."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["tool_name", "rule"],- "properties": {- "tool_name": {- "type": "string",- "description": "Exact tool name the rule applies to."- },- "rule": {- "type": "string",- "description": "Free-text rule, edict, or learning to pin."- },- "priority": {- "type": "string",- "enum": ["critical", "high", "normal"],- "description": "How aggressively to surface the rule. Default: normal."- },- "tags": {- "type": "array",- "items": { "type": "string" },- "description": "Optional free-form tags (e.g. `safety`, `permission`)."- }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let parsed: Args = serde_json::from_value(args)- .map_err(|e| anyhow::anyhow!("invalid arguments for memory_tools_put: {e}"))?;- log::debug!(- "[tool][memory_tools] put tool_name={} priority={:?} tags={}",- parsed.tool_name,- parsed.priority,- parsed.tags.len()- );- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("memory_tools_put: {e}"))?;- let family = guard- .as_tool_memory()- .ok_or_else(|| anyhow::anyhow!("memory_tools_put: {NO_TOOL_MEMORY}"))?;- let mut rule = ToolMemoryRule::new(- &parsed.tool_name,- &parsed.rule,- parse_priority(parsed.priority.as_deref()),- ToolMemorySource::UserExplicit,- );- rule.tags = parsed.tags;- let rule_id = rule.id.clone();- let tool_name = rule.tool_name.clone();- family- .put_tool_rule(rule)- .await- .map_err(|e| anyhow::anyhow!("memory_tools_put: {e}"))?;- // `put_tool_rule` answers with unit; the tool's contract is the stored- // rule (normalised tool_name, preserved created_at, refreshed- // updated_at), so read it back by the id generated above.- let stored = family- .tool_rules(&tool_name)- .await- .map_err(|e| anyhow::anyhow!("memory_tools_put: {e}"))?- .into_iter()- .find(|r| r.id == rule_id)- .ok_or_else(|| {- anyhow::anyhow!("memory_tools_put: stored rule {rule_id} not found on read-back")- })?;- log::debug!(- "[tool][memory_tools] put via guard tool_name={} id={} read_back=ok",- stored.tool_name,- stored.id- );- let json = serde_json::to_string(&stored)?;- Ok(ToolResult::success(json))- }-}--#[cfg(test)]-#[path = "put_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/memory/tools/tool_memory/put_tests.rs b/crates/openhuman-core/src/memory/tools/tool_memory/put_tests.rsdeleted file mode 100644index 4ba314ceef..0000000000--- a/crates/openhuman-core/src/memory/tools/tool_memory/put_tests.rs+++ /dev/null@@ -1,275 +0,0 @@-use super::*;-use std::ffi::OsString;--use tempfile::TempDir;--use crate::config::Config;-use crate::config::TEST_ENV_LOCK;-use crate::memory::guard::policy::GUARD_DENIED_PREFIX;-use crate::security::live_policy;-use crate::security::policy::{AutonomyLevel, SecurityPolicy};-use serde_json::json;-use std::sync::Arc;-use tinytools::Tool;--/// Install `autonomy` as the live policy for this test thread only. Same-/// shape `memory/guard/policy_tests.rs` uses; `#[tokio::test]`'s-/// current-thread runtime keeps the future on the installing thread.-fn scoped_tier(autonomy: AutonomyLevel) -> live_policy::TestPolicyGuard {- let dir = std::env::temp_dir();- live_policy::install_scoped(- Arc::new(SecurityPolicy {- autonomy,- ..SecurityPolicy::default()- }),- dir.clone(),- dir,- )-}--struct WorkspaceEnvGuard {- _lock: std::sync::MutexGuard<'static, ()>,- previous: Option<OsString>,-}--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- std::env::set_var("OPENHUMAN_WORKSPACE", path);- Self {- _lock: lock,- previous,- }- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- if let Some(previous) = self.previous.as_ref() {- std::env::set_var("OPENHUMAN_WORKSPACE", previous);- } else {- std::env::remove_var("OPENHUMAN_WORKSPACE");- }- }-}--async fn isolated_config(tmp: &TempDir) -> (WorkspaceEnvGuard, Config) {- let guard = WorkspaceEnvGuard::set(tmp.path());- let config = Config::load_or_init().await.expect("load config");- (guard, config)-}--#[test]-fn parse_priority_defaults_to_normal() {- assert_eq!(parse_priority(None), ToolMemoryPriority::Normal);- assert_eq!(parse_priority(Some("normal")), ToolMemoryPriority::Normal);- assert_eq!(parse_priority(Some("unknown")), ToolMemoryPriority::Normal);-}--#[test]-fn parse_priority_accepts_critical_and_high_case_insensitively() {- assert_eq!(- parse_priority(Some("critical")),- ToolMemoryPriority::Critical- );- assert_eq!(- parse_priority(Some("CRITICAL")),- ToolMemoryPriority::Critical- );- assert_eq!(parse_priority(Some("high")), ToolMemoryPriority::High);- assert_eq!(parse_priority(Some("HiGh")), ToolMemoryPriority::High);-}--#[test]-fn args_default_tags_to_empty() {- let args: Args = serde_json::from_value(json!({- "tool_name": "bash",- "rule": "Never run rm -rf"- }))- .unwrap();- assert_eq!(args.tool_name, "bash");- assert_eq!(args.rule, "Never run rm -rf");- assert!(args.priority.is_none());- assert!(args.tags.is_empty());-}--#[test]-fn parameters_schema_describes_priority_enum() {- let tool = MemoryToolsPutTool;- let schema = tool.parameters_schema();- assert_eq!(schema["required"], json!(["tool_name", "rule"]));- assert_eq!(- schema["properties"]["priority"]["enum"],- json!(["critical", "high", "normal"])- );-}--#[tokio::test]-async fn execute_rejects_missing_required_fields() {- let tool = MemoryToolsPutTool;- let err = tool- .execute(json!({ "tool_name": "bash" }))- .await- .expect_err("missing rule should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tools_put"));-- let err = tool- .execute(json!({ "rule": "Never run rm -rf" }))- .await- .expect_err("missing tool_name should fail");- assert!(err- .to_string()- .contains("invalid arguments for memory_tools_put"));-}--#[tokio::test]-async fn execute_success_path_persists_rule_in_isolated_workspace() {- let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryToolsPutTool;- let result = tool- .execute(json!({- "tool_name": "bash",- "rule": "Always dry-run dangerous commands first",- "priority": "high",- "tags": ["safety", "shell"]- }))- .await- .expect("valid memory_tools_put request should succeed in isolated workspace");- assert!(!result.is_error);-- let parsed: serde_json::Value =- serde_json::from_str(&result.text()).expect("tool result should be json");- assert_eq!(parsed["tool_name"], "bash");- assert_eq!(parsed["rule"], "Always dry-run dangerous commands first");- assert_eq!(parsed["priority"], "high");- assert_eq!(parsed["source"], "user_explicit");- assert_eq!(parsed["tags"], json!(["safety", "shell"]));- assert!(parsed["id"].as_str().is_some());-- let guard = crate::memory::ops::guard::active_memory_guard()- .await- .expect("active memory guard");- let rules = guard- .as_tool_memory()- .expect("embedded driver advertises the tool_memory family")- .tool_rules("bash")- .await- .expect("list stored rules");- let stored = rules- .iter()- .find(|rule| rule.rule == "Always dry-run dangerous commands first")- .expect("stored bash rule should be present");- assert_eq!(stored.priority, ToolMemoryPriority::High);- assert_eq!(stored.source, ToolMemorySource::UserExplicit);- assert_eq!(stored.tags, vec!["safety".to_string(), "shell".to_string()]);-}--#[tokio::test]-async fn execute_defaults_unknown_priority_to_normal() {- let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let tool = MemoryToolsPutTool;- let result = tool- .execute(json!({- "tool_name": "bash",- "rule": "Prefer printf over echo for escapes",- "priority": "unexpected"- }))- .await- .expect("unknown priority should still succeed");- assert!(!result.is_error);-- let parsed: serde_json::Value =- serde_json::from_str(&result.text()).expect("tool result should be json");- assert_eq!(parsed["priority"], "normal");-}--/// The behavioural discriminator for the re-point: before it, the tool-/// wrote through an undecorated `MemoryClientRef` and no tier check ran, so-/// a `readonly` agent could still pin rules. Through the guard,-/// `admit_write` calls `enforce_write_tier` first.-#[tokio::test]-async fn execute_is_refused_under_the_readonly_tier() {- let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let _tier = scoped_tier(AutonomyLevel::ReadOnly);- let tool = MemoryToolsPutTool;- let err = tool- .execute(json!({- "tool_name": "bash",- "rule": "readonly agents must not pin rules"- }))- .await- .expect_err("the readonly tier must refuse a tool-memory write");- let message = err.to_string();- assert!(- message.contains(GUARD_DENIED_PREFIX),- "refusal must be attributable to the guard: {message}"- );-}--/// The paired positive case: the same call under `full` succeeds, so the-/// test above is proving the tier gate rather than a broken write path.-#[tokio::test]-async fn execute_succeeds_under_the_full_tier() {- let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let _tier = scoped_tier(AutonomyLevel::Full);- let tool = MemoryToolsPutTool;- let result = tool- .execute(json!({- "tool_name": "bash",- "rule": "full-tier agents may pin rules"- }))- .await- .expect("the full tier must admit a tool-memory write");- assert!(!result.is_error);-}--/// `memory_tools_put` and `memory_tools_list` must observe each other now-/// that both resolve through the guard rather than through their own-/// `ToolMemoryStore` handles.-#[tokio::test]-async fn guarded_put_and_guarded_list_share_the_store() {- let _serial = crate::memory::ops::GLOBAL_MEMORY_TEST_LOCK.lock().await;- let tmp = TempDir::new().expect("tempdir");- let (_workspace, _cfg) = isolated_config(&tmp).await;- let put = MemoryToolsPutTool;- let stored = put- .execute(json!({- "tool_name": "web_search",- "rule": "prefer primary sources",- "priority": "critical"- }))- .await- .expect("put should succeed");- let stored: serde_json::Value =- serde_json::from_str(&stored.text()).expect("put result should be json");- let stored_id = stored["id"].as_str().expect("stored id").to_string();-- let list = super::super::list::MemoryToolsListTool;- let listed = list- .execute(json!({ "tool_name": "web_search" }))- .await- .expect("list should succeed");- let listed: serde_json::Value =- serde_json::from_str(&listed.text()).expect("list result should be json");- let ids: Vec<&str> = listed- .as_array()- .expect("list returns an array")- .iter()- .filter_map(|r| r["id"].as_str())- .collect();- assert!(- ids.contains(&stored_id.as_str()),- "the guarded list must observe the guarded put: {ids:?}"- );-}