Skip to content

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

fix: fence queued memory work and preserve harness budgets

Steven Enamakeleb59de28d84d
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
index 88351d45d9..d0829da44c 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
@@ -54,7 +54,7 @@ pub(crate) fn typed_dispatch_for(
"close_subagent" => Arc::new(CloseSubagentDispatch::new(adapter)),
"list_subagents" => Arc::new(ListSubagentsDispatch::new(adapter)),
"delegate_graph" => Arc::new(DelegateGraphDispatch::new(adapter)),
- "delegate" => Arc::new(DelegateToolDispatch::new(adapter)),
+ "delegate" | "memory" => Arc::new(DelegateToolDispatch::new(adapter)),
"todo" => Arc::new(TodoToolDispatch::new(adapter)),
_ => {
return DelegationDispatch::for_tool(adapter).map(|dispatch| {
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration_tests.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration_tests.rs
index 9ad7f1c4b8..44d7969bd9 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration_tests.rs
@@ -48,3 +48,34 @@ fn threaded_turn_keeps_goal_tools_as_exposure_candidates() {
);
}
}
+
+#[tokio::test]
+async fn registered_memory_dispatch_enforces_one_budget_across_distinct_calls() {
+ use crate::memory::test_fixtures::{bind_reference, config_in};
+ use tinyagents_harness::{context::RunConfig, CallId};
+ use tinytools::ToolCallOptions;
+ let workspace = tempfile::tempdir().unwrap();
+ let config = config_in(&workspace);
+ let _engine = bind_reference(&config);
+ let tools: Arc<Vec<Box<dyn tinytools::Tool>>> = Arc::new(vec![Box::new(
+ crate::memory::tools::MemoryTool::new(Arc::new(config.clone())),
+ )]);
+ let adapter = CanonicalSharedToolAdapter::for_name(vec![tools], "memory").unwrap();
+ let dispatch = typed_dispatch_for("memory", Arc::new(adapter))
+ .expect("memory registration must preserve the harness run context");
+ let parent = OpenHumanRunContext::new().into_tinyagents(RunConfig::new("memory-dispatch"));
+ for index in 0..9 {
+ let result = dispatch
+ .execute(
+ &(),
+ CallId::new(format!("call-{index}")),
+ serde_json::json!({"action":"learn","text":format!("fact {index}")}),
+ ToolCallOptions::default(),
+ &parent,
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.is_error, index == 8, "call {index}");
+ }
+ crate::memory::tool_writes::drain(&config).await;
+}
diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.md
index fa60ad7e9c..e5cd38c04c 100644
--- a/crates/openhuman-core/src/memory/README.md
+++ b/crates/openhuman-core/src/memory/README.md
@@ -97,18 +97,19 @@ session has no root and memory stays off.
### Around every turn
TinyMemory's `AgentMemory` runs the lifecycle. [`lifecycle/mod.rs`](./lifecycle/mod.rs) builds one
-for an identity under the `[memory.recall]` policy, and [`lifecycle/hooks.rs`](./lifecycle/hooks.rs)
-has the three hooks the agent calls:
+for an identity under the `[memory.recall]` policy. The live turn calls
+[`lifecycle/prefetch.rs`](./lifecycle/prefetch.rs), which reads completed context
+immediately and queues engine work. [`lifecycle/hooks.rs`](./lifecycle/hooks.rs)
+contains the underlying lifecycle operations and bounded manual wrappers:
```text
user message
|
v
-session host prelude ----> hooks::pre_turn
-(agent/session_host/ logs the user turn (index 2n)
- runtime_session/ recalls a TurnPack within
- memory_ingest.rs) [memory.recall] pre_turn_timeout_ms
- | optional date hint runs beside it
+session host prelude ----> prefetch::pre_turn
+(agent/session_host/ takes a completed cached TurnPack (or none)
+ runtime_session/ queues user log (index 2n), recall and
+ memory_ingest.rs) optional date hint in a scoped worker
v
MemoryPackMiddleware ----> adds the pack to each model request of the
(agent/tinyagents/ turn as an ephemeral instruction; it is
@@ -118,24 +119,40 @@ MemoryPackMiddleware ----> adds the pack to each model request of the
model + tools run, turn is committed
|
v
-session host ------------> hooks::post_turn
+session host ------------> scoped background hooks::post_turn
logs the reply with a tool-call summary
(index 2n + 1); queues belief builds
|
v (later, when the transcript is compacted)
-memory_summarizer -------> hooks::compaction
-(agent/tinyagents/ recalls what the folded-away turns carried
- memory_summarizer.rs)
+memory_summarizer -------> prefetch::compaction
+(agent/tinyagents/ enriches from completed context only;
+ memory_summarizer.rs) queues recall of the folded-away turns
```
Turn indices follow the committed transcript: the user message of the turn
after `n` committed turns is `2n` and its reply `2n + 1`. They are stable
across retries and restarts, which is what lets TinyMemory treat a retried
-turn as a replay. Every hook is bounded by a timeout and never fails a
-turn: an engine outage degrades memory, it does not block the agent. If the
-engine refuses the whole account (for example `INSUFFICIENT_CREDITS`), the
-pack becomes a notice saying so, so the model does not read an empty pack
-as "nothing is stored".
+turn as a replay. Automatic hooks never await engine I/O on the live turn
+or the authoritative compaction summarizer. Cold or expired caches supply
+no pack; completed packs are labelled as context from an earlier lookup,
+which may be incomplete or unrelated to the current question. Explicit
+recall/fetch is the path to a current answer. If completed recall refuses
+the account (for example `INSUFFICIENT_CREDITS`), its pack is a notice that
+memory is unavailable, rather than evidence that nothing is stored.
+
+The cache is scoped to CoreContext, workspace, config fingerprint, resolved
+memory identity and thread. Entries expire after 60 seconds. There are at
+most 64 entries per context, 64 KiB per pack (including citations), eight
+active workers globally and 16 pending operations per entry. Each operation
+has a 120-second background deadline. When capacity is exhausted, automatic
+work is skipped without making the turn wait. The cache itself stays in process memory.
+Content invalidation clears packs and rejects stale completions while
+preserving queued logs; engine/credential invalidation also clears pending
+refreshes. Scoped spawns retain the caller's core and memory identity.
+
+The explicit/manual `hooks::pre_turn` and `hooks::compaction` retain their
+configured `pre_turn_timeout_ms` and `compaction_timeout_ms` deadlines; they
+are not what the live prelude and compaction wrapper await.
A few details hang off the turn. For a message that arrived on a channel,
`lifecycle::sender::channel_actor` records the sender as the observed actor
@@ -256,12 +273,14 @@ The agent `memory` tool applies the same confinement and overwrites any
| [`scope.rs`](./scope.rs) | `MemoryIdentity`, `ResolvedIdentity`, resolution order, `within` / `within_agent`, layout v3 roots. |
| [`local_root.rs`](./local_root.rs) | The persistent install-id root of a signed-out session. |
| [`lifecycle/mod.rs`](./lifecycle/mod.rs) | Builds `AgentMemory` for an identity under the `[memory.recall]` policy. |
-| [`lifecycle/hooks.rs`](./lifecycle/hooks.rs) | `pre_turn`, `post_turn`, `compaction`; `TurnPack`, `MemoryTurn`. |
+| [`lifecycle/hooks.rs`](./lifecycle/hooks.rs) | Lifecycle operations and bounded manual wrappers; `TurnPack`, `MemoryTurn`. |
+| [`lifecycle/prefetch.rs`](./lifecycle/prefetch.rs) | Scoped in-memory packs and bounded automatic background refresh. |
| [`lifecycle/jobs.rs`](./lifecycle/jobs.rs) | The persisted background job queue and the `memory_background` run. |
| [`lifecycle/views.rs`](./lifecycle/views.rs) | Policy get/set, pack preview, agents list, jobs list/run for the UI. |
| [`lifecycle/sender.rs`](./lifecycle/sender.rs) | Maps a channel message's sender to an observed actor. |
| [`lifecycle/date_hint.rs`](./lifecycle/date_hint.rs) | Optional model call that works out which days a turn refers to. |
| [`ops.rs`](./ops.rs) | Engine list/get/set, recall, fetch, learn, forget, erase all, items list. |
+| [`tool_budget.rs`](./tool_budget.rs), [`tool_writes.rs`](./tool_writes.rs) | Agent call deadlines and durable, owner-scoped admission/delivery of optional writes. |
| [`confine.rs`](./confine.rs) | Confines the RPC surface to the acting identity's subtree. |
| [`explore.rs`](./explore.rs) | The facet explorer behind `memory_explore` and `memory_items_get`. |
| [`brain.rs`](./brain.rs) | Brain source mapping and the `memory_brain_*` ops. |
@@ -290,24 +309,37 @@ The agent `memory` tool applies the same confinement and overwrites any
supply its own `MemoryEngine`.
- `scope::within_agent` and `scope::resolve_current` (`scope.rs`): set and
read the acting identity around a turn.
-- `lifecycle::hooks::pre_turn`, `post_turn`, `compaction`
- (`lifecycle/hooks.rs`): what the agent harness calls.
+- `lifecycle::prefetch::pre_turn` and `compaction`
+ (`lifecycle/prefetch.rs`): synchronous reads of completed packs plus scoped
+ background refresh. `lifecycle::hooks` contains the underlying operations;
+ `post_turn` is spawned after durable commit.
- `lifecycle::jobs::enqueue` and `run_due` (`lifecycle/jobs.rs`): the
background queue.
- `MemoryTool` and `run_action` ([`tools.rs`](./tools.rs)): the `recall | fetch | learn |
forget` tool. `learn` stamps the item with facts the model does not choose:
workspace, thread id, memory agent id, the learnings namespace, the tool
call, and `source.kind = agent`.
- `MemoryTool` bounds optional engine work with [`tool_budget.rs`](./tool_budget.rs):
- 15 seconds per call, 30 seconds of aggregate engine time and eight attempts
- per tracked harness run. The bounded tracker retains 128 run records and never
- evicts an outstanding reservation; idle records may age out under run churn.
- Concurrent reads reserve from the same time budget. A timeout
- disables further memory calls in that run and returns a tool error asking the
- model to continue without memory; the next run starts fresh. A timed-out write
- can already have reached the server, so the error warns against retrying it.
- Calls outside a harness still have the per-call deadline. RPC operations and
- explicit settings/import/deletion workflows retain their own behavior.
+ `MemoryTool` bounds calls with [`tool_budget.rs`](./tool_budget.rs): 15 seconds
+ per call, 30 seconds of aggregate reserved time and eight attempts per tracked
+ harness run. Concurrent calls reserve from the same budget. The tracker holds
+ 128 run records and never evicts an outstanding reservation. Aggregate limits
+ apply while the record is retained; idle eviction under churn can reset the
+ record if that same run later calls memory again. A timeout disables further
+ memory calls in the retained record and tells the model to continue without
+ retrying; a new run starts fresh. Calls
+ outside a harness still have the per-call deadline.
+ Explicit `recall`/`fetch` await the engine within that budget. Agent
+ `learn`/`forget` instead validate, confine and scrub their request into the
+ private durable [`tool_writes.rs`](./tool_writes.rs) outbox, then start scoped
+ background delivery. An acknowledgement says "queued; not yet saved to memory"
+ or "queued; not yet removed from memory"; it confirms local admission, not a
+ remote mutation. The model must not claim the write completed or repeat it to
+ force indexing. A timed-out admission may already be durable, so it also must
+ not be retried blindly. The queue holds at most 256 entries and 2 MiB per
+ partition, retries under the matching owner on auth/background ticks, and
+ keeps credentials out of persisted entries. Explicit RPC, UI, import and
+ deletion workflows retain their own behavior.
+
- `deletion::forget_thread` (`deletion.rs`): called by `threads` when a
thread is deleted. `channels::forget_channel` is called by `channels` on
disconnect.
diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
index 7e46d37294..84231e0c75 100644
--- a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
@@ -167,23 +167,31 @@ pub(crate) fn pre_turn(
enqueue(
cache,
key,
- Box::pin(crate::core::runtime::spawn::scoped(async move {
- if config.memory.conversations.enabled {
- if let Some(channel) = channel {
- let workspace = config.workspace_dir.clone();
- let thread = input.thread_id.clone();
- let _ = crate::core::runtime::spawn_blocking_scoped(move || {
- crate::memory::channels::record(&workspace, &channel, &thread)
- })
- .await;
+ guard_turn_work(
+ &config.clone(),
+ Box::pin(crate::core::runtime::spawn::scoped(async move {
+ if config.memory.conversations.enabled {
+ if let Some(channel) = channel {
+ let workspace = config.workspace_dir.clone();
+ let thread = input.thread_id.clone();
+ let _ = crate::core::runtime::spawn_blocking_scoped(move || {
+ crate::memory::channels::record(&workspace, &channel, &thread)
+ })
+ .await;
+ }
}
- }
- hooks::pre_turn_work(&config, &identity, input).await
- })),
+ hooks::pre_turn_work(&config, &identity, input).await
+ })),
+ ),
);
pack.map(cached_notice)
}
+fn guard_turn_work(config: &Config, work: Work) -> Work {
+ let mutation = crate::memory::tool_writes::automatic_mutation(config);
+ Box::pin(async move { mutation.run(work).await.flatten() })
+}
+
fn cached_notice(mut pack: TurnPack) -> TurnPack {
let notice = "This is cached memory from a completed background lookup for an earlier turn. It may be incomplete or unrelated to the current question; use explicit memory recall or fetch when you need a current answer.\n\n";
pack.markdown.insert_str(0, notice);
diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
index 57e582ebc1..21886f6fa2 100644
--- a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
@@ -431,3 +431,93 @@ fn runtime_shutdown_releases_worker_and_pending_work() {
assert!(!state.entries[&key].active);
assert!(state.entries[&key].pending.is_empty());
}
+
+#[tokio::test]
+async fn an_erase_retires_queued_automatic_work_and_allows_later_work() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let tmp = tempfile::tempdir().unwrap();
+ let config = crate::memory::test_fixtures::config_in(&tmp);
+ let identity = crate::memory::scope::MemoryIdentity::agent("erase-prefetch").resolve(&config);
+ let key = Key::new(&config, &identity, "erase-prefetch", false);
+ let cache = Arc::new(Cache::default());
+ let earlier = Arc::new(AtomicUsize::new(0));
+ let later = Arc::new(AtomicUsize::new(0));
+ let old_count = earlier.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ guard_turn_work(
+ &config,
+ Box::pin(async move {
+ old_count.fetch_add(1, Ordering::SeqCst);
+ Some(pack("earlier automatic log"))
+ }),
+ ),
+ );
+ // The current-thread executor has not polled the earlier job. Erasure
+ // advances the owner fence synchronously before its first suspension.
+ let fence = crate::memory::tool_writes::fence_and_clear(&config)
+ .await
+ .unwrap();
+ let new_count = later.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ guard_turn_work(
+ &config,
+ Box::pin(async move {
+ new_count.fetch_add(1, Ordering::SeqCst);
+ Some(pack("later automatic log"))
+ }),
+ ),
+ );
+ drop(fence);
+ drain(&cache, &key).await;
+ assert_eq!(
+ earlier.load(Ordering::SeqCst),
+ 0,
+ "old automatic logs must never poll after erase begins"
+ );
+ assert_eq!(later.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn erase_waits_for_current_automatic_work_before_returning_its_barrier() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = crate::memory::test_fixtures::config_in(&tmp);
+ let identity = crate::memory::scope::MemoryIdentity::agent("erase-active").resolve(&config);
+ let key = Key::new(&config, &identity, "erase-active", false);
+ let cache = Arc::new(Cache::default());
+ let started = Arc::new(tokio::sync::Notify::new());
+ let release = Arc::new(tokio::sync::Notify::new());
+ let began = started.clone();
+ let done = release.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ guard_turn_work(
+ &config,
+ Box::pin(async move {
+ began.notify_one();
+ done.notified().await;
+ Some(pack("current automatic log"))
+ }),
+ ),
+ );
+ started.notified().await;
+ let erase_config = config.clone();
+ let mut fencing =
+ tokio::spawn(
+ async move { crate::memory::tool_writes::fence_and_clear(&erase_config).await },
+ );
+ assert!(
+ tokio::time::timeout(Duration::from_secs(1), &mut fencing)
+ .await
+ .is_err(),
+ "erase must wait for the active automatic mutation"
+ );
+ release.notify_one();
+ let fence = fencing.await.unwrap().unwrap();
+ drop(fence);
+ drain(&cache, &key).await;
+}
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index 5542d3bbc6..b029b534f8 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -42,8 +42,8 @@ pub mod scope;
pub mod sources;
pub mod status;
mod tool_budget;
-pub mod tools;
pub(crate) mod tool_writes;
+pub mod tools;
pub mod types;
pub mod user_scope;
diff --git a/crates/openhuman-core/src/memory/ops_tests.rs b/crates/openhuman-core/src/memory/ops_tests.rs
index 15ed8523e8..dff2b012af 100644
--- a/crates/openhuman-core/src/memory/ops_tests.rs
+++ b/crates/openhuman-core/src/memory/ops_tests.rs
@@ -478,9 +478,12 @@ async fn erasing_memory_cancels_queued_learning_so_restart_cannot_restore_it() {
&config,
&serde_json::json!({"action":"learn","text":"Prefers tea"}),
&facts,
- ).unwrap();
+ )
+ .unwrap();
assert!(queued["status"].as_str().unwrap().starts_with("queued"));
- erase_all(&config, EraseAllParams { confirm: true }).await.unwrap();
+ erase_all(&config, EraseAllParams { confirm: true })
+ .await
+ .unwrap();
let restarted = config.clone();
crate::memory::tool_writes::drain(&restarted).await;
assert!(stored(&engine, MetaFilter::default()).await.is_empty());
diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rs
index 249378dbaf..3541d92a79 100644
--- a/crates/openhuman-core/src/memory/tool_writes.rs
+++ b/crates/openhuman-core/src/memory/tool_writes.rs
@@ -22,6 +22,7 @@ use crate::config::Config;
const MAX_PENDING: usize = 256;
const MAX_BYTES: usize = 2 * 1024 * 1024;
const WRITE_TIMEOUT: Duration = Duration::from_secs(120);
+static FENCE_SEQUENCE: AtomicU64 = AtomicU64::new(0);
static PROCESS_EPOCH: LazyLock<String> = LazyLock::new(|| uuid::Uuid::new_v4().to_string());
const QUEUED: &str = "queued; not yet saved to memory";
static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
@@ -329,6 +330,40 @@ fn partitions(config: &Config) -> MemoryResult<Vec<PathBuf>> {
Ok(files)
}
+/// Owner epoch captured when automatic turn work is admitted, before it can
+/// wait in the prefetch queue. Erasure retires older work and waits for active
+/// mutations while subsequent work waits behind the exclusive barrier.
+pub(crate) struct AutomaticMutation {
+ state: Arc<OwnerState>,
+ generation: u64,
+}
+
+impl AutomaticMutation {
+ pub(crate) async fn run<T>(self, work: impl std::future::Future<Output = T>) -> Option<T> {
+ if self.state.generation.load(Ordering::SeqCst) != self.generation {
+ return None;
+ }
+ let _barrier = self.state.barrier.read().await;
+ if self.state.generation.load(Ordering::SeqCst) != self.generation {
+ return None;
+ }
+ Some(work.await)
+ }
+}
+
+/// Captures authority without waiting on the engine or an active erasure.
+pub(crate) fn automatic_mutation(config: &Config) -> AutomaticMutation {
+ let state = owner_state(config);
+ let generation = {
+ let _admission = state
+ .admission
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ state.generation.load(Ordering::SeqCst)
+ };
+ AutomaticMutation { state, generation }
+}
+
/// Holds the owner's mutation barrier through explicit engine erasure.
/// Subsequent queued writes resume only after the outer erasure finishes.
pub(crate) struct WriteFence {
@@ -365,7 +400,9 @@ pub(crate) async fn fence_and_clear(config: &Config) -> MemoryResult<WriteFence>
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.fences.fetch_add(1, Ordering::SeqCst);
- state.generation.fetch_add(1, Ordering::SeqCst) + 1
+ let next = FENCE_SEQUENCE.fetch_add(1, Ordering::SeqCst) + 1;
+ state.generation.store(next, Ordering::SeqCst);
+ next
};
let mut fence = WriteFence {
guard: None,
diff --git a/crates/openhuman-core/src/memory/tool_writes_tests.rs b/crates/openhuman-core/src/memory/tool_writes_tests.rs
index 19e1cf5d67..edb4e2c106 100644
--- a/crates/openhuman-core/src/memory/tool_writes_tests.rs
+++ b/crates/openhuman-core/src/memory/tool_writes_tests.rs
@@ -536,3 +536,27 @@ async fn erasing_one_owner_fences_pending_writes_from_every_team_root() {
assert_eq!(drain(&second).await, 0);
assert!(stored(&engine, MetaFilter::default()).await.is_empty());
}
+
+#[tokio::test]
+async fn a_later_erase_clears_pending_writes_when_the_owner_state_was_released() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let first = fence_and_clear(&config).await.unwrap();
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Queued after the first erase began"}),
+ &facts(&config),
+ )
+ .unwrap();
+ let previous_owner = Arc::downgrade(&first.state);
+ drop(first);
+ // The default current-thread test runtime has not polled the scheduled
+ // retry yet; the weak map no longer owns the previous fence generation.
+ assert!(previous_owner.upgrade().is_none());
+ let second = fence_and_clear(&config).await.unwrap();
+ assert!(
+ read(&config.workspace_dir).unwrap().is_empty(),
+ "the second erase must discard a learning admitted before it started"
+ );
+ drop(second);
+}
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rs
index 5f547ba871..c2ad556201 100644
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@ -312,10 +312,12 @@ impl Tool for MemoryTool {
"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); \
- `learn` stores a durable fact, preference, procedure or correction about the \
+ `learn` queues a durable fact, preference, procedure or correction about the \
user or their work, shared with every agent working alongside you; `forget` \
- removes items by id. Relevant memory is already added to each turn as \
- <memory-context>; use `recall` or `fetch` to look further, and set `refers_to` when \
+ queues removal of items by id. Write acknowledgements mean locally queued, \
+ not yet saved or removed remotely; do not repeat them to force indexing. \
+ Cached memory may be added as <memory-context>; use `recall` or `fetch` \
+ for current information, and set `refers_to` when \
the question is about a particular time. Recall before asking \
the user something they may already have told you; learn things worth \
remembering next time."
@@ -358,8 +360,7 @@ impl Tool for MemoryTool {
let run_id = context
.and_then(ToolRunContext::host_extension)
.and_then(|any| any.downcast_ref::<tinyagents_harness::tool::ToolExecutionContext>())
- .map(|ctx| ctx.run_id.as_str().to_string())
- .or_else(crate::agent::turn_origin::current_request_id);
+ .map(|ctx| ctx.run_id.as_str().to_string());
Ok(self
.budget
.run(run_id, async {
@@ -403,3 +404,7 @@ mod agent_tests;
#[cfg(test)]
#[path = "tools_schema_tests.rs"]
mod schema_tests;
+
+#[cfg(test)]
+#[path = "tools_budget_tests.rs"]
+mod budget_tests;
diff --git a/crates/openhuman-core/src/memory/tools_budget_tests.rs b/crates/openhuman-core/src/memory/tools_budget_tests.rs
new file mode 100644
index 0000000000..d36cee7afd
--- /dev/null
+++ b/crates/openhuman-core/src/memory/tools_budget_tests.rs
@@ -0,0 +1,85 @@
+use super::*;
+use crate::memory::test_fixtures::{bind_reference, config_in, stored};
+use std::collections::HashSet;
+use tinyagents_harness::context::{RunConfig, RunContext};
+use tinyagents_harness::ids::CallId;
+use tinyagents_harness::tool::ToolExecutionContext;
+use tinymemory_api::MetaFilter;
+
+#[tokio::test]
+async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let tool = MemoryTool::new(Arc::new(config.clone()));
+ let first: RunContext = RunContext::new(RunConfig::new("first"), ());
+ let next: RunContext = RunContext::new(RunConfig::new("next"), ());
+ for i in 0..9 {
+ let context =
+ ToolExecutionContext::from_run_context(&first, CallId::new(format!("call-{i}")));
+ let result = tool
+ .execute_with_context(
+ json!({"action":"learn","text":format!("fact {i}")}),
+ ToolCallOptions::default(),
+ Some(&context),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.is_error, i == 8);
+ }
+ super::super::tool_writes::drain(&config).await;
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 8);
+ let context = ToolExecutionContext::from_run_context(&next, CallId::new("next-call"));
+ let result = tool
+ .execute_with_context(
+ json!({"action":"learn","text":"next turn fact"}),
+ ToolCallOptions::default(),
+ Some(&context),
+ )
+ .await
+ .unwrap();
+ assert!(!result.is_error);
+ super::super::tool_writes::drain(&config).await;
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 9);
+}
+
+#[tokio::test]
+async fn harness_runs_have_independent_budgets_and_identical_learnings_deduplicate() {
+ use tinyagents_harness::context::{RunConfig, RunContext};
+ use tinyagents_harness::ids::CallId;
+ use tinyagents_harness::tool::ToolExecutionContext;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let tool = MemoryTool::new(Arc::new(config.clone()));
+ let first: RunContext = RunContext::new(RunConfig::new("first-harness-run"), ());
+ let next: RunContext = RunContext::new(RunConfig::new("next-harness-run"), ());
+ let args = json!({"action":"learn","text":"Prefers tea"});
+ let mut ids = HashSet::new();
+ for i in 0..9 {
+ let context =
+ ToolExecutionContext::from_run_context(&first, CallId::new(format!("call-{i}")));
+ let result = tool
+ .execute_with_context(args.clone(), ToolCallOptions::default(), Some(&context))
+ .await
+ .unwrap();
+ assert_eq!(result.is_error, i == 8);
+ if !result.is_error {
+ let value: Value = serde_json::from_str(&result.text()).unwrap();
+ ids.insert(value["id"].as_str().unwrap().to_string());
+ }
+ }
+ assert_eq!(
+ ids.len(),
+ 1,
+ "invocation IDs must not create duplicate learnings"
+ );
+ let context = ToolExecutionContext::from_run_context(&next, CallId::new("next-call"));
+ let result = tool
+ .execute_with_context(args, ToolCallOptions::default(), Some(&context))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "a new harness run gets a fresh budget");
+ super::super::tool_writes::drain(&config).await;
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 1);
+}
diff --git a/crates/openhuman-core/src/memory/tools_tests.rs b/crates/openhuman-core/src/memory/tools_tests.rs
index 70729b03dc..ca26d01d8d 100644
--- a/crates/openhuman-core/src/memory/tools_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_tests.rs
@@ -41,82 +41,6 @@ fn text(result: &ToolResult) -> String {
result.text()
}
-#[tokio::test]
-async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn() {
- use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- let engine = bind_reference(&config);
- let tool = MemoryTool::new(Arc::new(config.clone()));
- let origin = |request: &str| AgentTurnOrigin::WebChat {
- thread_id: "thread-budget".into(),
- client_id: "client-budget".into(),
- request_id: Some(request.into()),
- };
- with_origin(origin("first"), async {
- for i in 0..9 {
- let result = tool
- .execute(json!({"action":"learn","text":format!("fact {i}")}))
- .await
- .unwrap();
- assert_eq!(result.is_error, i == 8);
- }
- })
- .await;
- super::super::tool_writes::drain(&config).await;
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 8);
- let result = with_origin(
- origin("next"),
- tool.execute(json!({"action":"learn","text":"next turn fact"})),
- )
- .await
- .unwrap();
- assert!(!result.is_error);
- super::super::tool_writes::drain(&config).await;
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 9);
-}
-
-#[tokio::test]
-async fn harness_runs_have_independent_budgets_and_identical_learnings_deduplicate() {
- use tinyagents_harness::context::{RunConfig, RunContext};
- use tinyagents_harness::ids::CallId;
- use tinyagents_harness::tool::ToolExecutionContext;
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- let engine = bind_reference(&config);
- let tool = MemoryTool::new(Arc::new(config.clone()));
- let first: RunContext = RunContext::new(RunConfig::new("first-harness-run"), ());
- let next: RunContext = RunContext::new(RunConfig::new("next-harness-run"), ());
- let args = json!({"action":"learn","text":"Prefers tea"});
- let mut ids = HashSet::new();
- for i in 0..9 {
- let context =
- ToolExecutionContext::from_run_context(&first, CallId::new(format!("call-{i}")));
- let result = tool
- .execute_with_context(args.clone(), ToolCallOptions::default(), Some(&context))
- .await
- .unwrap();
- assert_eq!(result.is_error, i == 8);
- if !result.is_error {
- let value: Value = serde_json::from_str(&result.text()).unwrap();
- ids.insert(value["id"].as_str().unwrap().to_string());
- }
- }
- assert_eq!(
- ids.len(),
- 1,
- "invocation IDs must not create duplicate learnings"
- );
- let context = ToolExecutionContext::from_run_context(&next, CallId::new("next-call"));
- let result = tool
- .execute_with_context(args, ToolCallOptions::default(), Some(&context))
- .await
- .unwrap();
- assert!(!result.is_error, "a new harness run gets a fresh budget");
- super::super::tool_writes::drain(&config).await;
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 1);
-}
-
#[test]
fn schema_and_permissions_follow_the_action() {
let tool = MemoryTool::new(Arc::new(Config::default()));
diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.md
index d5a4e58c70..9d0faddec3 100644
--- a/docs/RELEASE-MANUAL-SMOKE.md
+++ b/docs/RELEASE-MANUAL-SMOKE.md
@@ -32,6 +32,15 @@ Applies to every release, all platforms.
- [ ] **A failed chat turn does not offer an invalid regenerate action** — Trigger a provider failure in a test profile and inspect its error card. Expected: the diagnostic text remains visible, with no Retry or Refresh button on that failed message. A completed assistant reply still offers Refresh (#6613).
- [ ] **A failed turn leaves its thread usable** — In a test profile, get one successful reply, trigger a streamed provider failure on the next turn, then send another message in the same thread. Expected: the error card appears, the composer re-enables, the next reply streams normally, and the agent still has the first turn's context. If a queued follow-up starts as the failed turn ends, its stream and composer state stay active.
+### Memory latency and queued writes (coverage 8.1 / 8.2)
+
+Use a disposable staging account/workspace and synthetic facts. Keep inference reachable while delaying or blocking only the memory endpoint.
+
+- [ ] **Automatic memory does not stall a chat or compaction** — Start a fresh conversation while memory reads take at least 60 seconds, then send another turn and trigger transcript compaction in a long test thread. Expected: inference and compaction proceed while memory refresh remains pending; an unavailable or expired pack is omitted. After restoring memory, a later turn can use the completed scoped pack. A different thread or account must not receive that context.
+- [ ] **Learn and forget acknowledge local queueing** — Ask the agent to learn a unique synthetic fact while memory writes are delayed, then forget its returned item ID. Expected: each tool result says queued without waiting for remote acceptance; the agent continues the requested work and does not claim the fact was saved or removed remotely. Quit after queue acknowledgement, relaunch and restore memory. Expected: retry processes learn before forget and the forgotten fact does not reappear. Repeat with memory explicitly disabled: new writes are refused and earlier pending writes remain unsent until re-enabled.
+- [ ] **Explicit recall/fetch stay bounded** — With memory reads blocked, ask the agent to use recall or fetch. Expected: a call stops waiting after at most 15 seconds, repeated optional memory calls share a 30-second/8-attempt budget while that run record remains tracked, and the agent continues without memory. Idle records can be evicted under heavy run churn. A new chat turn receives a fresh budget; inference/provider latency is measured separately.
+- [ ] **Erase all retires earlier queued learnings** — Queue a synthetic learning during a memory outage, then restore access and use Erase all with confirmation. Expected: the current mutation settles before erasure, older pending learnings are discarded, and none are replayed after restart. Queue a new learning after erasure and repeat Erase all in the same app process; it must also be removed. Verify another staging account's queued facts remain isolated.
+
### Refreshed application UI
- [ ] **Settings, Connections, theme, and workflow surfaces remain usable** — On desktop, navigate between Settings sections and Connections tabs, switch between light/dark and at least one named theme family, export and re-import a custom theme, then open a workflow canvas and its run history. Expected: each route renders its own content without stale panels or horizontal overflow; imported themes can be selected and theme selection and run details survive a reload where persistence is expected.
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 167ad79e01..363841d903 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -355,20 +355,21 @@ Spec: `docs/specs/memory-v2.md` (host) and `vendor/tinymemory/docs/specs/memory-
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | -------------------------------- | ----- | ------------ | ------ | ----- |
-| 8.1.1 | Learn / store a learning | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tools_tests.rs`, `tests/memory_v2_e2e.rs` (`learn_list_fetch_recall_and_forget_round_trip`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | `memory` tool `learn` action and `openhuman.memory_learn` |
-| 8.1.2 | Recall (answer with citations) | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Ask chip |
-| 8.1.3 | Fetch and list | RU+RI | `crates/openhuman-core/src/memory/ops_tests.rs`, `tests/memory_v2_e2e.rs` | ✅ | Hybrid only on both launch engines; other modes answer `UNSUPPORTED` |
-| 8.1.4 | Forget | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | By id |
-| 8.1.5 | Agent `memory` tool | RU | `crates/openhuman-core/src/memory/tools_tests.rs` | ✅ | Actions `recall`, `fetch`, `learn`, `forget`; not registered when memory is off |
+| 8.1.1 | Learn / store a learning | RU+RI+WD | `crates/openhuman-core/src/memory/ops_tests.rs`, `crates/openhuman-core/src/memory/tools_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `tests/memory_v2_e2e.rs` (`learn_list_fetch_recall_and_forget_round_trip`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Agent `learn` returns a durable local queued acknowledgement without awaiting the engine; explicit `openhuman.memory_learn` retains its RPC contract. Held-engine, scrub-before-persist, atomic owner-only storage, capacity, persistence failure, restart replay and invocation-ID deduplication regressions cover the outbox |
+| 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.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
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | ---------------------------------------- | ----- | ------------ | ------ | ----- |
| 8.2.1 | Engine list, select, status; memory off | RU+RI+WD | `crates/openhuman-core/src/memory/engine_tests.rs`, `crates/openhuman-core/src/memory/status_tests.rs`, `crates/openhuman-core/src/memory/error_tests.rs`, `tests/memory_v2_e2e.rs` (`memory_is_off_when_signed_out`, `signing_in_turns_memory_on`, `engines_list_get_and_set`, `engine_failures_surface_as_structured_errors`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | TinyHumans and CortexDB |
-| 8.2.2 | Per-account isolation | RI | `tests/memory_v2_e2e.rs` (`memory_is_isolated_per_account`) | ✅ | |
-| 8.2.3 | Turn logging and per-turn memory pack | RU+RI | `crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs`, `crates/openhuman-core/src/memory/lifecycle/mod_tests.rs`, `crates/openhuman-core/src/memory/bus_tests.rs`, `tests/memory_v2_e2e.rs` (`a_chat_turn_carries_its_pack_and_is_logged`) | ✅ | Pack is ephemeral (`<memory-context>`); tool results are one line, no arguments |
-| 8.2.4 | Background jobs (belief builds) | RU+RI | `crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs`, `tests/memory_v2_e2e.rs` (`brain_pack_preview_and_jobs_round_trip`) | ✅ | `memory_background` cron, every 5 minutes |
+| 8.2.2 | Per-account isolation | RU+RI | `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs`, `tests/memory_v2_e2e.rs` (`memory_is_isolated_per_account`) | ✅ | Shared-workspace outboxes and mutation barriers isolate owners; cached packs isolate identity, config, thread, workspace and core context. Credential changes reject late in-flight results |
+| 8.2.3 | Turn logging and per-turn memory pack | RU+RI | `crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs`, `crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs`, `crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs`, `crates/openhuman-core/src/memory/lifecycle/mod_tests.rs`, `crates/openhuman-core/src/memory/bus_tests.rs`, `tests/memory_v2_e2e.rs` (`a_chat_turn_carries_its_pack_and_is_logged`) | ✅ | Chat and transcript compaction consume only completed, scoped packs; refresh, turn logging, date extraction and compaction recall run in background. Held-engine and slow-refresh regressions prove these hooks do not delay inference or compaction. Packs expire after 60 seconds, are bounded, and stay ephemeral (`<memory-context>`); tool results are one line, no arguments |
+| 8.2.4 | Background jobs (belief builds) | RU+RI | `crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs`, `crates/openhuman-core/src/memory/tool_writes_tests.rs`, `tests/memory_v2_e2e.rs` (`brain_pack_preview_and_jobs_round_trip`) | ✅ | `memory_background` cron, every 5 minutes; tool-write outboxes drain immediately and retry on credential/cron events after restart. Failures retain the FIFO head; background mutation deadlines allow up to 120 seconds without holding a chat turn |
| 8.2.5 | Document sources: add, sync, list, remove | RU+RI+WD | `crates/openhuman-core/src/memory/sources/sync_tests.rs`, `crates/openhuman-core/src/memory/sources/mod_tests.rs`, `tests/memory_v2_e2e.rs` (`sources_add_sync_list_and_remove`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | folder, file, link, github, rss |
| 8.2.6 | Folder-source path picker | RU+VU | `crates/openhuman-app/src/directory_picker.rs`, `app/src/utils/tauriCommands/directoryPicker.test.ts` | ✅ | |
| 8.2.7 | Pack preview (Ask tab) and brain views | RU+RI+WD | `crates/openhuman-core/src/memory/lifecycle/views_tests.rs`, `crates/openhuman-core/src/memory/brain_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | No `context.md`; pack never persisted in the transcript |
diff --git a/docs/specs/memory-v2.md b/docs/specs/memory-v2.md
index 9f48823388..c3f97512cc 100644
--- a/docs/specs/memory-v2.md
+++ b/docs/specs/memory-v2.md
@@ -92,10 +92,10 @@ credential.
| Hook | Where | What |
| --- | --- | --- |
-| pre-turn | session host `before_turn` (`agent/session_host/runtime_session/memory_ingest.rs`), concurrently with request enrichment | `AgentMemory::pre_turn`: logs the user turn (accepted, not indexed) and recalls the turn's pack, under `[memory.recall] pre_turn_timeout_ms` |
+| pre-turn | session host `before_turn` (`agent/session_host/runtime_session/memory_ingest.rs`) | `lifecycle::prefetch::pre_turn` takes a completed cached pack immediately, or none on a cold cache, and queues scoped `AgentMemory::pre_turn` logging and recall |
| inject | `MemoryPackMiddleware` (`agent/tinyagents/middleware/memory_pack.rs`) | adds the pack, wrapped in `<memory-context>`, to every model request of the turn with `push_ephemeral_instruction` |
-| post-turn | session host, after the durable commit | `AgentMemory::post_turn`: logs the reply with its tool calls (name, id, and a one-line result per call), queues the belief build it hands back |
-| compaction | `MemoryRecallSummarizer` (`agent/tinyagents/memory_summarizer.rs`) wrapping the turn's summarizer | `AgentMemory::recall_for_compaction` over the dropped turns, concurrently with the summary; appended to the checkpoint under "Recalled from memory" |
+| post-turn | scoped background work after the durable commit | `AgentMemory::post_turn`: logs the reply with its tool calls (name, id, and a one-line result per call), queues the belief build it hands back |
+| compaction | `MemoryRecallSummarizer` (`agent/tinyagents/memory_summarizer.rs`) wrapping the turn's summarizer | Takes completed cached context for "Recalled from memory" and queues `AgentMemory::recall_for_compaction`; engine I/O never delays the inner summarizer |
| session start | pre-turn, on the first turn of a session resumed after a compaction | `AgentMemory::start_session`: the thread's own earlier turns lead the pack |
- **Turn indices** follow the committed transcript: the user message after
@@ -105,11 +105,16 @@ credential.
the thread's persisted history and the provider's cached prefix are exactly
as they were. The window of the thread still verbatim in the prompt (from
the turn after the last compaction checkpoint) is left out of the pack.
-- **No hook fails a turn.** Each is bounded and logs instead of raising; a
- timed-out pre-turn still finishes logging in the background.
+- **Automatic hooks never await remote memory on a live turn.** Scoped
+ workers handle user logging, date hints and context refresh with bounded
+ queues and deadlines. Cached packs expire after 60 seconds and identify
+ themselves as results of an earlier lookup. A cold cache supplies none.
+ The explicit/manual hooks retain configured pre-turn/compaction deadlines.
+- **No hook fails a turn.** An unavailable engine or a saturated background
+ queue degrades best-effort memory without holding up the model or summary.
- **A refused recall is not an empty one.** When nothing was recalled because
the engine refused the account (`INSUFFICIENT_CREDITS`, `UNAUTHORIZED`,
- `UNAVAILABLE`), the turn is given a short notice saying memory is
+ `UNAVAILABLE`), the completed pack is a short notice saying memory is
unavailable and why, so the model does not tell the user nothing is stored.
TinyMemory's holistic recall reports a section's failure as a skip reason,
so the hook reads the refusal back from there too.
@@ -217,14 +222,26 @@ CortexDB refuses for it is written again without it (tinymemory's fallback). Off
One tool, `action` = `recall` | `fetch` | `learn` | `forget`:
- `recall { question, filter? }` → `{answer, citations[]}`.
- `fetch { query, mode?, filter?, limit? }` → `{hits[]}`; `mode` limited to the engine's `fetch_modes`.
-- `learn { text, kind?, confidence? }` → `{id}`. The host fills `meta`: the
+- `learn { text, kind?, confidence? }` → `{id, status: "queued; not yet saved to memory"}`. The host fills `meta`: the
layout's learnings node, `workspace`, `thread_id`, `agent_id` (the memory
agent id), `tool_call`, `source.kind = "agent"`.
-- `forget { ids }` → `{forgotten}`.
+- `forget { ids }` → `{queued, status: "queued; not yet removed from memory"}`.
Every read and `forget` is confined to the identity's layout (its root's
subtree); a `reach` in the model's filter is overwritten.
+Agent writes are admitted to a private durable outbox after validation,
+confinement and scrubbing; the acknowledgement confirms local acceptance, not
+remote completion. Background delivery resolves credentials at drain time,
+retries under the matching owner, and does not block the model. Explicit RPC
+and UI operations retain their direct, confirmed engine behavior.
+
+The agent tool bounds each call to 15 seconds and reserves from 30 seconds of
+aggregate time and eight attempts per retained run record. The tracker keeps
+128 records; idle eviction can reset a same-run record under churn, but cannot
+evict outstanding reservations. A timeout tells the model to continue without
+retrying memory in that run; a timed-out write admission may already be durable.
+
## RPC (`openhuman.memory_*`)
Errors use the standard structured error; `code` is one of `MEMORY_OFF`,
diff --git a/gitbooks/developing/architecture/memory.md b/gitbooks/developing/architecture/memory.md
index b6e9085df4..3bb1d0caba 100644
--- a/gitbooks/developing/architecture/memory.md
+++ b/gitbooks/developing/architecture/memory.md
@@ -7,7 +7,7 @@ icon: diagram-project
# Memory
-`crates/openhuman-core/src/memory/` is the host layer over TinyMemory. It runs the agent memory lifecycle around every turn. A memory pack is recalled before the model runs, the turn is logged on both sides, memory is recalled into compaction checkpoints, and belief builds run in the background.
+`crates/openhuman-core/src/memory/` is the host layer over TinyMemory. It runs the agent memory lifecycle around every turn. The prelude takes completed cached context immediately and queues user logging and refresh; committed replies are logged in the background. Compaction uses completed context and queues its own refresh without delaying the authoritative summarizer. Belief builds also run in the background.
The behavior is specified in [`docs/specs/memory-v2.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/specs/memory-v2.md). The user-facing feature is [Memory](../../features/memory.md).
@@ -26,7 +26,8 @@ The behavior is specified in [`docs/specs/memory-v2.md`](https://github.com/tiny
| `engine` | Binds `[memory] engine`: `tinyhumans` over the host's backend credential (resolved per request) with the transport's attribution headers, or `cortexdb` with the key stored as `memory-cortexdb`. Off when neither is usable. |
| `guard` | `ScrubbingEngine`: every write is scrubbed under the host policy, whichever path makes it. |
| `scope` | `MemoryIdentity` scoped around every turn, resolved to a layout root and a memory agent id (host binding, definition pin, team, default). |
-| `lifecycle::hooks` | `pre_turn`, `post_turn`, `compaction`: bounded, never fail a turn. |
+| `lifecycle::prefetch` | Scoped, bounded in-memory cache and background workers for automatic turn and compaction recall. |
+| `lifecycle::hooks` | Lifecycle primitives; explicit/manual `pre_turn` and `compaction` retain configured deadlines. |
| `lifecycle::jobs` | The persisted background queue and the `memory_background` cron job. |
| `lifecycle::views` | Policy, pack preview, agents list, job views for the RPCs. |
| `brain` | Brain source mapping for synced items and the `memory_brain_*` ops. |
@@ -34,7 +35,7 @@ The behavior is specified in [`docs/specs/memory-v2.md`](https://github.com/tiny
| `channels` | Which channel each logged thread arrived on, for forgetting a channel. |
| `backfill` | Consent-gated storing of past chats in the lifecycle's shape. |
| `import` | Consent-gated, resumable v1 import. |
-| `tools` | The single `memory` agent tool (`recall`, `fetch`, `learn`, `forget`), confined to the identity's layout. |
+| `tools`, `tool_budget`, `tool_writes` | The scoped agent tool: bounded explicit reads and durable local admission of `learn`/`forget`, followed by background delivery. |
| `ops`, `explore` | Engine selection, recall, fetch, learn, forget, listing, the explorer. |
| `bus` | The cron subscriber (`memory_sources_sync`, `memory_background`). |
| `schemas` | The `openhuman.memory_*` controllers. |
@@ -44,10 +45,16 @@ The behavior is specified in [`docs/specs/memory-v2.md`](https://github.com/tiny
| Hook | File |
| --- | --- |
-| Pre-turn (log + recall), first turn after a compaction also `start_session` | `agent/session_host/runtime_session/memory_ingest.rs`, from `before_turn` in `runtime_session.rs` |
+| Pre-turn (take cached pack, queue logging and refresh) | `agent/session_host/runtime_session/memory_ingest.rs`, from `before_turn` in `runtime_session.rs` |
| Pack injection, ephemeral, every model request of the turn | `agent/tinyagents/middleware/memory_pack.rs` |
| Post-turn (log the reply, queue builds), after the durable commit | `memory_ingest.rs`, from `finalize_after_durable_commit` |
-| Compaction recall into the checkpoint | `agent/tinyagents/memory_summarizer.rs`, wrapped around the summarizer in `harness_context_ladder.rs` |
+| Compaction enrichment from completed cache, with background refresh | `agent/tinyagents/memory_summarizer.rs`, wrapped around the summarizer in `harness_context_ladder.rs` |
+
+Automatic packs are keyed by CoreContext, workspace, config fingerprint, resolved memory identity and thread. They expire after 60 seconds. The cache holds at most 64 entries per context and 64 KiB per pack; eight workers globally process bounded queues of at most 16 pending operations per entry, with a 120-second deadline per operation. Saturation skips best-effort automatic work rather than waiting. Packs identify themselves as results of an earlier lookup, not authoritative answers to the current question.
+
+Successful content changes clear cached packs and advance a revision, preserving queued conversation logs while rejecting older in-flight results. Engine or credential invalidation clears the caches and pending refreshes. Scoped background tasks retain both CoreContext and memory identity.
+
+The agent tool allows 15 seconds per call, 30 seconds of aggregate reserved time and eight attempts per retained run record. The tracker keeps 128 records; idle eviction under churn can reset the budget for that run, while outstanding reservations cannot be evicted. `learn`/`forget` acknowledge durable local admission, not remote completion. Their scrubbed outbox entries contain trusted scope rather than credentials, and retry under the matching owner on background/auth ticks. Direct RPC, UI and import/deletion workflows keep their explicit behavior.
The turn's `MemoryTurn` (config, identity, thread, pack) rides
`OpenHumanRunContext::memory_turn`; a child run has its own.
diff --git a/gitbooks/features/memory.md b/gitbooks/features/memory.md
index 3c0fd42912..9755482e09 100644
--- a/gitbooks/features/memory.md
+++ b/gitbooks/features/memory.md
@@ -1,7 +1,7 @@
---
description: >-
Memory: a pluggable engine that stores your documents, conversations and
- learnings, recalls what matters before every turn, and answers questions
+ learnings, refreshes context in the background, and answers questions
with citations.
icon: brain
---
@@ -16,9 +16,9 @@ Open it from **Connections > Memory**. It has eight tabs: Engine, Ask, Explorer,
Memory works around every turn, and the agent does not have to ask for it.
-- **Before the model answers**, OpenHuman logs what you said and recalls a short *memory pack* for the turn, sized to a token budget. The pack holds relevant learnings (and beliefs the engine built from them), documents from your brain, this agent's earlier conversations and, briefly, other agents' conversations. The pack is added to the model request for that turn only. It is never written into the chat, so your conversation stays exactly as you had it.
-- **After the answer**, the reply is logged with a one-line result for each tool it used.
-- **When a long chat is compacted**, OpenHuman recalls what the folded-away turns covered and adds it to the summary that replaces them.
+- **Before the model answers**, OpenHuman takes a completed *memory pack* from its short-lived cache, when one is available, and starts logging your message and refreshing memory in the background. The first turn can have no pack. A cached pack can hold learnings, beliefs, documents and earlier conversations from a previous lookup; it is labelled as cached context, so the agent can use explicit recall when it needs a current answer. The pack is added to requests for that turn only and never written into the chat.
+- **After the answer**, the reply is logged in the background with a one-line result for each tool it used.
+- **When a long chat is compacted**, OpenHuman can add completed cached memory to the summary and starts refreshing recall of the folded-away turns. Memory reads never hold up the summary.
- **In the background**, every few minutes, the engine builds beliefs from what was stored, such as "the user prefers short answers" or "deploys happen on Fridays".
Memory chips on an answer show which stored items the pack cited. To see what a turn would get, open **Ask > Pack preview**.
@@ -32,7 +32,7 @@ An engine stores your memory and answers questions about it. There are two.
| TinyHumans | Hosted CortexDB run by TinyHumans, reached through the TinyHumans backend | You are signed in, or the host supplies a TinyHumans API key (headless and library hosts) |
| CortexDB | Your own CortexDB, called directly (managed `api-v1.cortexdb.ai` or self-hosted) | A CortexDB API key (kept in the OS keychain), and an endpoint if it is not the managed one |
-With either engine your memory items live in CortexDB, not on your computer. OpenHuman keeps only bookkeeping locally, such as queued jobs and sync progress. See [Where your memory is stored](privacy-and-security.md#where-your-memory-is-stored).
+With either engine, committed memory items live in CortexDB. OpenHuman also keeps scrubbed pending agent writes in a private local queue until they are delivered, plus job and sync bookkeeping. Cached packs stay in process memory for a short time. See [Where your memory is stored](privacy-and-security.md#where-your-memory-is-stored).
Pick an engine on the **Engine** tab. If you are signed out and have neither a CortexDB key nor a host-supplied TinyHumans API key, memory is off. The agent has no memory tool, nothing is stored, and the Memory page tells you why.
@@ -62,11 +62,11 @@ Sources sync when you press sync and on a schedule you set for each source. An u
### Conversations
-Every turn is logged as it happens: your message before the model runs, and the reply after. Each agent's turns are kept apart. Tool calls are stored by name and id with a one-line result, never their arguments. You can switch turn logging off on the **Conversations** tab, which also lists each agent's stored turns.
+Turn logging runs in the background: your message is queued before the model runs, and the reply after it commits. A slow or unavailable memory engine does not delay the answer. Each agent's turns are kept apart. Tool calls are stored by name and id with a one-line result, never their arguments. You can switch turn logging off on the **Conversations** tab, which also lists each agent's stored turns.
### Learnings
-A learning is one lasting statement: a preference, fact, procedure or correction. The agent saves them with its `memory` tool (the `learn` action), and you can add or delete them on the **Learnings** tab. Beliefs the engine built are listed there too, marked "Built belief".
+A learning is one lasting statement: a preference, fact, procedure or correction. The agent queues them with its `memory` tool (the `learn` action), and you can add or delete them on the **Learnings** tab. A tool acknowledgement saying "queued; not yet saved to memory" confirms local acceptance, not a completed save by the engine. Beliefs the engine built are listed there too, marked "Built belief".
Everything is scrubbed for secrets and personal identifiers before it leaves your machine.
@@ -94,7 +94,7 @@ A host that runs OpenHuman agents as part of something larger, such as an AI com
## The agent's memory tool
-The agent has one tool, `memory`, with four actions: `recall`, `fetch`, `learn` and `forget`. OpenHuman's own [MCP server](../developing/mcp-server.md) offers the same abilities to other apps as `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn` and `memory.forget`.
+The agent has one tool, `memory`, with four actions: `recall`, `fetch`, `learn` and `forget`. Explicit reads have a deadline and a shared budget for the current run; when memory is too slow, the agent gets an error and continues without retrying it in that run. Agent `learn` and `forget` requests are queued locally and delivered in the background, so their acknowledgements do not confirm a remote save or deletion. OpenHuman's own [MCP server](../developing/mcp-server.md) offers the same abilities to other apps as `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn` and `memory.forget`.
## Settings and background work
diff --git a/gitbooks/features/native-tools/memory-tools.md b/gitbooks/features/native-tools/memory-tools.md
index 7fe5326cc3..b35535060c 100644
--- a/gitbooks/features/native-tools/memory-tools.md
+++ b/gitbooks/features/native-tools/memory-tools.md
@@ -11,16 +11,24 @@ icon: brain
| --- | --- |
| `recall` | Ask a question. Returns an answer and the citations it rests on. |
| `fetch` | Raw hybrid search over stored items, optionally filtered by metadata. Returns hits. |
-| `learn` | Save one durable learning: a preference, fact, procedure or correction. |
-| `forget` | Remove items by id. |
+| `learn` | Queue one durable learning: a preference, fact, procedure or correction. |
+| `forget` | Queue removal of items by id. |
The tool is registered only when a memory engine is usable. With none selected, memory is off and the agent never sees the tool. Every learning is shared with all agents under the same memory root. It is tagged with the workspace, thread, agent and tool call that produced it.
## The tool and the per-turn pack
-Every turn already arrives with a small [memory pack](../memory.md#how-the-agent-uses-memory) (`<memory-context>`). It holds the learnings, documents and history most relevant to what you just said.
+A turn can receive a completed cached [memory pack](../memory.md#how-the-agent-uses-memory) (`<memory-context>`). A cold cache supplies none. The pack is labelled as context from an earlier background lookup and can be incomplete or unrelated to the current question. Automatic refresh and turn logging never wait on the remote engine before the model runs.
-Use the tool to go further than the pack. The agent can ask a question the pack does not cover ("what do I know about the Stripe webhook?"), search with metadata filters, or save something worth remembering next time.
+Use explicit `recall` or `fetch` when a current answer is needed, or to go further than the pack. The agent can ask a question the pack does not cover ("what do I know about the Stripe webhook?"), search with metadata filters, or save something worth remembering next time.
+
+## Deadlines and queued writes
+
+Agent memory calls have a 15-second per-call deadline, a shared 30-second budget and at most eight attempts per tracked run. Concurrent calls reserve from the same budget. If a read times out or the budget is exhausted, the tool tells the agent to continue without memory and not retry it in that run. A new run has a fresh budget.
+
+`learn` and `forget` persist a validated, scrubbed request in a private local outbox and start background delivery. The statuses "queued; not yet saved to memory" and "queued; not yet removed from memory" confirm local acceptance only. The agent must not describe them as completed remote saves or deletions, or repeat them to force indexing. Pending delivery can resume after a restart, sign-in or background tick. Queue admission can fail when its limits are reached.
+
+These agent-tool limits do not replace the behavior of explicit Memory-page or RPC workflows.
External MCP clients get the same abilities from OpenHuman's [MCP server](../../developing/mcp-server.md) as `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn` and `memory.forget`.
diff --git a/gitbooks/features/privacy-and-security.md b/gitbooks/features/privacy-and-security.md
index f7b7d4100e..9a3381b7d4 100644
--- a/gitbooks/features/privacy-and-security.md
+++ b/gitbooks/features/privacy-and-security.md
@@ -25,8 +25,8 @@ Your workspace files, settings and audio buffers stay on your machine. Your memo
| Item | Where it lives |
| --- | --- |
-| Memory items | Not local with hosted memory. They are stored in CortexDB by your selected engine (see below). A CortexDB you host on your own machine keeps them there. |
-| Memory bookkeeping | Local: the job queue and sync, backfill and import progress under `<workspace>/memory/`, the sources list in `config.toml`, and a CortexDB key in the OS keychain. No memory content. |
+| Committed memory items | Stored in CortexDB by your selected engine (see below). A CortexDB you host on your own machine keeps them there. Pending agent writes are held locally until delivery. |
+| Memory bookkeeping and pending writes | Local: scrubbed agent `learn`/`forget` requests await delivery in a private outbox under `<workspace>/memory/`, alongside job queues and sync, backfill and import progress. Sources are listed in `config.toml`; the CortexDB key is kept in the OS keychain. Automatic context packs stay in process memory briefly. |
| Audio capture buffers | Local. Discarded after speech-to-text. |
| Local model state | Local. |