Skip to content

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

fix(memory): handle empty conversation buffer on read

Steven Enamakel4466c48f000e
diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rs
index eaa1c29512..fdc6ddb378 100644
--- a/crates/openhuman-core/src/memory/bus.rs
+++ b/crates/openhuman-core/src/memory/bus.rs
@@ -50,6 +50,7 @@ pub fn committed_turn(event: &DomainEvent) -> Option<CommittedTurn> {
Some(CommittedTurn {
thread_id: thread_id.clone(),
agent_id: agent_id.clone(),
+ namespace: tinymemory::Namespace::ROOT,
workspace: workspace.clone(),
channel: channel.clone(),
user: user_text.clone(),
@@ -169,10 +170,22 @@ pub fn register_memory_subscribers() {
let mut ticker = tokio::time::interval(IDLE_SWEEP_INTERVAL);
loop {
ticker.tick().await;
- if let Ok(config) = crate::config::rpc::load_config_with_timeout().await {
+ // Every workspace with buffered turns, each with its own
+ // config, so an agent with its own workspace is flushed too.
+ for workspace in super::conversations::buffered_workspaces() {
+ let loaded =
+ crate::config::rpc::load_config_for_workspace_with_timeout(&workspace)
+ .await;
+ let Ok(config) = loaded else {
+ continue;
+ };
let flushed = super::conversations::flush_idle(&config, Utc::now()).await;
if flushed > 0 {
- tracing::debug!(flushed, "[memory:bus] idle threads stored");
+ tracing::debug!(
+ flushed,
+ workspace = %workspace.display(),
+ "[memory:bus] idle threads stored"
+ );
}
}
}
diff --git a/crates/openhuman-core/src/memory/conversations/buffer.rs b/crates/openhuman-core/src/memory/conversations/buffer.rs
index 230ebded29..634a2dbf11 100644
--- a/crates/openhuman-core/src/memory/conversations/buffer.rs
+++ b/crates/openhuman-core/src/memory/conversations/buffer.rs
@@ -10,7 +10,7 @@ use std::collections::HashMap;
use chrono::{DateTime, Duration, Utc};
use tinymemory::{
- MemoryMeta, Role, SourceKind, SourceRef, StoreItem, ToolCallRef, Turn, TurnRange,
+ MemoryMeta, Namespace, Role, SourceKind, SourceRef, StoreItem, ToolCallRef, Turn, TurnRange,
};
/// One committed exchange: the user's message and the assistant's reply.
@@ -20,6 +20,8 @@ pub struct CommittedTurn {
pub thread_id: String,
/// The agent that answered.
pub agent_id: Option<String>,
+ /// The memory node of the agent that answered.
+ pub namespace: Namespace,
/// The agent's working folder.
pub workspace: Option<String>,
/// The channel the turn arrived on.
@@ -40,7 +42,8 @@ pub fn channel_tag(channel: &str) -> String {
format!("channel:{}", channel.to_ascii_lowercase())
}
-/// Turns of one thread ready to be stored as one `Conversation` item.
+/// Turns of one thread, answered by one agent, ready to be stored as one
+/// `Conversation` item.
#[derive(Debug, Clone, PartialEq)]
pub struct Batch {
/// The thread.
@@ -61,8 +64,8 @@ impl Batch {
/// The `Conversation` item this batch stores.
///
/// Meta carries `thread_id`, `agent_id` and `workspace` (from the latest
- /// turn that has them), `turns`, a `channel:<name>` tag, and
- /// `source = conversation:<thread_id>`.
+ /// turn that has them), the answering agent's `namespace`, `turns`, a
+ /// `channel:<name>` tag, and `source = conversation:<thread_id>`.
/// Tool calls ride on each assistant turn by name and id; arguments never
/// enter the item.
#[must_use]
@@ -79,6 +82,11 @@ impl Batch {
.rev()
.find_map(|turn| turn.workspace.clone());
let observed_at = self.turns.last().map(|turn| turn.at);
+ let namespace = self
+ .turns
+ .last()
+ .map(|turn| turn.namespace.clone())
+ .unwrap_or_default();
let tags: Vec<String> = self
.turns
.iter()
@@ -113,6 +121,7 @@ impl Batch {
StoreItem::Conversation {
turns,
meta: MemoryMeta {
+ namespace,
workspace,
thread_id: Some(self.thread_id.clone()),
turns: Some(TurnRange {
@@ -146,10 +155,22 @@ pub struct ConversationBuffer {
}
impl ConversationBuffer {
- /// Adds `turn` as turn number `index` of its thread. Returns the thread's
- /// batch when it now holds `batch_turns` turns.
- pub fn push(&mut self, turn: CommittedTurn, index: u32, batch_turns: u32) -> Option<Batch> {
+ /// Adds `turn` as turn number `index` of its thread. Returns the batches
+ /// that are ready: the thread's pending turns when a different agent
+ /// (namespace) answered them, so a batch never mixes two agents' memory,
+ /// and the thread's batch once it holds `batch_turns` turns.
+ pub fn push(&mut self, turn: CommittedTurn, index: u32, batch_turns: u32) -> Vec<Batch> {
let thread_id = turn.thread_id.clone();
+ let mut ready = Vec::new();
+ let switched = self.threads.get(&thread_id).is_some_and(|pending| {
+ pending
+ .turns
+ .last()
+ .is_some_and(|last| last.namespace != turn.namespace)
+ });
+ if switched {
+ ready.extend(self.take(&thread_id));
+ }
let pending = self.threads.entry(thread_id.clone()).or_default();
if pending.turns.is_empty() {
pending.first = index;
@@ -157,9 +178,9 @@ impl ConversationBuffer {
pending.last_activity = Some(turn.at);
pending.turns.push(turn);
if pending.turns.len() >= batch_turns.max(1) as usize {
- return self.take(&thread_id);
+ ready.extend(self.take(&thread_id));
}
- None
+ ready
}
/// Removes and returns every thread idle for at least `idle_secs` at `now`.
diff --git a/crates/openhuman-core/src/memory/conversations/mod.rs b/crates/openhuman-core/src/memory/conversations/mod.rs
index bb43c15232..2d6657b6b4 100644
--- a/crates/openhuman-core/src/memory/conversations/mod.rs
+++ b/crates/openhuman-core/src/memory/conversations/mod.rs
@@ -164,7 +164,7 @@ pub fn recent(workspace_dir: &Path) -> Vec<RecentConversation> {
/// Buffers one committed turn, storing its thread's batch when full.
///
/// A no-op when conversations are disabled or memory is off.
-pub async fn record_turn(config: &Config, turn: CommittedTurn) {
+pub async fn record_turn(config: &Config, mut turn: CommittedTurn) {
let settings = &config.memory.conversations;
if !settings.enabled {
tracing::trace!("[memory:conversations] disabled; turn dropped");
@@ -174,6 +174,10 @@ pub async fn record_turn(config: &Config, turn: CommittedTurn) {
tracing::trace!("[memory:conversations] memory off; turn dropped");
return;
}
+ // The answering agent's node; the main chat agent's is the root.
+ if let Some(agent_id) = turn.agent_id.as_deref() {
+ turn.namespace = crate::memory::scope::namespace_for(config, agent_id, None);
+ }
let index = next_turn_index(&config.workspace_dir, &turn.thread_id, turn.at);
let ready = {
let mut buffers = BUFFERS
@@ -184,11 +188,23 @@ pub async fn record_turn(config: &Config, turn: CommittedTurn) {
.or_default()
.push(turn, index, settings.batch_turns)
};
- if let Some(batch) = ready {
+ for batch in ready {
store_batch(config, batch).await;
}
}
+/// Every workspace with buffered turns: the idle flusher visits each, not
+/// only the default profile's.
+#[must_use]
+pub fn buffered_workspaces() -> Vec<std::path::PathBuf> {
+ BUFFERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .keys()
+ .cloned()
+ .collect()
+}
+
/// Stores every thread idle for `idle_secs` at `now`.
pub async fn flush_idle(config: &Config, now: DateTime<Utc>) -> usize {
let ready = {