Skip to content

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

feat(memory): compacted turns recallable, capped evidence, paged fetch

sanil-23fb3043e5125f
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
index ecca2e5280..2ed272bfcf 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
@@ -167,6 +167,7 @@ impl OpenHumanTurnPrelude {
identity,
thread_id,
pack,
+ in_prompt_from,
core: self.host_env.core.clone(),
}))
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs
index d130f2df40..373a577ed7 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs
@@ -53,6 +53,10 @@ pub(crate) struct HostOperationContext {
/// Who the run acts as on memory; see
/// [`OpenHumanRunContext::memory_identity`](super::OpenHumanRunContext::memory_identity).
pub(crate) memory_identity: Option<crate::memory::scope::MemoryIdentity>,
+ /// The thread's turns still verbatim in the run's prompt, from the turn's
+ /// memory (see [`MemoryTurn::in_prompt`](crate::memory::lifecycle::hooks::MemoryTurn::in_prompt)).
+ /// `None` when the turn has no memory, as a sub-agent's run does.
+ pub(crate) memory_in_prompt: Option<tinymemory_api::ThreadWindow>,
/// The context the run acts under; see
/// [`OpenHumanRunContext::core`](super::OpenHumanRunContext::core).
pub(crate) core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,
@@ -119,6 +123,20 @@ pub(crate) fn memory_identity_for_tool(
.and_then(|host| host.memory_identity.clone())
}
+/// Reads the thread's turns still verbatim in the run's prompt from the
+/// explicit tool carrier. Direct tool dispatch has none.
+pub(crate) fn memory_in_prompt_for_tool(
+ context: Option<&dyn tinytools::ToolRunContext>,
+) -> Option<tinymemory_api::ThreadWindow> {
+ context
+ .and_then(tinytools::ToolRunContext::host_extension)
+ .and_then(|extension| {
+ extension.downcast_ref::<tinyagents_harness::tool::ToolExecutionContext>()
+ })
+ .and_then(|context| context.state::<HostOperationContext>())
+ .and_then(|host| host.memory_in_prompt.clone())
+}
+
/// Reads the calling agent's sandbox policy from the explicit tool carrier.
/// Direct tool dispatch has no agent-specific mode.
pub(crate) fn sandbox_mode_for_tool(
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 9bb3b487ac..eb8210205e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -419,9 +419,9 @@ pub(crate) struct HarnessHostPolicy {
pub(crate) use super::operation_context::tool_context_with_approval;
pub use super::operation_context::OpenHumanRunExt;
pub(crate) use super::operation_context::{
- approval_for_tool, dispatch_ctx_for_tool, memory_identity_for_tool, parent_agent_id_for_tool,
- sandbox_mode_for_tool, task_recency_window_for_tool, turn_origin_for_tool,
- HostOperationContext,
+ approval_for_tool, dispatch_ctx_for_tool, memory_identity_for_tool, memory_in_prompt_for_tool,
+ parent_agent_id_for_tool, sandbox_mode_for_tool, task_recency_window_for_tool,
+ turn_origin_for_tool, HostOperationContext,
};
impl Default for OpenHumanRunContext {
@@ -682,6 +682,7 @@ impl OpenHumanRunContext {
.as_ref()
.map(|parent| parent.agent_definition_id.clone()),
memory_identity: self.memory_identity.clone(),
+ memory_in_prompt: self.memory_turn.as_ref().map(|turn| turn.in_prompt()),
core: self.core.clone(),
});
let context = tinyagents_harness::context::RunContext::new(config, self)
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
index a316d2b669..99c4e228c8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
@@ -685,3 +685,42 @@ fn a_run_kept_past_its_turn_does_not_pin_the_tenant() {
// outlive a turn reference it weakly.
assert!(!core.tenant_in_use());
}
+
+#[test]
+fn the_turns_still_in_the_prompt_reach_the_runs_tools() {
+ let config = crate::config::Config::default();
+ let mut host = OpenHumanRunContext::new();
+ host.memory_turn = Some(std::sync::Arc::new(
+ crate::memory::lifecycle::hooks::MemoryTurn {
+ identity: crate::memory::scope::MemoryIdentity::agent("a").resolve(&config),
+ config: std::sync::Arc::new(config),
+ thread_id: "thread-long".into(),
+ pack: None,
+ in_prompt_from: 12,
+ core: None,
+ },
+ ));
+ let run = host.into_tinyagents(tinyagents_harness::context::RunConfig::new("memory-window"));
+ let call = tinyagents_harness::tool::ToolExecutionContext::from_run_context(
+ &run,
+ tinyagents_harness::ids::CallId::new("memory-window-call"),
+ );
+ assert_eq!(
+ memory_in_prompt_for_tool(Some(&call)),
+ Some(tinymemory_api::ThreadWindow {
+ thread_id: "thread-long".into(),
+ from_turn: 12,
+ })
+ );
+
+ // A run without the turn's memory (a sub-agent's, a direct dispatch)
+ // knows no window.
+ let bare = OpenHumanRunContext::new()
+ .into_tinyagents(tinyagents_harness::context::RunConfig::new("no-memory"));
+ let call = tinyagents_harness::tool::ToolExecutionContext::from_run_context(
+ &bare,
+ tinyagents_harness::ids::CallId::new("no-memory-call"),
+ );
+ assert_eq!(memory_in_prompt_for_tool(Some(&call)), None);
+ assert_eq!(memory_in_prompt_for_tool(None), None);
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
index 45d8f13ed2..f551d7c23b 100644
--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
@@ -54,6 +54,7 @@ async fn bound_turn(tmp: &tempfile::TempDir) -> Arc<MemoryTurn> {
identity,
thread_id: "t".into(),
pack: None,
+ in_prompt_from: 0,
core: None,
})
}
@@ -237,6 +238,7 @@ async fn a_held_memory_engine_does_not_delay_transcript_compaction() {
identity,
thread_id: "held".into(),
pack: None,
+ in_prompt_from: 0,
core: None,
});
let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn));
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs
index 9ddce6fd36..0f23e94cf2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs
@@ -19,6 +19,7 @@ fn context(pack: Option<TurnPack>) -> RunContext<OpenHumanRunContext> {
config: Arc::new(config),
thread_id: "t".into(),
pack,
+ in_prompt_from: 0,
core: None,
}));
RunContext::new(RunConfig::new("memory-pack-test"), data)
diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
index 0909d0dda4..d2122fd7c4 100644
--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
@@ -151,12 +151,26 @@ pub struct MemoryTurn {
pub thread_id: String,
/// The pack the turn was given, if any.
pub pack: Option<TurnPack>,
+ /// The first turn of the thread still verbatim in the turn's prompt:
+ /// the turns before it were compacted into a checkpoint. 0 when nothing
+ /// was compacted.
+ pub in_prompt_from: u32,
/// The context the turn runs under, held weakly so a finished tenant's
/// lease is not kept alive by a lingering turn handle.
pub core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,
}
impl MemoryTurn {
+ /// The thread's turns still verbatim in the turn's prompt, which the
+ /// agent's own memory reads leave out (the compacted ones stay readable).
+ #[must_use]
+ pub fn in_prompt(&self) -> tinymemory_api::ThreadWindow {
+ tinymemory_api::ThreadWindow {
+ thread_id: self.thread_id.clone(),
+ from_turn: self.in_prompt_from,
+ }
+ }
+
/// The dispatch context the turn's memory work runs under: its own, else
/// the calling task's.
#[must_use]
diff --git a/crates/openhuman-core/src/memory/parameters/memory.json b/crates/openhuman-core/src/memory/parameters/memory.json
index 814a015c10..ee6bbf4198 100644
--- a/crates/openhuman-core/src/memory/parameters/memory.json
+++ b/crates/openhuman-core/src/memory/parameters/memory.json
@@ -32,12 +32,6 @@
"type": "object",
"description": "recall/fetch: metadata filter, e.g. {\"kinds\": [\"learning\"], \"workspace\": \"/path\", \"repo\": \"owner/name\"}."
},
- "limit": {
- "type": "integer",
- "minimum": 1,
- "maximum": 100,
- "description": "recall/fetch: most results."
- },
"cursor": {
"type": "string",
"description": "fetch: next-page cursor."
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rs
index bf2f00f139..d2a0fe3019 100644
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@ -43,6 +43,9 @@ use super::types::{
/// Most citations kept per thread between two drains.
const MAX_TURN_CITATIONS: usize = 20;
+/// How many matches one `fetch` returns; the model pages on with `cursor`.
+const FETCH_TOP: usize = 5;
+
type TurnCitations = Mutex<HashMap<String, Vec<TurnCitation>>>;
/// Citations `recall` produced during a thread's in-flight turn, drained by
@@ -138,6 +141,9 @@ pub struct CallFacts {
pub agent_id: Option<String>,
/// The provider-assigned tool-call id.
pub tool_call_id: Option<String>,
+ /// The calling thread's turns still verbatim in the run's prompt, when
+ /// the run knows them (a turn with memory on). Reads leave these out.
+ pub in_prompt: Option<ThreadWindow>,
/// The chat the call's turn is surfaced in, so the memory activity it
/// raises reaches that chat. `None` outside a chat turn.
pub chat: Option<crate::security::approval::ApprovalChatContext>,
@@ -173,6 +179,9 @@ impl CallFacts {
.map(str::to_string),
tool_call_id: crate::tools::host_extensions::tool_call_id(context),
chat: crate::agent::tinyagents::host::run_context::approval_for_tool(context).chat,
+ in_prompt: crate::agent::tinyagents::host::run_context::memory_in_prompt_for_tool(
+ context,
+ ),
..Self::of(config, &identity)
}
}
@@ -227,10 +236,23 @@ 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.
+/// The turns a read inside a thread leaves out: those of the calling thread
+/// the agent's prompt still holds verbatim. Turns compaction folded into a
+/// checkpoint are readable again, so a long thread can recall what it said
+/// before; when the run does not know its window, the whole thread is left
+/// out.
fn calling_thread(facts: &CallFacts) -> Option<ThreadWindow> {
- facts.thread_id.as_deref().map(ThreadWindow::whole)
+ let thread_id = facts.thread_id.as_deref()?;
+ let window = facts
+ .in_prompt
+ .clone()
+ .filter(|window| window.thread_id == thread_id)
+ .unwrap_or_else(|| ThreadWindow::whole(thread_id));
+ tracing::debug!(
+ from_turn = window.from_turn,
+ "[memory:tool] reads leave out the thread's turns still in the prompt"
+ );
+ Some(window)
}
/// What `recall` shows the model: the evidence to answer from and how many
@@ -241,8 +263,85 @@ 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() })
+ json!({ "evidence": capped_evidence(&view.answer), "items": view.citations.len() })
+ }
+}
+
+/// About how many tokens of evidence `recall` hands the model (counted as
+/// four characters a token). The rest stays reachable through `fetch`.
+const EVIDENCE_TOKENS: usize = 2_500;
+
+/// The engine's closing note when a recall searched memory only in part.
+const PARTLY_SEARCHED: &str = "\n\n(Memory was only partly searched";
+
+/// `evidence` cut to about [`EVIDENCE_TOKENS`] tokens, only ever at the end
+/// of a line: whole `---`-separated entries in rank order, then as many whole
+/// lines of the next entry as fit (marked `[…]`), then a note on what was
+/// left out. A line is never split, so a single line longer than the budget
+/// is kept whole when it is the first. The engine's closing note (memory
+/// only partly searched) is always kept.
+fn capped_evidence(evidence: &str) -> String {
+ const SEPARATOR: &str = "\n\n---\n\n";
+ let budget = EVIDENCE_TOKENS * 4;
+ if evidence.len() <= budget {
+ return evidence.to_string();
+ }
+ let (body, closing) = match evidence.rfind(PARTLY_SEARCHED) {
+ Some(at) => (&evidence[..at], &evidence[at..]),
+ None => (evidence, ""),
+ };
+ let entries: Vec<&str> = body.split(SEPARATOR).collect();
+ let mut out = String::new();
+ let mut whole = 0;
+ let mut cut_short = false;
+ for entry in &entries {
+ let joint = if out.is_empty() { "" } else { SEPARATOR };
+ if out.len() + joint.len() + entry.len() <= budget {
+ out.push_str(joint);
+ out.push_str(entry);
+ whole += 1;
+ continue;
+ }
+ // The entry does not fit: keep the whole lines of it that do.
+ let mut lines = 0;
+ for line in entry.split('\n') {
+ let piece = if lines == 0 { joint.len() } else { 1 } + line.len();
+ if out.len() + piece > budget && !out.is_empty() {
+ break;
+ }
+ out.push_str(if lines == 0 { joint } else { "\n" });
+ out.push_str(line);
+ lines += 1;
+ }
+ if lines == entry.split('\n').count() {
+ whole += 1;
+ } else if lines > 0 {
+ out.push_str("\n[…]");
+ cut_short = true;
+ }
+ break;
+ }
+ let left = entries.len() - whole - usize::from(cut_short);
+ if left > 0 || cut_short {
+ let shortened = if cut_short {
+ ", the last one shortened,"
+ } else {
+ ""
+ };
+ out.push_str(&format!(
+ "\n\n({left} more memory entries left out{shortened} to keep this under about \
+ {EVIDENCE_TOKENS} tokens; search again with more specific words to see \
+ others.)"
+ ));
}
+ tracing::debug!(
+ entries = entries.len(),
+ whole,
+ cut_short,
+ "[memory:tool] recall evidence capped"
+ );
+ out.push_str(closing);
+ out
}
/// Runs one action. Errors become a model-visible tool error, never a hard
@@ -263,6 +362,8 @@ pub async fn run_action(
"recall" => match parse::<RecallParams>(args) {
Ok(mut params) => {
confine(&mut params.filter, facts);
+ // How much recall reads is the host's call, not the model's.
+ params.limit = None;
let question = params.question.clone();
ops::recall_with(config, params, RecallMode::Evidence, calling_thread(facts))
.await
@@ -285,9 +386,18 @@ pub async fn run_action(
"fetch" => match parse::<FetchParams>(args) {
Ok(mut params) => {
confine(&mut params.filter, facts);
+ // Five at a time, always; more come through `cursor`.
+ params.limit = Some(FETCH_TOP);
ops::fetch_with(config, params, calling_thread(facts))
.await
- .map(|view| json!(view))
+ .map(|view| {
+ let mut out =
+ json!({ "matches": fetch_page(&view), "items": view.hits.len() });
+ if let Some(cursor) = view.next_cursor {
+ out["next_cursor"] = json!(cursor);
+ }
+ out
+ })
.map_err(render_error)
}
Err(error) => Err(error),
@@ -339,6 +449,35 @@ pub async fn run_action(
}
}
+/// What `fetch` shows the model: its top matches as dated lines, best first,
+/// each with the id `forget` takes. The engine's `next_cursor`, when there
+/// is one, rides beside this text; the tool description says how to use it.
+fn fetch_page(view: &super::types::FetchView) -> String {
+ let mut out = match view.hits.len() {
+ 0 => "Nothing in memory matches.".to_string(),
+ 1 => "1 match.".to_string(),
+ n => format!("Top {n} matches, best first."),
+ };
+ for hit in &view.hits {
+ out.push_str("\n\n");
+ if let Some(at) = hit.meta.observed_at {
+ out.push_str(&format!("[{}] ", at.format("%Y-%m-%d %H:%M UTC")));
+ }
+ match hit.kind {
+ tinymemory_api::ItemKind::Learning => out.push_str("learning: "),
+ tinymemory_api::ItemKind::Document => out.push_str("document: "),
+ tinymemory_api::ItemKind::Conversation => {}
+ }
+ out.push_str(hit.text.trim());
+ out.push_str(&format!("\n(id {})", hit.id));
+ }
+ tracing::debug!(
+ hits = view.hits.len(),
+ "[memory:tool] fetch matches rendered"
+ );
+ out
+}
+
/// Confines a model-supplied filter to the calling agent's reach.
fn confine(filter: &mut Option<tinymemory_api::MetaFilter>, facts: &CallFacts) {
filter.get_or_insert_with(Default::default).reach = Some(facts.reach.clone());
@@ -361,8 +500,13 @@ impl Tool for MemoryTool {
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); \
+ returns matching items five at a time, best first, each with its id (filter by \
+ metadata such as workspace, repo, file_path, kinds). When it also returns \
+ `next_cursor`, more items match: for the next five of the same search, call fetch \
+ again with the same query and filter and `cursor` set to it. For a question that \
+ counts or lists things across conversations (how many, which ones, every time), \
+ follow `next_cursor` until fetch stops returning one before answering. A cursor \
+ only continues the search it came from; for different words, fetch without one. \
`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, \
diff --git a/crates/openhuman-core/src/memory/tools_read_tests.rs b/crates/openhuman-core/src/memory/tools_read_tests.rs
index 281dfabb8d..7501395970 100644
--- a/crates/openhuman-core/src/memory/tools_read_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_read_tests.rs
@@ -18,19 +18,67 @@ fn text(result: &ToolResult) -> String {
result.text()
}
+/// A fetch result's page as the model reads it, and how many items it holds.
+fn page(result: &ToolResult) -> (String, u64) {
+ assert!(!result.is_error, "{}", text(result));
+ let out: Value = serde_json::from_str(&text(result)).unwrap();
+ (
+ out["matches"].as_str().unwrap().to_string(),
+ out["items"].as_u64().unwrap(),
+ )
+}
+
/// A one-turn conversation in `thread`, where `facts` reads and writes.
fn turn_in(facts: &CallFacts, thread: &str, text: &str) -> tinymemory_api::StoreItem {
+ turn_at(facts, thread, 0, text)
+}
+
+/// Turn `index` of `thread`, where `facts` reads and writes.
+fn turn_at(facts: &CallFacts, thread: &str, index: u32, 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 }),
+ turns: Some(tinymemory_api::TurnRange {
+ first: index,
+ last: index,
+ }),
..tinymemory_api::MemoryMeta::default()
},
}
}
+/// A long thread whose turns before `from_turn` were compacted out of the
+/// prompt: turn 2 (compacted) and turn 8 (still in the prompt).
+async fn compacted_thread(engine: &impl MemoryEngine, from_turn: u32) -> CallFacts {
+ // A thread of its own: recall records citations per thread id, process
+ // wide, and tests run in parallel.
+ let mut facts = CallFacts {
+ thread_id: Some("thread-compacted".into()),
+ ..facts()
+ };
+ let live = facts.thread_id.clone().unwrap();
+ engine
+ .store(turn_at(
+ &facts,
+ &live,
+ 2,
+ "I liked the oolong tea from Taiwan",
+ ))
+ .await
+ .unwrap();
+ engine
+ .store(turn_at(&facts, &live, 8, "which oolong tea did I like"))
+ .await
+ .unwrap();
+ facts.in_prompt = Some(ThreadWindow {
+ thread_id: live,
+ from_turn,
+ });
+ facts
+}
+
#[tokio::test]
async fn recall_returns_evidence_and_leaves_the_calling_thread_out() {
let tmp = tempfile::tempdir().unwrap();
@@ -98,13 +146,10 @@ async fn fetch_leaves_the_calling_thread_out() {
&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");
+ let (shown, items) = page(&fetched);
+ assert_eq!(items, 1, "{shown}");
+ assert!(shown.contains("oolong answer from before"), "{shown}");
+ assert!(!shown.contains("oolong question in this thread"), "{shown}");
}
#[tokio::test]
@@ -165,3 +210,250 @@ async fn the_rpc_recall_still_answers_and_excludes_nothing() {
"answer mode reports the answering engine"
);
}
+
+#[tokio::test]
+async fn recall_reads_its_own_threads_compacted_turns_but_not_the_ones_in_the_prompt() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let facts = compacted_thread(engine.as_ref(), 6).await;
+
+ let recalled = run_action(
+ &DispatchCtx::ambient(),
+ &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"),
+ "a turn compacted out of the prompt is readable again: {out}"
+ );
+ assert!(
+ !evidence.contains("which oolong tea did I like"),
+ "a turn still in the prompt must not come back as a memory: {out}"
+ );
+}
+
+#[tokio::test]
+async fn fetch_reads_its_own_threads_compacted_turns_but_not_the_ones_in_the_prompt() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let facts = compacted_thread(engine.as_ref(), 6).await;
+
+ let fetched = run_action(
+ &DispatchCtx::ambient(),
+ &config,
+ &json!({"action": "fetch", "query": "oolong", "mode": "keyword", "limit": 5}),
+ &facts,
+ )
+ .await;
+ let (shown, items) = page(&fetched);
+ assert_eq!(items, 1, "{shown}");
+ assert!(shown.contains("oolong tea from Taiwan"), "{shown}");
+ assert!(!shown.contains("which oolong tea did I like"), "{shown}");
+}
+
+#[tokio::test]
+async fn a_window_for_another_thread_leaves_the_whole_calling_thread_out() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let mut facts = compacted_thread(engine.as_ref(), 6).await;
+ facts.in_prompt = Some(ThreadWindow {
+ thread_id: "thread-elsewhere".into(),
+ from_turn: 6,
+ });
+
+ let fetched = run_action(
+ &DispatchCtx::ambient(),
+ &config,
+ &json!({"action": "fetch", "query": "oolong", "mode": "keyword", "limit": 5}),
+ &facts,
+ )
+ .await;
+ let (shown, items) = page(&fetched);
+ assert_eq!(items, 0, "{shown}");
+ assert_eq!(shown, "Nothing in memory matches.");
+}
+
+#[tokio::test]
+async fn fetch_shows_its_top_five_as_dated_lines_and_pages_on_with_its_cursor() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let facts = facts();
+ for i in 0..7 {
+ let mut item = turn_in(&facts, "thread-past", &format!("oolong note {i}"));
+ if let tinymemory_api::StoreItem::Conversation { meta, .. } = &mut item {
+ meta.observed_at = Some(
+ chrono::DateTime::parse_from_rfc3339("2023-05-21T18:53:00Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc),
+ );
+ }
+ engine.store(item).await.unwrap();
+ }
+
+ let fetched = run_action(
+ &DispatchCtx::ambient(),
+ &config,
+ &json!({"action": "fetch", "query": "oolong note", "mode": "keyword"}),
+ &facts,
+ )
+ .await;
+ let (shown, items) = page(&fetched);
+ assert_eq!(items, 5, "five at a time: {shown}");
+ assert!(shown.starts_with("Top 5 matches, best first."), "{shown}");
+ assert!(
+ shown.contains("[2023-05-21 18:53 UTC] user: oolong note"),
+ "{shown}"
+ );
+ assert!(
+ shown.contains("(id "),
+ "each match carries the id forget takes: {shown}"
+ );
+ assert!(!shown.contains("namespace"), "no metadata dump: {shown}");
+
+ // More match: the engine's cursor continues the same search.
+ let cursor = serde_json::from_str::<Value>(&text(&fetched)).unwrap()["next_cursor"]
+ .as_str()
+ .expect("a fetch with more matches returns next_cursor")
+ .to_string();
+ let next = run_action(
+ &DispatchCtx::ambient(),
+ &config,
+ &json!({"action": "fetch", "query": "oolong note", "mode": "keyword", "cursor": cursor}),
+ &facts,
+ )
+ .await;
+ let (rest, items) = page(&next);
+ assert_eq!(items, 2, "{rest}");
+ assert!(
+ serde_json::from_str::<Value>(&text(&next))
+ .unwrap()
+ .get("next_cursor")
+ .is_none(),
+ "the last page has no cursor"
+ );
+ let notes = |text: &str| {
+ (0..7)
+ .filter(|i| text.contains(&format!("oolong note {i}")))
+ .collect::<Vec<_>>()
+ };
+ let mut seen = notes(&shown);
+ seen.extend(notes(&rest));
+ seen.sort_unstable();
+ assert_eq!(
+ seen,
+ (0..7).collect::<Vec<_>>(),
+ "the two pages hold every note once"
+ );
+
+ let more = run_action(
+ &DispatchCtx::ambient(),
+ &config,
+ &json!({"action": "fetch", "query": "oolong note", "mode": "keyword", "limit": 10}),
+ &facts,
+ )
+ .await;
+ assert_eq!(
+ page(&more).1,
+ 5,
+ "the page size is the host's: a model's limit is ignored"
+ );
+}
+
+/// `n` entries of `lines` lines each, `width` characters a line, as an
+/// engine renders evidence.
+fn evidence_of(n: usize, lines: usize, width: usize) -> String {
+ (0..n)
+ .map(|e| {
+ (0..lines)
+ .map(|l| {
+ let head = format!("[2023-05-21 01:33 UTC] [user] entry {e} line {l} ");
+ format!("{head}{}", "x".repeat(width.saturating_sub(head.len())))
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ })
+ .collect::<Vec<_>>()
+ .join("\n\n---\n\n")
+}
+
+/// Every line of `capped` is a whole line of `evidence`, or one of the cap's
+/// own markers.
+fn assert_whole_lines(evidence: &str, capped: &str) {
+ let source: std::collections::HashSet<&str> = evidence.lines().collect();
+ for line in capped.lines() {
+ assert!(
+ source.contains(line) || line == "[…]" || line.starts_with('('),
+ "a line was cut: {line:?}"
+ );
+ }
+}
+
+#[test]
+fn short_evidence_is_left_as_it_is() {
+ let evidence = evidence_of(3, 2, 80);
+ assert_eq!(capped_evidence(&evidence), evidence);
+}
+
+#[test]
+fn long_evidence_keeps_whole_entries_then_whole_lines_and_says_what_was_left_out() {
+ // 30 entries of 4 lines of 200 characters: about 6,000 tokens.
+ let evidence = evidence_of(30, 4, 200);
+ let capped = capped_evidence(&evidence);
+ let note = capped.rfind("\n\n(").unwrap();
+ assert!(
+ note <= EVIDENCE_TOKENS * 4,
+ "the evidence stays within the budget"
+ );
+ assert_whole_lines(&evidence, &capped);
+ // 12 whole entries (12 × 803 + 11 separators = 9,713 characters), then
+ // the 13th cut after its first line.
+ assert!(capped.contains("entry 11 line 3"), "{capped}");
+ assert!(capped.contains("entry 12 line 0"), "{capped}");
+ assert!(!capped.contains("entry 12 line 1"), "{capped}");
+ assert!(
+ capped.contains("entry 12 line 0 xxx"),
+ "the kept line is whole"
+ );
+ assert!(capped.contains("\n[…]"), "a shortened entry is marked");
+ assert!(
+ capped.contains("(17 more memory entries left out, the last one shortened,")
+ && capped.contains("search again with more specific words"),
+ "{}",
+ &capped[note..]
+ );
+}
+
+#[test]
+fn a_first_line_longer_than_the_budget_is_kept_whole_never_split() {
+ let evidence = evidence_of(2, 1, EVIDENCE_TOKENS * 4 + 500);
+ let capped = capped_evidence(&evidence);
+ assert_whole_lines(&evidence, &capped);
+ assert!(capped.starts_with(evidence.lines().next().unwrap()));
+ assert!(!capped.contains("[…]"), "the first entry was kept whole");
+ assert!(
+ capped.contains("(1 more memory entries left out to keep"),
+ "{capped}"
+ );
+}
+
+#[test]
+fn the_partly_searched_note_survives_the_cap() {
+ let evidence = format!(
+ "{}\n\n(Memory was only partly searched: one scope did not answer in time.)",
+ evidence_of(30, 4, 200)
+ );
+ let capped = capped_evidence(&evidence);
+ assert!(
+ capped.ends_with("(Memory was only partly searched: one scope did not answer in time.)")
+ );
+ assert_whole_lines(&evidence, &capped);
+}
diff --git a/crates/openhuman-core/src/memory/tools_schema_tests.rs b/crates/openhuman-core/src/memory/tools_schema_tests.rs
index a0820f1799..26305e3565 100644
--- a/crates/openhuman-core/src/memory/tools_schema_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_schema_tests.rs
@@ -14,7 +14,6 @@ fn expected_memory() -> serde_json::Value {
"query": {"type": "string", "description": "fetch: what to search for."},
"mode": {"type": "string", "enum": ["hybrid", "keyword", "vector"], "description": "fetch: retrieval mode; only the engine's declared modes work (hybrid is always safe)."},
"filter": {"type": "object", "description": "recall/fetch: metadata filter, e.g. {\"kinds\": [\"learning\"], \"workspace\": \"/path\", \"repo\": \"owner/name\"}."},
- "limit": {"type": "integer", "minimum": 1, "maximum": 100, "description": "recall/fetch: most results."},
"cursor": {"type": "string", "description": "fetch: next-page cursor."},
"refers_to": {
"type": "object",
diff --git a/crates/openhuman-core/src/memory/tools_tests.rs b/crates/openhuman-core/src/memory/tools_tests.rs
index 7b40a6ff7b..c090a94638 100644
--- a/crates/openhuman-core/src/memory/tools_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_tests.rs
@@ -204,10 +204,7 @@ async fn recall_fetch_and_forget_round_trip_and_recall_records_citations() {
.await;
assert!(!fetched.is_error, "{}", text(&fetched));
assert_eq!(
- serde_json::from_str::<Value>(&text(&fetched)).unwrap()["hits"]
- .as_array()
- .unwrap()
- .len(),
+ serde_json::from_str::<Value>(&text(&fetched)).unwrap()["items"],
1
);
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index fe44a7c8a6..9492df1fdc 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/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.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) capped at about 2,500 tokens, cut only at line ends; `fetch` returns five matches at a time (no `limit` argument), as dated lines with their ids, plus the engine's `next_cursor` for the next five of the same search; and `recall`/`fetch` leave out the calling thread's turns still verbatim in the prompt (`exclude_thread`; turns compacted out of the prompt stay readable, and with no known window the whole thread is left out); 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