Skip to content

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

feat(memory): agent recall returns evidence and leaves the calling thread out

sanil-23a0d1bdc12d2e
diff --git a/Cargo.lock b/Cargo.lock
index 82f9dea551..9ae7574be2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -9547,7 +9547,7 @@ dependencies = [
"log",
"serde",
"serde_json",
- "sha2 0.10.9",
+ "sha2 0.11.0",
"thiserror 2.0.20",
"tinymemory-api",
]
diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rs
index 464ca58767..b7c6b9990b 100644
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@ -9,7 +9,8 @@
use chrono::Utc;
use tinymemory_api::{
EraseRequest, FetchRequest, ForgetTarget, ItemId, LearningKind, ListRequest, MemoryMeta,
- MetaFilter, RecallRequest, StoreItem, StoreReceipt, TimeHint, WriteOptions,
+ MetaFilter, RecallMode, RecallRequest, StoreItem, StoreReceipt, ThreadWindow, TimeHint,
+ WriteOptions,
};
use crate::config::Config;
@@ -170,6 +171,19 @@ fn time_hint(config: &Config, refers_to: Option<RefersTo>) -> MemoryResult<Optio
/// `memory_recall`.
pub async fn recall(config: &Config, params: RecallParams) -> MemoryResult<RecallView> {
+ recall_with(config, params, RecallMode::Answer, None).await
+}
+
+/// [`recall`] in `mode`, leaving `exclude_thread`'s turns out. The agent's
+/// memory tool asks for [`RecallMode::Evidence`] (its own model answers) and
+/// excludes the thread it runs in, whose user turn is logged before the tool
+/// reads and would otherwise come back as a memory.
+pub async fn recall_with(
+ config: &Config,
+ params: RecallParams,
+ mode: RecallMode,
+ exclude_thread: Option<ThreadWindow>,
+) -> MemoryResult<RecallView> {
let bound = bound(config)?;
let request = RecallRequest {
question: params.question,
@@ -177,12 +191,15 @@ pub async fn recall(config: &Config, params: RecallParams) -> MemoryResult<Recal
limit: clamp_limit(params.limit),
instructions: None,
refers_to: time_hint(config, params.refers_to)?,
+ exclude_thread,
+ mode,
};
request.validate()?;
let answer = bound.engine.recall(request).await?;
tracing::debug!(
engine = %bound.id,
citations = answer.citations.len(),
+ ?mode,
"[memory:ops] recall answered"
);
Ok(RecallView {
@@ -195,6 +212,15 @@ pub async fn recall(config: &Config, params: RecallParams) -> MemoryResult<Recal
/// `memory_fetch`. An unset mode uses the engine's first declared mode; a
/// mode the engine does not declare is `UNSUPPORTED`.
pub async fn fetch(config: &Config, params: FetchParams) -> MemoryResult<FetchView> {
+ fetch_with(config, params, None).await
+}
+
+/// [`fetch`] leaving `exclude_thread`'s turns out (see [`recall_with`]).
+pub async fn fetch_with(
+ config: &Config,
+ params: FetchParams,
+ exclude_thread: Option<ThreadWindow>,
+) -> MemoryResult<FetchView> {
let bound = bound(config)?;
let descriptor = bound.engine.descriptor();
let mode = match params.mode {
@@ -216,6 +242,7 @@ pub async fn fetch(config: &Config, params: FetchParams) -> MemoryResult<FetchVi
beliefs: 0,
max_scopes: None,
refers_to: time_hint(config, params.refers_to)?,
+ exclude_thread,
};
request.validate()?;
let page = bound.engine.fetch(request).await?;
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rs
index 3892356a45..0fabea82a6 100644
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@ -23,7 +23,9 @@ use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use serde_json::{json, Value};
-use tinymemory_api::{MemoryMeta, Namespace, Reach, SourceKind, SourceRef, ToolCallRef};
+use tinymemory_api::{
+ MemoryMeta, Namespace, Reach, RecallMode, SourceKind, SourceRef, ThreadWindow, ToolCallRef,
+};
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};
use crate::config::Config;
@@ -33,7 +35,9 @@ use crate::core::events::DomainEvent;
use super::error::MemoryError;
use super::ops;
pub use super::tool_budget::is_budget_refusal;
-use super::types::{FetchParams, ForgetParams, LearnParams, RecallParams, TurnCitation};
+use super::types::{
+ FetchParams, ForgetParams, LearnParams, RecallParams, RecallView, TurnCitation,
+};
/// Most citations kept per thread between two drains.
const MAX_TURN_CITATIONS: usize = 20;
@@ -218,17 +222,39 @@ fn parse<T: serde::de::DeserializeOwned>(args: &Value) -> Result<T, String> {
serde_json::from_value(args.clone()).map_err(|error| format!("invalid arguments: {error}"))
}
+/// The turns a read inside a thread leaves out: the whole calling thread,
+/// whose turns the agent's prompt already holds.
+fn calling_thread(facts: &CallFacts) -> Option<ThreadWindow> {
+ facts.thread_id.as_deref().map(ThreadWindow::whole)
+}
+
+/// What `recall` shows the model: the evidence to answer from and how many
+/// items it holds (their ids are kept as the turn's citations), or a note
+/// when nothing was recalled. The citations' snippets repeat the evidence,
+/// so they are left out.
+fn evidence_json(view: &RecallView) -> Value {
+ if view.answer.trim().is_empty() {
+ json!({ "evidence": "", "note": "Nothing relevant is stored in memory." })
+ } else {
+ json!({ "evidence": view.answer, "items": view.citations.len() })
+ }
+}
+
/// Runs one action. Errors become a model-visible tool error, never a hard
/// failure, so the model can adapt (memory off, unsupported mode, …).
pub async fn run_action(config: &Config, args: &Value, facts: &CallFacts) -> ToolResult {
let action = arg_str(args, "action").unwrap_or_default();
tracing::debug!(action = %action, "[memory:tool] dispatch");
let result: Result<Value, String> = match action.as_str() {
+ // The agent answers from the evidence itself, so recall writes no
+ // answer of its own; and the thread the call runs in is left out of
+ // recall and fetch, since its user turn is logged before the tool
+ // reads and would otherwise come back as a memory.
"recall" => match parse::<RecallParams>(args) {
Ok(mut params) => {
confine(&mut params.filter, facts);
let question = params.question.clone();
- ops::recall(config, params)
+ ops::recall_with(config, params, RecallMode::Evidence, calling_thread(facts))
.await
.map(|view| {
if let Some(thread_id) = facts.thread_id.as_deref() {
@@ -240,7 +266,7 @@ pub async fn run_action(config: &Config, args: &Value, facts: &CallFacts) -> Too
thread_id: facts.chat.as_ref().map(|chat| chat.thread_id.clone()),
client_id: facts.chat.as_ref().map(|chat| chat.client_id.clone()),
});
- json!(view)
+ evidence_json(&view)
})
.map_err(render_error)
}
@@ -249,7 +275,7 @@ pub async fn run_action(config: &Config, args: &Value, facts: &CallFacts) -> Too
"fetch" => match parse::<FetchParams>(args) {
Ok(mut params) => {
confine(&mut params.filter, facts);
- ops::fetch(config, params)
+ ops::fetch_with(config, params, calling_thread(facts))
.await
.map(|view| json!(view))
.map_err(render_error)
@@ -320,8 +346,13 @@ impl Tool for MemoryTool {
fn description(&self) -> &str {
"Long-term memory across conversations, documents and learnings. \
- `recall` answers a question from memory with citations; `fetch` returns raw \
- matching items (filter by metadata such as workspace, repo, file_path, kinds); \
+ `recall` searches memory for a question and returns what it holds (facts and \
+ dated conversation lines) for you to answer from; it does not answer for you. \
+ Search matches meaning and wording: if a search misses something, search again \
+ with different words before concluding it is not in memory, and search \
+ separately for each part of a question that combines several things. `fetch` \
+ returns raw matching items (filter by metadata such as workspace, repo, \
+ file_path, kinds); \
`learn` queues a durable fact, preference, procedure or correction about the \
user or their work, shared with every agent working alongside you; `forget` \
queues removal of items by id. Write acknowledgements mean locally queued, \
@@ -420,3 +451,7 @@ mod schema_tests;
#[cfg(test)]
#[path = "tools_budget_tests.rs"]
mod budget_tests;
+
+#[cfg(test)]
+#[path = "tools_read_tests.rs"]
+mod read_tests;
diff --git a/crates/openhuman-core/src/memory/tools_read_tests.rs b/crates/openhuman-core/src/memory/tools_read_tests.rs
new file mode 100644
index 0000000000..f31894623c
--- /dev/null
+++ b/crates/openhuman-core/src/memory/tools_read_tests.rs
@@ -0,0 +1,164 @@
+//! The memory tool's reads: recall returns the engine's evidence, and recall
+//! and fetch leave the calling thread out.
+
+use super::*;
+use crate::memory::scope::MemoryIdentity;
+use crate::memory::test_fixtures::{bind_reference, config_in};
+use tinymemory_api::MemoryEngine;
+
+fn facts() -> CallFacts {
+ CallFacts {
+ thread_id: Some("thread-tool-1".into()),
+ agent_id: Some("orchestrator".into()),
+ ..CallFacts::of(&Config::default(), &MemoryIdentity::agent("orchestrator"))
+ }
+}
+
+fn text(result: &ToolResult) -> String {
+ result.text()
+}
+
+/// A one-turn conversation in `thread`, where `facts` reads and writes.
+fn turn_in(facts: &CallFacts, thread: &str, text: &str) -> tinymemory_api::StoreItem {
+ tinymemory_api::StoreItem::Conversation {
+ turns: vec![tinymemory_api::Turn::new(tinymemory_api::Role::User, text)],
+ meta: tinymemory_api::MemoryMeta {
+ namespace: facts.namespace.clone(),
+ thread_id: Some(thread.to_string()),
+ turns: Some(tinymemory_api::TurnRange { first: 0, last: 0 }),
+ ..tinymemory_api::MemoryMeta::default()
+ },
+ }
+}
+
+#[tokio::test]
+async fn recall_returns_evidence_and_leaves_the_calling_thread_out() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let facts = facts();
+ let live = facts.thread_id.clone().unwrap();
+ engine
+ .store(turn_in(&facts, &live, "which oolong tea did I like"))
+ .await
+ .unwrap();
+ engine
+ .store(turn_in(
+ &facts,
+ "thread-past",
+ "I liked the oolong tea from Taiwan",
+ ))
+ .await
+ .unwrap();
+
+ let recalled = run_action(
+ &config,
+ &json!({"action": "recall", "question": "oolong tea"}),
+ &facts,
+ )
+ .await;
+ assert!(!recalled.is_error, "{}", text(&recalled));
+ let out: Value = serde_json::from_str(&text(&recalled)).unwrap();
+ let evidence = out["evidence"].as_str().unwrap();
+ assert!(evidence.contains("oolong tea from Taiwan"), "{out}");
+ assert!(
+ !evidence.contains("which oolong tea did I like"),
+ "the turn being answered must not come back as a memory: {out}"
+ );
+ assert_eq!(out["items"], 1);
+ assert!(
+ out.get("answer").is_none(),
+ "recall writes no answer of its own"
+ );
+ let cites = take_turn_citations(&live);
+ assert_eq!(cites.len(), 1, "{cites:?}");
+}
+
+#[tokio::test]
+async fn fetch_leaves_the_calling_thread_out() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let facts = facts();
+ let live = facts.thread_id.clone().unwrap();
+ engine
+ .store(turn_in(&facts, &live, "oolong question in this thread"))
+ .await
+ .unwrap();
+ engine
+ .store(turn_in(&facts, "thread-past", "oolong answer from before"))
+ .await
+ .unwrap();
+
+ let fetched = run_action(
+ &config,
+ &json!({"action": "fetch", "query": "oolong", "mode": "keyword", "limit": 5}),
+ &facts,
+ )
+ .await;
+ assert!(!fetched.is_error, "{}", text(&fetched));
+ let hits = serde_json::from_str::<Value>(&text(&fetched)).unwrap()["hits"]
+ .as_array()
+ .unwrap()
+ .clone();
+ assert_eq!(hits.len(), 1, "{hits:?}");
+ assert_eq!(hits[0]["meta"]["thread_id"], "thread-past");
+}
+
+#[tokio::test]
+async fn recall_with_nothing_relevant_says_so() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ bind_reference(&config);
+ let recalled = run_action(
+ &config,
+ &json!({"action": "recall", "question": "anything at all"}),
+ &facts(),
+ )
+ .await;
+ assert!(!recalled.is_error, "{}", text(&recalled));
+ let out: Value = serde_json::from_str(&text(&recalled)).unwrap();
+ assert_eq!(out["evidence"], "");
+ assert_eq!(out["note"], "Nothing relevant is stored in memory.");
+}
+
+#[tokio::test]
+async fn the_rpc_recall_still_answers_and_excludes_nothing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let facts = facts();
+ engine
+ .store(turn_in(
+ &facts,
+ "thread-tool-1",
+ "oolong in the live thread",
+ ))
+ .await
+ .unwrap();
+ let view = ops::recall(
+ &config,
+ RecallParams {
+ question: "oolong".into(),
+ filter: None,
+ limit: None,
+ refers_to: None,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ view.citations.len(),
+ 1,
+ "no thread is excluded outside the tool"
+ );
+ assert!(
+ view.answer.starts_with("From 1 stored items"),
+ "{}",
+ view.answer
+ );
+ assert!(
+ view.model.is_some(),
+ "answer mode reports the answering engine"
+ );
+}
diff --git a/crates/openhuman-core/src/memory/types.rs b/crates/openhuman-core/src/memory/types.rs
index ca60e80ff8..1874407dd3 100644
--- a/crates/openhuman-core/src/memory/types.rs
+++ b/crates/openhuman-core/src/memory/types.rs
@@ -115,7 +115,8 @@ pub struct RefersTo {
/// `memory_recall` result.
#[derive(Debug, Clone, Serialize)]
pub struct RecallView {
- /// The synthesised answer.
+ /// The synthesised answer; in evidence mode
+ /// ([`super::ops::recall_with`]), the recalled evidence as text.
pub answer: String,
/// The items it rests on.
pub citations: Vec<Citation>,
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index f448ff9323..94187774ba 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -360,7 +360,7 @@ Spec: `docs/specs/memory-v2.md` (host) and `vendor/tinymemory/docs/specs/memory-
| 8.1.2 | Recall (answer with citations) | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tool_budget_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Ask chip; explicit agent-tool recall is bounded to 15 seconds per call, 30 seconds aggregate and 8 attempts while the bounded run record remains tracked; a timeout disables optional memory for the tracked run (idle records may be evicted under churn) |
| 8.1.3 | Fetch and list | RU+RI | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tool_budget_tests.rs`, `tests/memory_v2_e2e.rs` | ✅ | Hybrid only on both launch engines; other modes answer `UNSUPPORTED`. Explicit agent-tool fetch shares the bounded recall budget |
| 8.1.4 | Forget | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | By id; agent-tool forget queues trusted-reach removal, preserves learn-before-forget order and retains failed writes for retry; a queued result does not claim removal |
-| 8.1.5 | Agent `memory` tool | RU | `crates/openhuman-core/src/memory/tools_tests.rs`, `crates/openhuman-core/src/memory/tool_budget_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs` | ✅ | Actions `recall`, `fetch`, `learn`, `forget`; write acknowledgements distinguish queueing from engine acceptance, budget exhaustion cannot fail chat, and explicit memory disable rejects new writes and pauses pending retries |
+| 8.1.5 | Agent `memory` tool | RU | `crates/openhuman-core/src/memory/tools_tests.rs`, `crates/openhuman-core/src/memory/tools_read_tests.rs`, `crates/openhuman-core/src/memory/tool_budget_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs` | ✅ | Actions `recall`, `fetch`, `learn`, `forget`; `recall` returns the engine's evidence (`RecallMode::Evidence`, no engine-written answer) and `recall`/`fetch` leave the calling thread out (`exclude_thread`); write acknowledgements distinguish queueing from engine acceptance, budget exhaustion cannot fail chat, and explicit memory disable rejects new writes and pauses pending retries |
| 8.1.6 | Erase all and queued-write privacy fence | RU | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs` | ✅ | Explicit erase holds an owner mutation barrier through engine erasure, waits only for current mutations, clears earlier pending tool writes across that owner's team/layout partitions, retires queued automatic turn logs, waits for active automatic work, and preserves later enqueues and other owners. Restart and successive-fence regressions prevent old queued learnings from reappearing. Source/import/belief jobs and legacy post-turn logging retain their existing lifecycle |
### 8.2 Engines, Ingestion and Context
diff --git a/vendor/tinymemory b/vendor/tinymemory
index 5671f49b3f..f6a1b3cdae 160000
--- a/vendor/tinymemory
+++ b/vendor/tinymemory
@@ -1 +1 @@
-Subproject commit 5671f49b3f5ded9814b951cee9c1691af4a3c90c
+Subproject commit f6a1b3cdae51f2790d8b4888a63e0832aabfc415