Skip to content

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

chore: files changed crates/openhuman-core/src/memory/context.rs,crates/openhuman-core/src/memory/co

Steven Enamakelc4c85ba919c0
diff --git a/crates/openhuman-core/src/memory/conversations/backfill_tests.rs b/crates/openhuman-core/src/memory/backfill_tests.rs
similarity index 67%
rename from crates/openhuman-core/src/memory/conversations/backfill_tests.rs
rename to crates/openhuman-core/src/memory/backfill_tests.rs
index d80bbedac3..7912b4babd 100644
--- a/crates/openhuman-core/src/memory/conversations/backfill_tests.rs
+++ b/crates/openhuman-core/src/memory/backfill_tests.rs
@@ -4,7 +4,6 @@ use std::time::Duration;
use tinymemory_api::{ItemKind, MetaFilter};
-use crate::memory::conversations;
use crate::memory::error::{INVALID_REQUEST, MEMORY_OFF};
use crate::memory::test_fixtures::{bind_reference, config_in, stored};
use crate::threads::store::CreateConversationThread;
@@ -71,7 +70,7 @@ fn messages_become_turns_like_the_chat_shows_them() {
message("4", "user", " ", "2026-09-01T10:03:00Z"),
message("5", "user", "Bali in October", "not a time"),
];
- let turns = turns_of("t", &messages);
+ let turns = turns_of(&messages);
assert_eq!(turns.len(), 3);
assert_eq!(turns[0].user, "");
assert_eq!(turns[0].assistant, "Welcome!");
@@ -83,39 +82,34 @@ fn messages_become_turns_like_the_chat_shows_them() {
}
#[test]
-fn the_range_leaves_live_turns_and_stored_turns_alone() {
- assert_eq!(pending_range(10, 0, 0), 0..10);
- assert_eq!(pending_range(10, 3, 0), 0..7, "the 3 newest are live's");
- assert_eq!(pending_range(10, 3, 4), 4..7);
- assert_eq!(pending_range(10, 3, 9), 7..7, "nothing left");
- assert_eq!(pending_range(2, 5, 0), 0..0, "live took more than exist");
+fn the_range_stops_where_live_logging_began() {
+ assert_eq!(pending_range(10, None, 0), 0..10);
+ assert_eq!(pending_range(10, Some(7), 0), 0..7, "turns 7.. are live's");
+ assert_eq!(pending_range(10, Some(7), 4), 4..7);
+ assert_eq!(pending_range(10, Some(7), 9), 7..7, "nothing left");
+ assert_eq!(pending_range(2, Some(5), 0), 0..2);
}
#[test]
-fn batches_cut_the_range_by_batch_turns() {
- let turns = turns_of(
- "t",
- &(0..5)
- .map(|i| {
- message(
- &i.to_string(),
- "user",
- &format!("q{i}"),
- "2026-09-01T10:00:00Z",
- )
- })
- .collect::<Vec<_>>(),
- );
- let cut = batches("t", &turns, 1..5, 3);
- assert_eq!(cut.len(), 2);
- assert_eq!((cut[0].first, cut[0].last()), (1, 3));
- assert_eq!((cut[1].first, cut[1].last()), (4, 4));
- assert!(batches("t", &turns, 2..2, 3).is_empty());
- assert_eq!(
- batches("t", &turns, 0..5, 0).len(),
- 5,
- "zero means one per item"
- );
+fn a_turn_is_one_item_per_message_at_the_agents_node() {
+ let config = Config::default();
+ let identity = MemoryIdentity::agent(MAIN_AGENT).resolve(&config);
+ let turn = PastTurn {
+ user: "q".into(),
+ assistant: "a".into(),
+ at: Utc::now(),
+ };
+ let items = turn_items(&identity, "t", 3, &turn);
+ assert_eq!(items.len(), 2);
+ let meta = items[1].meta();
+ assert_eq!(meta.turns.map(|range| range.first), Some(7));
+ assert_eq!(meta.namespace.to_string(), "agent:orchestrator");
+ assert!(meta.tags.iter().any(|tag| tag == BACKFILL_TAG));
+ let reply_only = PastTurn {
+ user: String::new(),
+ ..turn
+ };
+ assert_eq!(turn_items(&identity, "t", 0, &reply_only).len(), 1);
}
#[tokio::test]
@@ -133,10 +127,9 @@ async fn refuses_without_consent_and_with_memory_off() {
}
#[tokio::test]
-async fn stores_past_chats_once_and_skips_what_live_ingestion_took() {
+async fn stores_past_chats_once_and_skips_what_live_logging_took() {
let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 2;
+ let config = config_in(&tmp);
let engine = bind_reference(&config);
let workspace = config.workspace_dir.clone();
@@ -148,8 +141,6 @@ async fn stores_past_chats_once_and_skips_what_live_ingestion_took() {
("agent", "Values have one owner."),
("user", "And borrowing?"),
("agent", "References without ownership."),
- ("user", "Thanks"),
- ("agent", "Any time."),
],
)
.await;
@@ -157,33 +148,32 @@ async fn stores_past_chats_once_and_skips_what_live_ingestion_took() {
&workspace,
"live-thread",
&[
- ("user", "Before ingestion"),
+ ("user", "Before logging"),
("agent", "An old answer."),
- ("user", "After ingestion"),
+ ("user", "After logging"),
("agent", "A live answer."),
],
)
.await;
- // Live ingestion took live-thread's last turn.
- conversations::record_turn(
+ // The lifecycle logged live-thread's second turn (user index 2).
+ let identity = MemoryIdentity::agent(MAIN_AGENT).resolve(&config);
+ crate::memory::lifecycle::hooks::pre_turn(
&config,
- conversations::buffer::CommittedTurn {
+ &identity,
+ crate::memory::lifecycle::hooks::PreTurnInput {
thread_id: "live-thread".into(),
- agent_id: None,
- namespace: tinymemory_api::Namespace::ROOT,
- workspace: None,
- channel: None,
- user: "After ingestion".into(),
- assistant: "A live answer.".into(),
- tool_calls: Vec::new(),
+ turn_index: 2,
+ user_text: "After logging".into(),
+ in_prompt_from: 0,
at: Utc::now(),
+ resumed_after_compaction: false,
},
)
.await;
let before = status(&config).await.unwrap();
assert_eq!(before.state.phase, ImportPhase::Idle);
- assert_eq!((before.pending_threads, before.pending_turns), (2, 4));
+ assert_eq!((before.pending_threads, before.pending_turns), (2, 3));
let started = start(&config, BackfillStartParams { consent: true })
.await
@@ -191,11 +181,8 @@ async fn stores_past_chats_once_and_skips_what_live_ingestion_took() {
assert_eq!(started.state.threads_total, 2);
let done = wait_done(&config).await;
assert_eq!(done.state.phase, ImportPhase::Done, "{:?}", done.state);
- assert_eq!(done.state.turns_stored, 4);
- assert_eq!(
- done.state.items_stored, 3,
- "old-thread in two batches, live-thread in one"
- );
+ assert_eq!(done.state.turns_stored, 3);
+ assert_eq!(done.state.items_stored, 6);
assert!(done.state.finished_at.is_some());
assert_eq!((done.pending_threads, done.pending_turns), (0, 0));
@@ -205,15 +192,9 @@ async fn stores_past_chats_once_and_skips_what_live_ingestion_took() {
..MetaFilter::default()
};
let items = stored(&engine, filter.clone()).await;
- assert_eq!(items.len(), 3);
- let live: Vec<_> = items
- .iter()
- .filter(|hit| hit.meta.thread_id.as_deref() == Some("live-thread"))
- .collect();
- assert_eq!(live.len(), 1);
- assert!(live[0].text.contains("Before ingestion"));
+ assert_eq!(items.len(), 6);
assert!(
- !live[0].text.contains("After ingestion"),
+ !items.iter().any(|hit| hit.text.contains("After logging")),
"live's turn is not re-stored"
);
@@ -223,5 +204,5 @@ async fn stores_past_chats_once_and_skips_what_live_ingestion_took() {
.unwrap();
let again = wait_done(&config).await;
assert_eq!(again.state.items_stored, 0);
- assert_eq!(stored(&engine, filter).await.len(), 3);
+ assert_eq!(stored(&engine, filter).await.len(), 6);
}
diff --git a/crates/openhuman-core/src/memory/context.rs b/crates/openhuman-core/src/memory/context.rs
deleted file mode 100644
index a9dfdcb987..0000000000
--- a/crates/openhuman-core/src/memory/context.rs
+++ /dev/null
@@ -1,376 +0,0 @@
-//! `context.md`: the compiled memory brief, one per memory node, and its
-//! injection.
-//!
-//! [`refresh_for`] compiles a brief for one node from the bound engine with
-//! `tinymemory-context` (four default briefs plus recent learnings, trimmed to
-//! `[memory.context] budget_tokens`), reading only that node's reach — its own
-//! memory and the nodes it inherits — and writes it beside a
-//! `context_state.json` holding its timestamp and token count:
-//!
-//! - the root (the main agent, shared by everyone): `<workspace>/memory/context.md`;
-//! - any other node: `<workspace>/memory/context/<kind>-<id>/…/context.md`,
-//! one directory per segment (`context/agent-researcher/context.md`).
-//!
-//! The `memory_context_refresh` cron job refreshes the root and every node
-//! that has a document or a `[memory.agents.<id>]` entry ([`refresh_all`]);
-//! `memory_context_refresh` refreshes one node on demand.
-//!
-//! [`injection_block`] is what the session host prepends to the first user
-//! message of a **new** session, wrapped in `<memory-context>…</memory-context>`:
-//! the acting agent's own document ([`super::scope::current`]), or, until
-//! that is first compiled (which it then starts in the background), the
-//! nearest ancestor's. A resumed session never gets it again: its transcript
-//! is frozen.
-
-use std::path::{Path, PathBuf};
-
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
-use tinymemory_tools::context::{Brief, ContextCompiler, ContextSpec, DEFAULT_LEARNINGS_LIMIT};
-use tinymemory_api::{Namespace, Reach, Segment, SegmentKind};
-
-use crate::config::Config;
-
-use super::engine;
-use super::error::{MemoryError, MemoryResult};
-use super::types::{ContextSetParams, ContextView};
-
-/// Fewest minutes between scheduled recompiles.
-pub const MIN_INTERVAL_MINS: u32 = 5;
-
-/// Smallest token budget.
-pub const MIN_BUDGET_TOKENS: u32 = 100;
-
-/// Largest token budget.
-pub const MAX_BUDGET_TOKENS: u32 = 32_000;
-
-/// Opening tag of the injected block.
-pub const OPEN_TAG: &str = "<memory-context>";
-
-/// Closing tag of the injected block.
-pub const CLOSE_TAG: &str = "</memory-context>";
-
-#[derive(Debug, Default, Serialize, Deserialize)]
-struct ContextState {
- generated_at: Option<DateTime<Utc>>,
- tokens: usize,
-}
-
-fn memory_dir(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("memory")
-}
-
-/// The directory holding every non-root node's document.
-fn nodes_dir(workspace_dir: &Path) -> PathBuf {
- memory_dir(workspace_dir).join("context")
-}
-
-/// The directory `namespace`'s document lives in.
-fn node_dir(workspace_dir: &Path, namespace: &Namespace) -> PathBuf {
- if namespace.is_root() {
- return memory_dir(workspace_dir);
- }
- let mut dir = nodes_dir(workspace_dir);
- for segment in namespace.segments() {
- dir.push(format!("{}-{}", segment.kind().as_str(), segment.id()));
- }
- dir
-}
-
-/// Where the root's `context.md` lives.
-#[must_use]
-pub fn context_path(workspace_dir: &Path) -> PathBuf {
- context_path_for(workspace_dir, &Namespace::ROOT)
-}
-
-/// Where `namespace`'s `context.md` lives.
-#[must_use]
-pub fn context_path_for(workspace_dir: &Path, namespace: &Namespace) -> PathBuf {
- node_dir(workspace_dir, namespace).join("context.md")
-}
-
-fn state_path(workspace_dir: &Path, namespace: &Namespace) -> PathBuf {
- node_dir(workspace_dir, namespace).join("context_state.json")
-}
-
-fn read_state(workspace_dir: &Path, namespace: &Namespace) -> ContextState {
- std::fs::read_to_string(state_path(workspace_dir, namespace))
- .ok()
- .and_then(|text| serde_json::from_str(&text).ok())
- .unwrap_or_default()
-}
-
-fn read_markdown(workspace_dir: &Path, namespace: &Namespace) -> String {
- std::fs::read_to_string(context_path_for(workspace_dir, namespace)).unwrap_or_default()
-}
-
-/// `memory_context_get` for the root.
-#[must_use]
-pub fn view(config: &Config) -> ContextView {
- view_for(config, &Namespace::ROOT)
-}
-
-/// `memory_context_get` for `namespace`.
-#[must_use]
-pub fn view_for(config: &Config, namespace: &Namespace) -> ContextView {
- let state = read_state(&config.workspace_dir, namespace);
- let settings = &config.memory.context;
- ContextView {
- namespace: namespace.to_string(),
- markdown: read_markdown(&config.workspace_dir, namespace),
- tokens: state.tokens,
- generated_at: state.generated_at,
- interval_mins: settings.interval_mins,
- budget_tokens: settings.budget_tokens,
- enabled: settings.enabled,
- }
-}
-
-/// Every node with a compiled document, root first.
-#[must_use]
-pub fn compiled_nodes(workspace_dir: &Path) -> Vec<Namespace> {
- let mut found = vec![Namespace::ROOT];
- collect_nodes(&nodes_dir(workspace_dir), &Namespace::ROOT, &mut found);
- found
-}
-
-fn collect_nodes(dir: &Path, parent: &Namespace, found: &mut Vec<Namespace>) {
- let Ok(entries) = std::fs::read_dir(dir) else {
- return;
- };
- let mut children: Vec<(Namespace, PathBuf)> = entries
- .flatten()
- .filter(|entry| entry.path().is_dir())
- .filter_map(|entry| {
- let name = entry.file_name().to_string_lossy().to_string();
- let (kind, id) = name.split_once('-')?;
- let kind = SegmentKind::ALL.into_iter().find(|k| k.as_str() == kind)?;
- let node = parent.child(Segment::new(kind, id).ok()?).ok()?;
- Some((node, entry.path()))
- })
- .collect();
- children.sort();
- for (node, path) in children {
- if path.join("context.md").is_file() {
- found.push(node.clone());
- }
- collect_nodes(&path, &node, found);
- }
-}
-
-/// The spec compiled for the root.
-#[must_use]
-pub fn spec_for(config: &Config) -> ContextSpec {
- spec_for_node(config, &Namespace::ROOT)
-}
-
-/// The spec compiled for `namespace`: the node's own memory and the nodes it
-/// inherits.
-#[must_use]
-pub fn spec_for_node(config: &Config, namespace: &Namespace) -> ContextSpec {
- ContextSpec {
- budget_tokens: config.memory.context.budget_tokens.max(MIN_BUDGET_TOKENS) as usize,
- briefs: Brief::defaults(),
- learnings_limit: DEFAULT_LEARNINGS_LIMIT,
- reach: Some(Reach::of(namespace.clone())),
- }
-}
-
-/// Compiles the root's `context.md` from the bound engine and writes it.
-pub async fn refresh(config: &Config) -> MemoryResult<ContextView> {
- refresh_for(config, &Namespace::ROOT).await
-}
-
-/// Compiles `namespace`'s `context.md` from the bound engine and writes it.
-pub async fn refresh_for(config: &Config, namespace: &Namespace) -> MemoryResult<ContextView> {
- let bound = engine::resolve(config).engine()?;
- refresh_node_with(config, namespace, &*bound.engine, ContextCompiler::new()).await
-}
-
-/// Refreshes the root and every node with a document or a configured agent,
-/// skipping agents whose context is off. Returns how many were compiled.
-pub async fn refresh_all(config: &Config) -> usize {
- let mut nodes = compiled_nodes(&config.workspace_dir);
- for (agent_id, settings) in &config.memory.agents {
- let node = super::scope::namespace_for(config, agent_id, None);
- if settings.context != Some(false) && !nodes.contains(&node) {
- nodes.push(node);
- }
- }
- let mut compiled = 0;
- for node in nodes {
- match refresh_for(config, &node).await {
- Ok(_) => compiled += 1,
- Err(error) => {
- tracing::debug!(namespace = %node, code = error.code(), "[memory:context] refresh skipped");
- }
- }
- }
- compiled
-}
-
-/// [`refresh`] against an explicit engine and compiler.
-pub async fn refresh_with(
- config: &Config,
- engine: &dyn tinymemory_api::MemoryEngine,
- compiler: ContextCompiler,
-) -> MemoryResult<ContextView> {
- refresh_node_with(config, &Namespace::ROOT, engine, compiler).await
-}
-
-/// [`refresh_for`] against an explicit engine and compiler.
-pub async fn refresh_node_with(
- config: &Config,
- namespace: &Namespace,
- engine: &dyn tinymemory_api::MemoryEngine,
- compiler: ContextCompiler,
-) -> MemoryResult<ContextView> {
- let doc = compiler
- .compile(engine, &spec_for_node(config, namespace))
- .await
- .map_err(|error| MemoryError::invalid(error.to_string()))?;
- let dir = node_dir(&config.workspace_dir, namespace);
- let state = ContextState {
- generated_at: Some(doc.generated_at),
- tokens: doc.tokens,
- };
- let write = std::fs::create_dir_all(&dir)
- .and_then(|()| {
- std::fs::write(
- context_path_for(&config.workspace_dir, namespace),
- &doc.markdown,
- )
- })
- .and_then(|()| {
- let json = serde_json::to_vec_pretty(&state).map_err(std::io::Error::other)?;
- std::fs::write(state_path(&config.workspace_dir, namespace), json)
- });
- write.map_err(|error| MemoryError::Engine(format!("writing context.md failed: {error}")))?;
- tracing::info!(
- engine = %doc.engine,
- namespace = %namespace,
- tokens = doc.tokens,
- refs = doc.refs.len(),
- "[memory:context] context.md compiled"
- );
- Ok(view_for(config, namespace))
-}
-
-/// Applies `memory_context_set` to `config`; the caller persists it.
-pub fn apply_set(config: &mut Config, params: &ContextSetParams) -> MemoryResult<()> {
- let settings = &mut config.memory.context;
- if let Some(interval) = params.interval_mins {
- if interval < MIN_INTERVAL_MINS {
- return Err(MemoryError::invalid(format!(
- "interval_mins must be at least {MIN_INTERVAL_MINS}"
- )));
- }
- settings.interval_mins = interval;
- }
- if let Some(budget) = params.budget_tokens {
- if !(MIN_BUDGET_TOKENS..=MAX_BUDGET_TOKENS).contains(&budget) {
- return Err(MemoryError::invalid(format!(
- "budget_tokens must be between {MIN_BUDGET_TOKENS} and {MAX_BUDGET_TOKENS}"
- )));
- }
- settings.budget_tokens = budget;
- }
- if let Some(enabled) = params.enabled {
- settings.enabled = enabled;
- }
- Ok(())
-}
-
-/// Strips a leading `---` frontmatter block.
-fn strip_frontmatter(markdown: &str) -> &str {
- let Some(rest) = markdown.strip_prefix("---\n") else {
- return markdown;
- };
- match rest.find("\n---\n") {
- Some(end) => &rest[end + "\n---\n".len()..],
- None => markdown,
- }
-}
-
-/// Whether the acting agent gets a compiled context: `[memory.context]
-/// enabled`, overridden by `[memory.agents.<id>] context`.
-fn context_enabled(config: &Config, agent_id: Option<&str>) -> bool {
- agent_id
- .and_then(|id| config.memory.agents.get(id))
- .and_then(|settings| settings.context)
- .unwrap_or(config.memory.context.enabled)
-}
-
-/// The block a new session's first user message is prefixed with, or `None`
-/// when context is disabled, memory is off, or there is nothing compiled.
-///
-/// The document is the acting agent's ([`super::scope::current`]; the root's
-/// outside any agent). A node without one yet falls back to its nearest
-/// ancestor's and has its own compiled in the background, for its next
-/// session.
-#[must_use]
-pub fn injection_block(config: &Config) -> Option<String> {
- let identity = super::scope::current().unwrap_or_else(super::scope::MemoryIdentity::root);
- if !context_enabled(config, identity.agent_id.as_deref()) {
- return None;
- }
- if !engine::is_on(config) {
- tracing::debug!("[memory:context] memory off; no context injected");
- return None;
- }
- let own = &identity.namespace(config);
- let inherit = identity.inherit(config);
- if !own.is_root() && !context_path_for(&config.workspace_dir, own).is_file() {
- compile_in_background(config, own);
- }
- let mut node = Some(own.clone());
- let markdown = loop {
- let Some(current) = node else {
- break String::new();
- };
- let markdown = read_markdown(&config.workspace_dir, &current);
- if !markdown.trim().is_empty() || !inherit {
- break markdown;
- }
- node = current.parent();
- };
- let body = strip_frontmatter(&markdown).trim();
- if body.is_empty() {
- return None;
- }
- tracing::debug!(
- namespace = %own,
- chars = body.len(),
- "[memory:context] context.md injected"
- );
- Some(format!("{OPEN_TAG}\n{body}\n{CLOSE_TAG}"))
-}
-
-/// Starts compiling `namespace`'s first document, when a runtime is there.
-fn compile_in_background(config: &Config, namespace: &Namespace) {
- let Ok(handle) = tokio::runtime::Handle::try_current() else {
- return;
- };
- let config = config.clone();
- let namespace = namespace.clone();
- tracing::debug!(namespace = %namespace, "[memory:context] compiling a first context.md");
- handle.spawn(async move {
- if let Err(error) = refresh_for(&config, &namespace).await {
- tracing::debug!(namespace = %namespace, code = error.code(), "[memory:context] first compile skipped");
- }
- });
-}
-
-/// Prepends [`injection_block`] (when there is one) to a new session's first
-/// user message.
-#[must_use]
-pub fn prepend_to_first_message(config: &Config, message: &str) -> String {
- match injection_block(config) {
- Some(block) => format!("{block}\n\n{message}"),
- None => message.to_string(),
- }
-}
-
-#[cfg(test)]
-#[path = "context_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/context_tests.rs b/crates/openhuman-core/src/memory/context_tests.rs
deleted file mode 100644
index 28a2f09a41..0000000000
--- a/crates/openhuman-core/src/memory/context_tests.rs
+++ /dev/null
@@ -1,251 +0,0 @@
-use super::*;
-use crate::memory::ops::learn;
-use crate::memory::test_fixtures::{bind_reference, config_in};
-use crate::memory::types::LearnParams;
-use tinymemory_api::LearningKind;
-
-fn params(text: &str, kind: LearningKind) -> LearnParams {
- LearnParams {
- text: text.to_string(),
- kind: Some(kind),
- confidence: Some(0.9),
- meta: None,
- }
-}
-
-#[test]
-fn view_of_a_fresh_workspace_is_empty_with_the_configured_settings() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- let view = view(&config);
- assert!(view.markdown.is_empty());
- assert_eq!(view.tokens, 0);
- assert!(view.generated_at.is_none());
- assert_eq!(view.interval_mins, config.memory.context.interval_mins);
- assert_eq!(view.budget_tokens, config.memory.context.budget_tokens);
- assert!(view.enabled);
-}
-
-#[tokio::test]
-async fn refresh_without_an_engine_reports_memory_off() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- let error = refresh(&config).await.unwrap_err();
- assert_eq!(error.code(), crate::memory::error::MEMORY_OFF);
- assert!(!context_path(&config.workspace_dir).exists());
-}
-
-#[tokio::test]
-async fn refresh_writes_context_md_and_state() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- bind_reference(&config);
- learn(
- &config,
- params("The user prefers terse answers", LearningKind::Preference),
- None,
- )
- .await
- .unwrap();
-
- let view = refresh(&config).await.unwrap();
- let path = config.workspace_dir.join("memory").join("context.md");
- assert_eq!(context_path(&config.workspace_dir), path);
- let on_disk = std::fs::read_to_string(&path).expect("context.md written");
- assert_eq!(view.markdown, on_disk);
- assert!(view.generated_at.is_some());
- assert!(view.tokens > 0);
- assert!(state_path(&config.workspace_dir, &Namespace::ROOT).exists());
-}
-
-#[test]
-fn injection_block_wraps_the_body_and_strips_frontmatter() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- crate::memory::test_fixtures::bind_reference(&config);
- std::fs::create_dir_all(config.workspace_dir.join("memory")).unwrap();
- std::fs::write(
- context_path(&config.workspace_dir),
- "---\ngenerated: now\n---\n\n# Brief\n\nLikes tea.\n",
- )
- .unwrap();
- let block = injection_block(&config).expect("a block");
- assert!(block.starts_with(OPEN_TAG));
- assert!(block.ends_with(CLOSE_TAG));
- assert!(block.contains("Likes tea."));
- assert!(!block.contains("generated: now"));
- assert!(!block.contains("---"));
-
- let message = prepend_to_first_message(&config, "hello");
- assert!(message.starts_with(OPEN_TAG));
- assert!(message.ends_with("\n\nhello"));
-}
-
-#[test]
-fn injection_block_is_none_when_disabled_off_or_empty() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
-
- // Memory off, even with a document on disk.
- std::fs::create_dir_all(config.workspace_dir.join("memory")).unwrap();
- std::fs::write(context_path(&config.workspace_dir), "Likes tea.").unwrap();
- assert!(injection_block(&config).is_none());
- assert_eq!(prepend_to_first_message(&config, "hello"), "hello");
-
- // On, but nothing compiled yet.
- let tmp2 = tempfile::tempdir().unwrap();
- let config2 = config_in(&tmp2);
- bind_reference(&config2);
- assert!(injection_block(&config2).is_none());
-
- // On, but only frontmatter and whitespace.
- std::fs::create_dir_all(config2.workspace_dir.join("memory")).unwrap();
- std::fs::write(context_path(&config2.workspace_dir), "---\na: b\n---\n \n").unwrap();
- assert!(injection_block(&config2).is_none());
-
- // On with content, but disabled by config.
- bind_reference(&config);
- assert!(injection_block(&config).is_some());
- config.memory.context.enabled = false;
- assert!(injection_block(&config).is_none());
-}
-
-#[test]
-fn an_unterminated_frontmatter_is_left_alone() {
- assert_eq!(strip_frontmatter("---\nno end"), "---\nno end");
- assert_eq!(strip_frontmatter("plain"), "plain");
- assert_eq!(strip_frontmatter("---\na: 1\n---\nbody"), "body");
-}
-
-#[test]
-fn apply_set_validates_bounds_and_applies_fields() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
-
- for bad in [
- ContextSetParams {
- interval_mins: Some(MIN_INTERVAL_MINS - 1),
- ..ContextSetParams::default()
- },
- ContextSetParams {
- budget_tokens: Some(MIN_BUDGET_TOKENS - 1),
- ..ContextSetParams::default()
- },
- ContextSetParams {
- budget_tokens: Some(MAX_BUDGET_TOKENS + 1),
- ..ContextSetParams::default()
- },
- ] {
- let error = apply_set(&mut config, &bad).unwrap_err();
- assert_eq!(error.code(), crate::memory::error::INVALID_REQUEST);
- }
-
- apply_set(
- &mut config,
- &ContextSetParams {
- enabled: Some(false),
- interval_mins: Some(MIN_INTERVAL_MINS),
- budget_tokens: Some(MAX_BUDGET_TOKENS),
- },
- )
- .unwrap();
- let settings = &config.memory.context;
- assert!(!settings.enabled);
- assert_eq!(settings.interval_mins, MIN_INTERVAL_MINS);
- assert_eq!(settings.budget_tokens, MAX_BUDGET_TOKENS);
-}
-
-#[test]
-fn spec_for_never_goes_below_the_minimum_budget() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.context.budget_tokens = 1;
- assert_eq!(spec_for(&config).budget_tokens, MIN_BUDGET_TOKENS as usize);
-}
-
-fn as_agent(agent: &str) -> tinymemory_api::MemoryMeta {
- tinymemory_api::MemoryMeta {
- namespace: Namespace::agent(agent),
- agent_id: Some(agent.to_string()),
- ..tinymemory_api::MemoryMeta::default()
- }
-}
-
-#[tokio::test]
-async fn each_agent_gets_its_own_context_md_from_its_reach() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.agents.insert(
- "planner".into(),
- crate::config::schema::MemoryAgentConfig::default(),
- );
- bind_reference(&config);
- let researcher = Namespace::agent("researcher");
- for (text, meta) in [
- ("The user is called Sam", None),
- ("Prefer arxiv for papers", Some(as_agent("researcher"))),
- ("Draft in British English", Some(as_agent("writer"))),
- ] {
- learn(&config, params(text, LearningKind::Preference), meta)
- .await
- .unwrap();
- }
-
- let view = refresh_for(&config, &researcher).await.unwrap();
- assert_eq!(view.namespace, "agent:researcher");
- assert!(view.markdown.contains("arxiv"), "{}", view.markdown);
- assert!(view.markdown.contains("Sam"), "the root is inherited");
- assert!(
- !view.markdown.contains("British"),
- "a sibling is out of reach"
- );
- let path = context_path_for(&config.workspace_dir, &researcher);
- assert!(path.ends_with("memory/context/agent-researcher/context.md"));
- assert!(path.is_file());
- assert_eq!(
- compiled_nodes(&config.workspace_dir),
- vec![Namespace::ROOT, researcher.clone()]
- );
-
- // The cron job compiles the root, every compiled node and every
- // configured agent.
- assert_eq!(refresh_all(&config).await, 3);
- assert!(context_path_for(&config.workspace_dir, &Namespace::agent("planner")).is_file());
-
- let injected = crate::memory::scope::within_agent("researcher", async {
- injection_block(&config).unwrap()
- })
- .await;
- assert!(injected.contains("arxiv"));
- let main = injection_block(&config).unwrap();
- assert!(!main.contains("arxiv"), "the root's document is the root's");
-}
-
-#[tokio::test]
-async fn an_agent_without_a_document_falls_back_to_its_ancestor_s() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- bind_reference(&config);
- learn(
- &config,
- params("The user is called Sam", LearningKind::Fact),
- None,
- )
- .await
- .unwrap();
- refresh(&config).await.unwrap();
- let injected =
- crate::memory::scope::within_agent("scout", async { injection_block(&config) }).await;
- assert!(injected.unwrap().contains("Sam"));
-
- config.memory.agents.insert(
- "quiet".into(),
- crate::config::schema::MemoryAgentConfig {
- context: Some(false),
- ..Default::default()
- },
- );
- let none =
- crate::memory::scope::within_agent("quiet", async { injection_block(&config) }).await;
- assert!(none.is_none(), "an agent can switch its context off");
-}
diff --git a/crates/openhuman-core/src/memory/conversations/backfill.rs b/crates/openhuman-core/src/memory/conversations/backfill.rs
deleted file mode 100644
index 8559169591..0000000000
--- a/crates/openhuman-core/src/memory/conversations/backfill.rs
+++ /dev/null
@@ -1,397 +0,0 @@
-//! Storing past chats: conversations that predate automatic ingestion.
-//!
-//! Live ingestion ([`super::record_turn`]) only sees turns committed while it
-//! is on. This walks the thread store instead and stores every earlier turn
-//! of every thread, in the same `batch_turns` batches and with the same
-//! metadata live ingestion uses ([`Batch::into_item`]), plus a
-//! [`BACKFILL_TAG`] so they can be told apart.
-//!
-//! - **Turns.** A thread's messages become turns the way the chat shows them:
-//! each user message opens a turn and the replies after it, up to the next
-//! user message, are its answer. Replies before any user message form a turn
-//! with no user side.
-//! - **No overlap with live ingestion.** Live ingestion counts the turns it has
-//! taken per thread (the counter in `conversations_state.json`); those are
-//! the thread's most recent turns, so the backfill stops short of them.
-//! - **Resumable and repeatable.** How far each thread has been stored is kept
-//! in `<workspace>/memory/conversations_backfill.json`, so an interrupted run
-//! resumes and a later run sends only what is new. A re-sent batch is a
-//! replay (the item id is a content digest), never a duplicate.
-//! - **Consent.** It uploads chat history to the selected engine, so
-//! [`start`] refuses without `consent`.
-
-use std::collections::{BTreeMap, HashSet};
-use std::path::{Path, PathBuf};
-use std::sync::{LazyLock, Mutex};
-
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
-
-use crate::config::Config;
-use crate::memory::engine::{self, BoundEngine};
-use crate::memory::error::{MemoryError, MemoryResult};
-use crate::memory::ops::store_many_on;
-use crate::memory::types::ImportPhase;
-use crate::threads::store::blocking as threads;
-use crate::threads::store::ConversationMessage;
-
-use super::buffer::{Batch, CommittedTurn};
-
-/// The tag every backfilled conversation carries.
-pub const BACKFILL_TAG: &str = "backfill";
-
-/// Conversation items per bulk store (`MemoryEngine::store_many`).
-const STORE_GROUP: usize = 25;
-
-/// Backfills running now, per workspace.
-static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
-
-/// Progress of the last (or current) backfill.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct BackfillState {
- /// Idle, running, done, or stopped on an error.
- pub phase: ImportPhase,
- /// Threads with turns to store when the run started.
- pub threads_total: u64,
- /// Of those, threads finished.
- pub threads_done: u64,
- /// Turns stored by the run.
- pub turns_stored: u64,
- /// Conversation items stored by the run.
- pub items_stored: u64,
- /// Why it stopped, when it failed.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- /// When the last run finished.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub finished_at: Option<DateTime<Utc>>,
-}
-
-/// `memory_conversations_backfill_status` / `_start` result.
-#[derive(Debug, Clone, Serialize)]
-pub struct BackfillView {
- /// The run's progress.
- pub state: BackfillState,
- /// Threads that still have earlier turns to store.
- pub pending_threads: u64,
- /// Turns still to store across them.
- pub pending_turns: u64,
-}
-
-/// `memory_conversations_backfill_start` params.
-#[derive(Debug, Clone, Default, Deserialize)]
-pub struct BackfillStartParams {
- /// The caller agrees to upload past chats to the engine.
- #[serde(default)]
- pub consent: bool,
-}
-
-#[derive(Debug, Default, Serialize, Deserialize)]
-struct BackfillFile {
- #[serde(default)]
- state: BackfillState,
- /// Turns stored so far, per thread.
- #[serde(default)]
- stored: BTreeMap<String, u32>,
-}
-
-fn file_path(workspace_dir: &Path) -> PathBuf {
- workspace_dir
- .join("memory")
- .join("conversations_backfill.json")
-}
-
-fn read_file(workspace_dir: &Path) -> BackfillFile {
- std::fs::read_to_string(file_path(workspace_dir))
- .ok()
- .and_then(|text| serde_json::from_str(&text).ok())
- .unwrap_or_default()
-}
-
-fn write_file(workspace_dir: &Path, file: &BackfillFile) {
- let path = file_path(workspace_dir);
- let result = path
- .parent()
- .map_or(Ok(()), std::fs::create_dir_all)
- .and_then(|()| {
- let json = serde_json::to_vec_pretty(file).map_err(std::io::Error::other)?;
- std::fs::write(&path, json)
- });
- if let Err(error) = result {
- tracing::warn!(error = %error, "[memory:backfill] writing state failed");
- }
-}
-
-fn parse_time(raw: &str) -> Option<DateTime<Utc>> {
- DateTime::parse_from_rfc3339(raw)
- .ok()
- .map(|at| at.with_timezone(&Utc))
-}
-
-/// A thread's messages as turns, oldest first.
-#[must_use]
-pub fn turns_of(thread_id: &str, messages: &[ConversationMessage]) -> Vec<CommittedTurn> {
- let mut turns: Vec<CommittedTurn> = Vec::new();
- for message in messages {
- let text = message.content.trim();
- if text.is_empty() {
- continue;
- }
- let at = parse_time(&message.created_at);
- if message.sender.eq_ignore_ascii_case("user") {
- turns.push(CommittedTurn {
- thread_id: thread_id.to_string(),
- agent_id: None,
- // Past chats are the main agent's: the shared root.
- namespace: tinymemory_api::Namespace::ROOT,
- workspace: None,
- channel: None,
- user: text.to_string(),
- assistant: String::new(),
- tool_calls: Vec::new(),
- at: at.unwrap_or_else(Utc::now),
- });
- continue;
- }
- let needs_turn = turns.is_empty();
- if needs_turn {
- turns.push(CommittedTurn {
- thread_id: thread_id.to_string(),
- agent_id: None,
- // Past chats are the main agent's: the shared root.
- namespace: tinymemory_api::Namespace::ROOT,
- workspace: None,
- channel: None,
- user: String::new(),
- assistant: String::new(),
- tool_calls: Vec::new(),
- at: at.unwrap_or_else(Utc::now),
- });
- }
- if let Some(turn) = turns.last_mut() {
- if !turn.assistant.is_empty() {
- turn.assistant.push_str("\n\n");
- }
- turn.assistant.push_str(text);
- if let Some(at) = at {
- turn.at = at;
- }
- }
- }
- turns
-}
-
-/// Which turns of a thread with `total` turns the backfill should store:
-/// from what it already stored up to (not including) the ones live
-/// ingestion took.
-#[must_use]
-pub fn pending_range(total: usize, live_taken: u32, already_stored: u32) -> std::ops::Range<usize> {
- let end = total.saturating_sub(live_taken as usize);
- let start = (already_stored as usize).min(end);
- start..end
-}
-
-/// The batches storing `turns[range]`, `batch_turns` per item, tagged.
-#[must_use]
-pub fn batches(
- thread_id: &str,
- turns: &[CommittedTurn],
- range: std::ops::Range<usize>,
- batch_turns: u32,
-) -> Vec<Batch> {
- let size = batch_turns.max(1) as usize;
- let mut out = Vec::new();
- let mut first = range.start;
- while first < range.end {
- let end = (first + size).min(range.end);
- out.push(Batch {
- thread_id: thread_id.to_string(),
- first: u32::try_from(first).unwrap_or(u32::MAX),
- turns: turns[first..end].to_vec(),
- });
- first = end;
- }
- out
-}
-
-/// One thread's plan: its turns and the range still to store.
-struct ThreadPlan {
- thread_id: String,
- turns: Vec<CommittedTurn>,
- range: std::ops::Range<usize>,
-}
-
-async fn plan(
- workspace_dir: &Path,
- stored: &BTreeMap<String, u32>,
-) -> MemoryResult<Vec<ThreadPlan>> {
- let listed = threads::list_threads(workspace_dir.to_path_buf())
- .await
- .map_err(|error| MemoryError::Engine(format!("reading chat threads failed: {error}")))?;
- let mut plans = Vec::new();
- for thread in listed {
- let messages = match threads::get_messages(workspace_dir.to_path_buf(), thread.id.clone())
- .await
- {
- Ok(messages) => messages,
- Err(error) => {
- tracing::warn!(error = %error, "[memory:backfill] a thread was unreadable; skipped");
- continue;
- }
- };
- let turns = turns_of(&thread.id, &messages);
- let range = pending_range(
- turns.len(),
- super::live_turns_taken(workspace_dir, &thread.id),
- stored.get(&thread.id).copied().unwrap_or(0),
- );
- if !range.is_empty() {
- plans.push(ThreadPlan {
- thread_id: thread.id,
- turns,
- range,
- });
- }
- }
- Ok(plans)
-}
-
-fn is_running(workspace_dir: &Path) -> bool {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(workspace_dir)
-}
-
-/// `memory_conversations_backfill_status`.
-pub async fn status(config: &Config) -> MemoryResult<BackfillView> {
- let workspace_dir = &config.workspace_dir;
- let file = read_file(workspace_dir);
- let mut state = file.state;
- if state.phase == ImportPhase::Running && !is_running(workspace_dir) {
- state.phase = ImportPhase::Error;
- state.error = Some("the sync was interrupted; start it again to resume".to_string());
- }
- let plans = plan(workspace_dir, &file.stored).await?;
- Ok(BackfillView {
- state,
- pending_threads: plans.len() as u64,
- pending_turns: plans.iter().map(|p| p.range.len() as u64).sum(),
- })
-}
-
-/// `memory_conversations_backfill_start`: requires `consent` and memory on.
-pub async fn start(config: &Config, params: BackfillStartParams) -> MemoryResult<BackfillView> {
- if !params.consent {
- return Err(MemoryError::invalid(
- "storing past chats uploads them to the selected engine; pass consent: true",
- ));
- }
- let bound = engine::resolve(config).engine()?;
- let workspace_dir = config.workspace_dir.clone();
- let claimed = RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(workspace_dir.clone());
- if !claimed {
- return status(config).await;
- }
- let mut file = read_file(&workspace_dir);
- let plans = match plan(&workspace_dir, &file.stored).await {
- Ok(plans) => plans,
- Err(error) => {
- release(&workspace_dir);
- return Err(error);
- }
- };
- let pending_turns: u64 = plans.iter().map(|p| p.range.len() as u64).sum();
- file.state = BackfillState {
- phase: ImportPhase::Running,
- threads_total: plans.len() as u64,
- ..BackfillState::default()
- };
- write_file(&workspace_dir, &file);
- let view = BackfillView {
- state: file.state.clone(),
- pending_threads: plans.len() as u64,
- pending_turns,
- };
- tracing::info!(
- threads = plans.len(),
- turns = pending_turns,
- "[memory:backfill] started"
- );
- let batch_turns = config.memory.conversations.batch_turns;
- tokio::spawn(async move {
- run(&workspace_dir, &bound, file, plans, batch_turns).await;
- release(&workspace_dir);
- });
- Ok(view)
-}
-
-fn release(workspace_dir: &Path) {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .remove(workspace_dir);
-}
-
-async fn run(
- workspace_dir: &Path,
- bound: &BoundEngine,
- mut file: BackfillFile,
- plans: Vec<ThreadPlan>,
- batch_turns: u32,
-) {
- for plan in plans {
- let cut = batches(
- &plan.thread_id,
- &plan.turns,
- plan.range.clone(),
- batch_turns,
- );
- for group in cut.chunks(STORE_GROUP) {
- let turns: u64 = group.iter().map(|batch| batch.turns.len() as u64).sum();
- let end = group.last().map_or(0, |batch| batch.last() + 1);
- let items: Vec<_> = group
- .iter()
- .cloned()
- .map(|batch| {
- let mut item = batch.into_item();
- item.meta_mut().tags.push(BACKFILL_TAG.to_string());
- item
- })
- .collect();
- let count = items.len() as u64;
- if let Err(error) = store_many_on(bound, items).await {
- tracing::warn!(
- code = error.code(),
- "[memory:backfill] storing a batch failed; stopping"
- );
- file.state.phase = ImportPhase::Error;
- file.state.error = Some(String::from(error));
- file.state.finished_at = Some(Utc::now());
- write_file(workspace_dir, &file);
- return;
- }
- file.stored.insert(plan.thread_id.clone(), end);
- file.state.turns_stored += turns;
- file.state.items_stored += count;
- write_file(workspace_dir, &file);
- }
- file.state.threads_done += 1;
- write_file(workspace_dir, &file);
- }
- file.state.phase = ImportPhase::Done;
- file.state.finished_at = Some(Utc::now());
- write_file(workspace_dir, &file);
- tracing::info!(
- items = file.state.items_stored,
- turns = file.state.turns_stored,
- "[memory:backfill] done"
- );
-}
-
-#[cfg(test)]
-#[path = "backfill_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/conversations/buffer.rs b/crates/openhuman-core/src/memory/conversations/buffer.rs
deleted file mode 100644
index e2240453f8..0000000000
--- a/crates/openhuman-core/src/memory/conversations/buffer.rs
+++ /dev/null
@@ -1,232 +0,0 @@
-//! Per-thread batching of committed turns.
-//!
-//! A [`ConversationBuffer`] holds the turns of each thread that have not been
-//! stored yet. [`ConversationBuffer::push`] hands back a [`Batch`] once a
-//! thread holds `batch_turns` turns; [`ConversationBuffer::take_idle`] hands
-//! back every thread that has been quiet for `idle_secs`. Pure data: no I/O,
-//! no clock (callers pass `now`).
-
-use std::collections::HashMap;
-
-use chrono::{DateTime, Duration, Utc};
-use tinymemory_api::{MemoryMeta, Namespace, Role, SourceKind, SourceRef, StoreItem, ToolCallRef, Turn, TurnRange};
-
-/// One committed exchange: the user's message and the assistant's reply.
-#[derive(Debug, Clone, PartialEq)]
-pub struct CommittedTurn {
- /// The thread it belongs to.
- 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.
- pub channel: Option<String>,
- /// What the user said.
- pub user: String,
- /// What the assistant replied.
- pub assistant: String,
- /// Tool calls made while answering (name and id only).
- pub tool_calls: Vec<ToolCallRef>,
- /// When the turn committed.
- pub at: DateTime<Utc>,
-}
-
-/// The tag a conversation item from `channel` carries.
-#[must_use]
-pub fn channel_tag(channel: &str) -> String {
- format!("channel:{}", channel.to_ascii_lowercase())
-}
-
-/// 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.
- pub thread_id: String,
- /// Index of the first turn in the batch.
- pub first: u32,
- /// The turns, oldest first.
- pub turns: Vec<CommittedTurn>,
-}
-
-impl Batch {
- /// Index of the last turn in the batch.
- #[must_use]
- pub fn last(&self) -> u32 {
- self.first + u32::try_from(self.turns.len().saturating_sub(1)).unwrap_or(u32::MAX)
- }
-
- /// The `Conversation` item this batch stores.
- ///
- /// Meta carries `thread_id`, `agent_id` and `workspace` (from the latest
- /// 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]
- pub fn into_item(self) -> StoreItem {
- let last = self.last();
- let agent_id = self
- .turns
- .iter()
- .rev()
- .find_map(|turn| turn.agent_id.clone());
- let workspace = self
- .turns
- .iter()
- .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()
- .rev()
- .find_map(|turn| turn.channel.as_deref())
- .map(|channel| vec![channel_tag(channel)])
- .unwrap_or_default();
- let mut turns = Vec::with_capacity(self.turns.len() * 2);
- for turn in self.turns {
- if !turn.user.trim().is_empty() {
- turns.push(Turn {
- role: Role::User,
- text: turn.user,
- at: Some(turn.at),
- tool_calls: Vec::new(),
- });
- }
- if !turn.assistant.trim().is_empty() || !turn.tool_calls.is_empty() {
- let text = if turn.assistant.trim().is_empty() {
- "(tool calls only)".to_string()
- } else {
- turn.assistant
- };
- turns.push(Turn {
- role: Role::Assistant,
- text,
- at: Some(turn.at),
- tool_calls: turn.tool_calls,
- });
- }
- }
- StoreItem::Conversation {
- turns,
- meta: MemoryMeta {
- namespace,
- workspace,
- thread_id: Some(self.thread_id.clone()),
- turns: Some(TurnRange {
- first: self.first,
- last,
- }),
- agent_id,
- source: SourceRef {
- kind: SourceKind::Conversation,
- id: Some(self.thread_id),
- },
- observed_at,
- tags,
- ..MemoryMeta::default()
- },
- }
- }
-}
-
-#[derive(Debug, Default)]
-struct PendingThread {
- first: u32,
- turns: Vec<CommittedTurn>,
- last_activity: Option<DateTime<Utc>>,
-}
-
-/// Unstored turns, per thread.
-#[derive(Debug, Default)]
-pub struct ConversationBuffer {
- threads: HashMap<String, PendingThread>,
-}
-
-impl ConversationBuffer {
- /// 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;
- }
- pending.last_activity = Some(turn.at);
- pending.turns.push(turn);
- if pending.turns.len() >= batch_turns.max(1) as usize {
- ready.extend(self.take(&thread_id));
- }
- ready
- }
-
- /// Removes and returns every thread idle for at least `idle_secs` at `now`.
- pub fn take_idle(&mut self, now: DateTime<Utc>, idle_secs: u64) -> Vec<Batch> {
- let idle = Duration::seconds(i64::try_from(idle_secs).unwrap_or(i64::MAX));
- let ready: Vec<String> = self
- .threads
- .iter()
- .filter(|(_, pending)| {
- pending
- .last_activity
- .is_some_and(|last| now.signed_duration_since(last) >= idle)
- })
- .map(|(thread_id, _)| thread_id.clone())
- .collect();
- ready
- .into_iter()
- .filter_map(|thread_id| self.take(&thread_id))
- .collect()
- }
-
- /// Removes and returns every pending thread.
- pub fn take_all(&mut self) -> Vec<Batch> {
- let ids: Vec<String> = self.threads.keys().cloned().collect();
- ids.into_iter()
- .filter_map(|thread_id| self.take(&thread_id))
- .collect()
- }
-
- /// How many turns are pending in `thread_id`.
- #[must_use]
- pub fn pending(&self, thread_id: &str) -> usize {
- self.threads.get(thread_id).map_or(0, |p| p.turns.len())
- }
-
- fn take(&mut self, thread_id: &str) -> Option<Batch> {
- let pending = self.threads.remove(thread_id)?;
- if pending.turns.is_empty() {
- return None;
- }
- Some(Batch {
- thread_id: thread_id.to_string(),
- first: pending.first,
- turns: pending.turns,
- })
- }
-}
-
-#[cfg(test)]
-#[path = "buffer_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/conversations/buffer_tests.rs b/crates/openhuman-core/src/memory/conversations/buffer_tests.rs
deleted file mode 100644
index be4f3105f3..0000000000
--- a/crates/openhuman-core/src/memory/conversations/buffer_tests.rs
+++ /dev/null
@@ -1,222 +0,0 @@
-use super::*;
-use chrono::TimeZone;
-
-fn at(secs: i64) -> DateTime<Utc> {
- Utc.timestamp_opt(1_700_000_000 + secs, 0).single().unwrap()
-}
-
-fn turn(thread: &str, user: &str, assistant: &str, secs: i64) -> CommittedTurn {
- CommittedTurn {
- thread_id: thread.to_string(),
- agent_id: None,
- namespace: Namespace::ROOT,
- workspace: None,
- channel: None,
- user: user.to_string(),
- assistant: assistant.to_string(),
- tool_calls: Vec::new(),
- at: at(secs),
- }
-}
-
-#[test]
-fn push_flushes_exactly_when_the_batch_is_full() {
- let mut buffer = ConversationBuffer::default();
- assert!(buffer.push(turn("t", "a", "b", 0), 4, 3).is_empty());
- assert!(buffer.push(turn("t", "c", "d", 1), 5, 3).is_empty());
- assert_eq!(buffer.pending("t"), 2);
- let batch = buffer
- .push(turn("t", "e", "f", 2), 6, 3)
- .pop()
- .expect("full");
- assert_eq!(batch.thread_id, "t");
- assert_eq!(batch.first, 4);
- assert_eq!(batch.last(), 6);
- assert_eq!(batch.turns.len(), 3);
- assert_eq!(buffer.pending("t"), 0);
-
- // The next batch starts at the index it is handed.
- assert!(buffer.push(turn("t", "g", "h", 3), 7, 3).is_empty());
- let rest = buffer.take_all();
- assert_eq!(rest.len(), 1);
- assert_eq!(rest[0].first, 7);
-}
-
-#[test]
-fn threads_are_batched_independently() {
- let mut buffer = ConversationBuffer::default();
- assert!(buffer.push(turn("a", "1", "1", 0), 0, 2).is_empty());
- assert!(buffer.push(turn("b", "1", "1", 0), 0, 2).is_empty());
- let full = buffer
- .push(turn("a", "2", "2", 1), 1, 2)
- .pop()
- .expect("a is full");
- assert_eq!(full.thread_id, "a");
- assert_eq!(buffer.pending("a"), 0);
- assert_eq!(buffer.pending("b"), 1);
-}
-
-#[test]
-fn a_zero_batch_size_still_flushes_every_turn() {
- let mut buffer = ConversationBuffer::default();
- assert_eq!(buffer.push(turn("t", "a", "b", 0), 0, 0).len(), 1);
-}
-
-#[test]
-fn take_idle_returns_only_quiet_threads_at_the_boundary() {
- let mut buffer = ConversationBuffer::default();
- buffer.push(turn("quiet", "a", "b", 0), 0, 10);
- buffer.push(turn("busy", "a", "b", 50), 0, 10);
- // 59s after the quiet thread's last turn: not yet idle for 60s.
- assert!(buffer.take_idle(at(59), 60).is_empty());
- let ready = buffer.take_idle(at(60), 60);
- assert_eq!(ready.len(), 1);
- assert_eq!(ready[0].thread_id, "quiet");
- assert_eq!(buffer.pending("quiet"), 0);
- assert_eq!(buffer.pending("busy"), 1);
- let later = buffer.take_idle(at(200), 60);
- assert_eq!(later.len(), 1);
- assert_eq!(later[0].thread_id, "busy");
-}
-
-#[test]
-fn a_new_turn_resets_the_idle_clock() {
- let mut buffer = ConversationBuffer::default();
- buffer.push(turn("t", "a", "b", 0), 0, 10);
- buffer.push(turn("t", "c", "d", 100), 1, 10);
- assert!(buffer.take_idle(at(120), 60).is_empty());
- assert_eq!(buffer.take_idle(at(160), 60).len(), 1);
-}
-
-#[test]
-fn take_all_and_pending_on_an_empty_buffer() {
- let mut buffer = ConversationBuffer::default();
- assert_eq!(buffer.pending("nobody"), 0);
- assert!(buffer.take_all().is_empty());
- assert!(buffer.take_idle(at(0), 1).is_empty());
-}
-
-#[test]
-fn channel_tag_is_lowercased() {
- assert_eq!(channel_tag("Telegram"), "channel:telegram");
-}
-
-#[test]
-fn into_item_carries_meta_and_keeps_tool_call_names_and_ids_only() {
- let mut first = turn("thread-9", "list files", "here they are", 0);
- first.agent_id = Some("orchestrator".into());
- first.workspace = Some("/work".into());
- first.channel = Some("Web".into());
- first.tool_calls = vec![
- ToolCallRef {
- name: "shell".into(),
- id: Some("call-1".into()),
- },
- ToolCallRef {
- name: "file_read".into(),
- id: None,
- },
- ];
- let second = turn("thread-9", "thanks", "you're welcome", 30);
- let item = Batch {
- thread_id: "thread-9".into(),
- first: 10,
- turns: vec![first, second],
- }
- .into_item();
-
- let StoreItem::Conversation { turns, meta } = item else {
- panic!("expected a conversation");
- };
- assert_eq!(meta.thread_id.as_deref(), Some("thread-9"));
- assert_eq!(meta.agent_id.as_deref(), Some("orchestrator"));
- assert_eq!(meta.workspace.as_deref(), Some("/work"));
- assert_eq!(
- meta.turns,
- Some(TurnRange {
- first: 10,
- last: 11
- })
- );
- assert_eq!(meta.source.kind, SourceKind::Conversation);
- assert_eq!(meta.source.id.as_deref(), Some("thread-9"));
- assert_eq!(meta.tags, vec!["channel:web".to_string()]);
- assert_eq!(meta.observed_at, Some(at(30)));
-
- assert_eq!(turns.len(), 4);
- assert_eq!(turns[0].role, Role::User);
- assert_eq!(turns[1].role, Role::Assistant);
- assert_eq!(turns[1].tool_calls.len(), 2);
- assert_eq!(turns[1].tool_calls[0].name, "shell");
- assert_eq!(turns[1].tool_calls[0].id.as_deref(), Some("call-1"));
- assert_eq!(turns[1].tool_calls[1].id, None);
- assert!(turns[0].tool_calls.is_empty());
- // The serialised item has no place for arguments.
- let json = serde_json::to_string(&turns[1].tool_calls).unwrap();
- assert!(
- !json.contains("arguments") && !json.contains("args"),
- "{json}"
- );
-}
-
-#[test]
-fn into_item_skips_blank_sides_and_labels_tool_only_replies() {
- let mut tool_only = turn("t", "run it", " ", 0);
- tool_only.tool_calls = vec![ToolCallRef {
- name: "shell".into(),
- id: Some("c".into()),
- }];
- let silent = turn("t", " ", "just talking", 1);
- let StoreItem::Conversation { turns, meta } = (Batch {
- thread_id: "t".into(),
- first: 0,
- turns: vec![tool_only, silent],
- })
- .into_item() else {
- panic!("expected a conversation");
- };
- assert_eq!(turns.len(), 3);
- assert_eq!(turns[1].text, "(tool calls only)");
- assert_eq!(turns[2].role, Role::Assistant);
- assert_eq!(turns[2].text, "just talking");
- assert!(meta.tags.is_empty(), "no channel, no tag");
-}
-
-#[test]
-fn last_of_a_single_turn_batch_is_its_first() {
- let batch = Batch {
- thread_id: "t".into(),
- first: 5,
- turns: vec![turn("t", "a", "b", 0)],
- };
- assert_eq!(batch.last(), 5);
-}
-
-#[test]
-fn a_batch_never_mixes_two_agents() {
- let mut buffer = ConversationBuffer::default();
- let by = |agent: &str, secs| CommittedTurn {
- agent_id: Some(agent.to_string()),
- namespace: Namespace::agent(agent),
- ..turn("t", "q", "a", secs)
- };
- assert!(buffer.push(by("researcher", 0), 0, 10).is_empty());
- assert!(buffer.push(by("researcher", 1), 1, 10).is_empty());
- let flushed = buffer.push(by("writer", 2), 2, 10);
- assert_eq!(
- flushed.len(),
- 1,
- "the researcher's turns are stored on their own"
- );
- assert_eq!(flushed[0].turns.len(), 2);
- let item = flushed[0].clone().into_item();
- assert_eq!(item.meta().namespace, Namespace::agent("researcher"));
- assert_eq!(item.meta().agent_id.as_deref(), Some("researcher"));
- assert_eq!(buffer.pending("t"), 1);
- let rest = buffer.take_all();
- assert_eq!(rest[0].first, 2);
- assert_eq!(
- rest[0].clone().into_item().meta().namespace,
- Namespace::agent("writer")
- );
-}
diff --git a/crates/openhuman-core/src/memory/conversations/mod.rs b/crates/openhuman-core/src/memory/conversations/mod.rs
deleted file mode 100644
index 9fb45c88b1..0000000000
--- a/crates/openhuman-core/src/memory/conversations/mod.rs
+++ /dev/null
@@ -1,338 +0,0 @@
-//! Automatic conversation ingestion.
-//!
-//! Every committed turn ([`crate::core::events::DomainEvent::ConversationTurnCommitted`])
-//! is buffered per thread ([`buffer::ConversationBuffer`]) and stored as one
-//! `Conversation` item once the thread holds `batch_turns` turns or has been
-//! idle for `idle_secs` (`[memory.conversations]`). With memory off, or
-//! conversations disabled, a turn is dropped on arrival.
-//!
-//! Bookkeeping that must survive a restart — the per-thread turn counter that
-//! numbers `meta.turns`, and the latest stored batches the UI lists — lives in
-//! `<workspace>/memory/conversations_state.json`. Turn text never touches it.
-
-pub mod backfill;
-pub mod buffer;
-
-use std::collections::{BTreeMap, HashMap};
-use std::path::{Path, PathBuf};
-use std::sync::{LazyLock, Mutex};
-
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
-
-use crate::config::Config;
-
-use super::engine;
-use super::error::{MemoryError, MemoryResult};
-use super::types::{ConversationsSetParams, ConversationsView, RecentConversation};
-use buffer::{Batch, CommittedTurn, ConversationBuffer};
-
-/// How many stored batches the state file remembers.
-const RECENT_LIMIT: usize = 20;
-
-/// How many thread counters the state file keeps (oldest dropped first).
-const THREAD_COUNTER_LIMIT: usize = 1_000;
-
-/// Upper bound on `batch_turns`.
-const MAX_BATCH_TURNS: u32 = 100;
-
-/// Upper bound on `idle_secs` (a day).
-const MAX_IDLE_SECS: u64 = 86_400;
-
-/// Pending turns, per workspace directory.
-static BUFFERS: LazyLock<Mutex<HashMap<PathBuf, ConversationBuffer>>> =
- LazyLock::new(|| Mutex::new(HashMap::new()));
-
-/// Serialises state-file read-modify-writes in this process.
-static STATE_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
-
-#[derive(Debug, Default, Serialize, Deserialize)]
-struct ConversationsState {
- /// Next turn index per thread, with when it was last used.
- #[serde(default)]
- threads: BTreeMap<String, ThreadCounter>,
- /// Latest stored batches, newest first.
- #[serde(default)]
- recent: Vec<RecentConversation>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-struct ThreadCounter {
- next: u32,
- touched_at: DateTime<Utc>,
-}
-
-fn state_path(workspace_dir: &Path) -> PathBuf {
- workspace_dir
- .join("memory")
- .join("conversations_state.json")
-}
-
-fn read_state(workspace_dir: &Path) -> ConversationsState {
- let path = state_path(workspace_dir);
- match std::fs::read_to_string(&path) {
- Ok(text) => serde_json::from_str(&text).unwrap_or_else(|error| {
- tracing::warn!(error = %error, "[memory:conversations] unreadable state file, starting fresh");
- ConversationsState::default()
- }),
- Err(_) => ConversationsState::default(),
- }
-}
-
-fn write_state(workspace_dir: &Path, state: &ConversationsState) {
- let path = state_path(workspace_dir);
- let result = path
- .parent()
- .map_or(Ok(()), std::fs::create_dir_all)
- .and_then(|()| {
- let json = serde_json::to_vec_pretty(state).map_err(std::io::Error::other)?;
- std::fs::write(&path, json)
- });
- if let Err(error) = result {
- tracing::warn!(error = %error, "[memory:conversations] writing state file failed");
- }
-}
-
-/// Claims the next turn index of `thread_id`.
-fn next_turn_index(workspace_dir: &Path, thread_id: &str, now: DateTime<Utc>) -> u32 {
- let _guard = STATE_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut state = read_state(workspace_dir);
- let counter = state
- .threads
- .entry(thread_id.to_string())
- .or_insert(ThreadCounter {
- next: 0,
- touched_at: now,
- });
- let index = counter.next;
- counter.next = counter.next.saturating_add(1);
- counter.touched_at = now;
- if state.threads.len() > THREAD_COUNTER_LIMIT {
- let mut by_age: Vec<(String, DateTime<Utc>)> = state
- .threads
- .iter()
- .map(|(id, counter)| (id.clone(), counter.touched_at))
- .collect();
- by_age.sort_by_key(|(_, touched)| *touched);
- let excess = state.threads.len() - THREAD_COUNTER_LIMIT;
- for (id, _) in by_age.into_iter().take(excess) {
- state.threads.remove(&id);
- }
- }
- write_state(workspace_dir, &state);
- index
-}
-
-fn remember_stored(workspace_dir: &Path, batch: &Batch, stored_at: DateTime<Utc>) {
- let _guard = STATE_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut state = read_state(workspace_dir);
- state.recent.insert(
- 0,
- RecentConversation {
- thread_id: batch.thread_id.clone(),
- turns: u32::try_from(batch.turns.len()).unwrap_or(u32::MAX),
- stored_at,
- },
- );
- state.recent.truncate(RECENT_LIMIT);
- write_state(workspace_dir, &state);
-}
-
-/// How many turns of `thread_id` live ingestion has taken (stored or still
-/// buffered): the thread's most recent turns, which the backfill leaves alone.
-#[must_use]
-pub fn live_turns_taken(workspace_dir: &Path, thread_id: &str) -> u32 {
- let _guard = STATE_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- read_state(workspace_dir)
- .threads
- .get(thread_id)
- .map_or(0, |counter| counter.next)
-}
-
-/// The latest stored batches, newest first.
-#[must_use]
-pub fn recent(workspace_dir: &Path) -> Vec<RecentConversation> {
- read_state(workspace_dir).recent
-}
-
-/// 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, mut turn: CommittedTurn) {
- let settings = &config.memory.conversations;
- if !settings.enabled {
- tracing::trace!("[memory:conversations] disabled; turn dropped");
- return;
- }
- if !engine::is_on(config) {
- 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
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- buffers
- .entry(config.workspace_dir.clone())
- .or_default()
- .push(turn, index, settings.batch_turns)
- };
- 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 = {
- let mut buffers = BUFFERS
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- buffers
- .get_mut(&config.workspace_dir)
- .map(|buffer| buffer.take_idle(now, config.memory.conversations.idle_secs))
- .unwrap_or_default()
- };
- let count = ready.len();
- for batch in ready {
- store_batch(config, batch).await;
- }
- count
-}
-
-/// Stores every pending thread now (used when conversations are switched
-/// off, so nothing buffered is silently lost).
-pub async fn flush_all(config: &Config) -> usize {
- let ready = {
- let mut buffers = BUFFERS
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- buffers
- .get_mut(&config.workspace_dir)
- .map(ConversationBuffer::take_all)
- .unwrap_or_default()
- };
- let count = ready.len();
- for batch in ready {
- store_batch(config, batch).await;
- }
- count
-}
-
-/// How many turns of `thread_id` are buffered for `workspace_dir`.
-#[must_use]
-pub fn pending_turns(workspace_dir: &Path, thread_id: &str) -> usize {
- BUFFERS
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .get(workspace_dir)
- .map_or(0, |buffer| buffer.pending(thread_id))
-}
-
-async fn store_batch(config: &Config, batch: Batch) {
- let turns = batch.turns.len();
- let record = batch.clone();
- match super::ops::store_item(config, batch.into_item()).await {
- Ok(receipt) => {
- tracing::debug!(
- turns,
- replayed = receipt.replayed,
- "[memory:conversations] batch stored"
- );
- remember_stored(&config.workspace_dir, &record, Utc::now());
- }
- Err(error) => tracing::warn!(
- turns,
- code = error.code(),
- "[memory:conversations] storing a batch failed; it is dropped"
- ),
- }
-}
-
-/// Forgets every conversation stored from `channel` (used when a channel is
-/// disconnected with `clear_memory`). Memory off forgets nothing.
-pub async fn forget_channel(config: &Config, channel: &str) -> MemoryResult<usize> {
- let bound = match engine::resolve(config).engine() {
- Ok(bound) => bound,
- Err(MemoryError::Off(_)) => return Ok(0),
- Err(error) => return Err(error),
- };
- let filter = tinymemory_api::MetaFilter {
- kinds: vec![tinymemory_api::ItemKind::Conversation],
- tags_any: vec![buffer::channel_tag(channel)],
- ..tinymemory_api::MetaFilter::default()
- };
- let report = bound
- .engine
- .forget(tinymemory_api::ForgetTarget::Filter(filter))
- .await?;
- tracing::debug!(
- forgotten = report.forgotten,
- "[memory:conversations] channel forgotten"
- );
- Ok(report.forgotten)
-}
-
-/// `memory_conversations_get`.
-#[must_use]
-pub fn view(config: &Config) -> ConversationsView {
- let settings = &config.memory.conversations;
- ConversationsView {
- enabled: settings.enabled,
- batch_turns: settings.batch_turns,
- idle_secs: settings.idle_secs,
- recent: recent(&config.workspace_dir),
- }
-}
-
-/// Applies `memory_conversations_set` to `config`; the caller persists it.
-pub fn apply_set(config: &mut Config, params: &ConversationsSetParams) -> MemoryResult<()> {
- let settings = &mut config.memory.conversations;
- if let Some(batch_turns) = params.batch_turns {
- if !(1..=MAX_BATCH_TURNS).contains(&batch_turns) {
- return Err(MemoryError::invalid(format!(
- "batch_turns must be between 1 and {MAX_BATCH_TURNS}"
- )));
- }
- settings.batch_turns = batch_turns;
- }
- if let Some(idle_secs) = params.idle_secs {
- if !(1..=MAX_IDLE_SECS).contains(&idle_secs) {
- return Err(MemoryError::invalid(format!(
- "idle_secs must be between 1 and {MAX_IDLE_SECS}"
- )));
- }
- settings.idle_secs = idle_secs;
- }
- if let Some(enabled) = params.enabled {
- settings.enabled = enabled;
- }
- Ok(())
-}
-
-#[cfg(test)]
-#[path = "mod_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/conversations/mod_tests.rs b/crates/openhuman-core/src/memory/conversations/mod_tests.rs
deleted file mode 100644
index f380f15347..0000000000
--- a/crates/openhuman-core/src/memory/conversations/mod_tests.rs
+++ /dev/null
@@ -1,329 +0,0 @@
-use super::*;
-use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-use chrono::Duration;
-use tinymemory_api::{ItemKind, MetaFilter, ToolCallRef};
-
-fn turn(thread: &str, text: &str, at: DateTime<Utc>) -> CommittedTurn {
- CommittedTurn {
- thread_id: thread.to_string(),
- agent_id: Some("orchestrator".into()),
- namespace: tinymemory_api::Namespace::ROOT,
- workspace: Some("/work".into()),
- channel: Some("web".into()),
- user: text.to_string(),
- assistant: format!("re: {text}"),
- tool_calls: vec![ToolCallRef {
- name: "shell".into(),
- id: Some("call-1".into()),
- }],
- at,
- }
-}
-
-async fn conversations_in(
- engine: &tinymemory_api::conformance::ReferenceEngine,
-) -> Vec<tinymemory_api::Hit> {
- stored(
- engine,
- MetaFilter {
- kinds: vec![ItemKind::Conversation],
- ..MetaFilter::default()
- },
- )
- .await
-}
-
-#[tokio::test]
-async fn a_full_batch_is_stored_as_one_conversation_item() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 2;
- let engine = bind_reference(&config);
- let now = Utc::now();
-
- record_turn(&config, turn("t-batch", "first question", now)).await;
- assert_eq!(pending_turns(&config.workspace_dir, "t-batch"), 1);
- assert!(conversations_in(&engine).await.is_empty(), "not yet");
-
- record_turn(&config, turn("t-batch", "second question", now)).await;
- assert_eq!(pending_turns(&config.workspace_dir, "t-batch"), 0);
- let items = conversations_in(&engine).await;
- assert_eq!(items.len(), 1);
- let item = &items[0];
- assert_eq!(item.meta.thread_id.as_deref(), Some("t-batch"));
- assert_eq!(item.meta.turns.map(|t| (t.first, t.last)), Some((0, 1)));
- assert!(item.text.contains("first question") && item.text.contains("second question"));
-
- let recent = recent(&config.workspace_dir);
- assert_eq!(recent.len(), 1);
- assert_eq!(recent[0].thread_id, "t-batch");
- assert_eq!(recent[0].turns, 2);
-
- // The next batch continues the thread's numbering.
- record_turn(&config, turn("t-batch", "third", now)).await;
- record_turn(&config, turn("t-batch", "fourth", now)).await;
- let items = conversations_in(&engine).await;
- assert_eq!(items.len(), 2);
- assert!(items
- .iter()
- .any(|i| i.meta.turns.map(|t| (t.first, t.last)) == Some((2, 3))));
-}
-
-#[tokio::test]
-async fn idle_threads_are_flushed_without_waiting_on_a_clock() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 50;
- config.memory.conversations.idle_secs = 120;
- let engine = bind_reference(&config);
- let started = Utc::now();
-
- record_turn(&config, turn("t-idle", "hello", started)).await;
- assert_eq!(
- flush_idle(&config, started + Duration::seconds(119)).await,
- 0
- );
- assert!(conversations_in(&engine).await.is_empty());
- assert_eq!(pending_turns(&config.workspace_dir, "t-idle"), 1);
-
- assert_eq!(
- flush_idle(&config, started + Duration::seconds(120)).await,
- 1
- );
- assert_eq!(conversations_in(&engine).await.len(), 1);
- assert_eq!(pending_turns(&config.workspace_dir, "t-idle"), 0);
- assert_eq!(
- flush_idle(&config, started + Duration::seconds(500)).await,
- 0
- );
-}
-
-#[tokio::test]
-async fn flush_all_stores_every_pending_thread() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 50;
- let engine = bind_reference(&config);
- record_turn(&config, turn("t-one", "a", Utc::now())).await;
- record_turn(&config, turn("t-two", "b", Utc::now())).await;
- assert_eq!(flush_all(&config).await, 2);
- assert_eq!(conversations_in(&engine).await.len(), 2);
- assert_eq!(flush_all(&config).await, 0);
-}
-
-#[tokio::test]
-async fn disabled_conversations_and_memory_off_are_no_ops() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 1;
- let engine = bind_reference(&config);
-
- config.memory.conversations.enabled = false;
- record_turn(&config, turn("t-disabled", "x", Utc::now())).await;
- assert_eq!(pending_turns(&config.workspace_dir, "t-disabled"), 0);
- assert!(conversations_in(&engine).await.is_empty());
- assert!(!state_path(&config.workspace_dir).exists());
-
- let tmp_off = tempfile::tempdir().unwrap();
- let mut off = config_in(&tmp_off);
- off.memory.conversations.batch_turns = 1;
- record_turn(&off, turn("t-off", "x", Utc::now())).await;
- assert_eq!(pending_turns(&off.workspace_dir, "t-off"), 0);
- assert!(recent(&off.workspace_dir).is_empty());
-}
-
-#[tokio::test]
-async fn stored_conversations_carry_tool_names_and_ids_but_no_arguments() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 1;
- let engine = bind_reference(&config);
- record_turn(&config, turn("t-tools", "run ls", Utc::now())).await;
- let items = conversations_in(&engine).await;
- assert_eq!(items.len(), 1);
- let json = serde_json::to_string(&items[0]).unwrap();
- assert!(json.contains("shell"), "{json}");
- assert!(json.contains("call-1"), "{json}");
- assert!(!json.contains("arguments"), "{json}");
- // Turn text never touches the bookkeeping file.
- let state = std::fs::read_to_string(state_path(&config.workspace_dir)).unwrap();
- assert!(!state.contains("run ls"), "{state}");
-}
-
-#[tokio::test]
-async fn a_failed_store_drops_the_batch_without_recording_it() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 1;
- // A conversation with blank text on both sides is invalid for the engine.
- let mut blank = turn("t-blank", " ", Utc::now());
- blank.assistant = String::new();
- blank.tool_calls.clear();
- bind_reference(&config);
- record_turn(&config, blank).await;
- assert_eq!(pending_turns(&config.workspace_dir, "t-blank"), 0);
- assert!(recent(&config.workspace_dir).is_empty());
-}
-
-#[tokio::test]
-async fn recent_is_capped_and_newest_first() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 1;
- bind_reference(&config);
- for n in 0..RECENT_LIMIT + 3 {
- record_turn(&config, turn(&format!("t-{n}"), "msg", Utc::now())).await;
- }
- let listed = recent(&config.workspace_dir);
- assert_eq!(listed.len(), RECENT_LIMIT);
- assert_eq!(listed[0].thread_id, format!("t-{}", RECENT_LIMIT + 2));
-}
-
-#[test]
-fn turn_counters_are_per_thread_and_survive_in_the_state_file() {
- let tmp = tempfile::tempdir().unwrap();
- let ws = tmp.path();
- let now = Utc::now();
- assert_eq!(next_turn_index(ws, "a", now), 0);
- assert_eq!(next_turn_index(ws, "a", now), 1);
- assert_eq!(next_turn_index(ws, "b", now), 0);
- assert_eq!(next_turn_index(ws, "a", now), 2);
-}
-
-#[test]
-fn thread_counters_are_pruned_oldest_first() {
- let tmp = tempfile::tempdir().unwrap();
- let ws = tmp.path();
- let base = Utc::now() - Duration::days(1);
- let mut state = ConversationsState::default();
- for n in 0..THREAD_COUNTER_LIMIT {
- state.threads.insert(
- format!("old-{n:04}"),
- ThreadCounter {
- next: 1,
- touched_at: base + Duration::seconds(n as i64),
- },
- );
- }
- write_state(ws, &state);
- assert_eq!(next_turn_index(ws, "fresh", Utc::now()), 0);
- let after = read_state(ws);
- assert_eq!(after.threads.len(), THREAD_COUNTER_LIMIT);
- assert!(after.threads.contains_key("fresh"));
- assert!(
- !after.threads.contains_key("old-0000"),
- "the oldest went first"
- );
-}
-
-#[test]
-fn an_unreadable_state_file_starts_fresh() {
- let tmp = tempfile::tempdir().unwrap();
- std::fs::create_dir_all(tmp.path().join("memory")).unwrap();
- std::fs::write(state_path(tmp.path()), "{not json").unwrap();
- assert!(recent(tmp.path()).is_empty());
- assert_eq!(next_turn_index(tmp.path(), "t", Utc::now()), 0);
-}
-
-#[tokio::test]
-async fn forget_channel_removes_only_that_channels_conversations() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 1;
- let engine = bind_reference(&config);
- let mut telegram = turn("t-tg", "from telegram", Utc::now());
- telegram.channel = Some("Telegram".into());
- record_turn(&config, telegram).await;
- record_turn(&config, turn("t-web", "from web", Utc::now())).await;
- assert_eq!(conversations_in(&engine).await.len(), 2);
-
- assert_eq!(forget_channel(&config, "telegram").await.unwrap(), 1);
- let left = conversations_in(&engine).await;
- assert_eq!(left.len(), 1);
- assert_eq!(left[0].meta.thread_id.as_deref(), Some("t-web"));
-
- let tmp_off = tempfile::tempdir().unwrap();
- assert_eq!(
- forget_channel(&config_in(&tmp_off), "telegram")
- .await
- .unwrap(),
- 0,
- "memory off forgets nothing and is not an error"
- );
-}
-
-#[test]
-fn view_and_apply_set_validate_and_report() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- for bad in [
- ConversationsSetParams {
- batch_turns: Some(0),
- ..ConversationsSetParams::default()
- },
- ConversationsSetParams {
- batch_turns: Some(MAX_BATCH_TURNS + 1),
- ..ConversationsSetParams::default()
- },
- ConversationsSetParams {
- idle_secs: Some(0),
- ..ConversationsSetParams::default()
- },
- ConversationsSetParams {
- idle_secs: Some(MAX_IDLE_SECS + 1),
- ..ConversationsSetParams::default()
- },
- ] {
- assert_eq!(
- apply_set(&mut config, &bad).unwrap_err().code(),
- crate::memory::error::INVALID_REQUEST
- );
- }
- apply_set(
- &mut config,
- &ConversationsSetParams {
- enabled: Some(false),
- batch_turns: Some(7),
- idle_secs: Some(33),
- },
- )
- .unwrap();
- let view = view(&config);
- assert!(!view.enabled);
- assert_eq!(view.batch_turns, 7);
- assert_eq!(view.idle_secs, 33);
- assert!(view.recent.is_empty());
-}
-
-#[tokio::test]
-async fn each_agent_s_turns_land_on_its_own_node() {
- let tmp = tempfile::tempdir().unwrap();
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 2;
- let engine = bind_reference(&config);
- let now = Utc::now();
- let by = |agent: &str, text: &str| CommittedTurn {
- agent_id: Some(agent.into()),
- ..turn("t-agents", text, now)
- };
-
- record_turn(&config, by("orchestrator", "main question")).await;
- record_turn(&config, by("researcher", "research question")).await;
- record_turn(&config, by("researcher", "research follow-up")).await;
- let items = conversations_in(&engine).await;
- let at = |text: &str| {
- items
- .iter()
- .find(|item| item.text.contains(text))
- .map(|item| item.meta.namespace.to_string())
- };
- assert_eq!(at("main question").as_deref(), Some("root"));
- assert_eq!(at("research question").as_deref(), Some("agent:researcher"));
- assert!(
- items
- .iter()
- .all(|item| !(item.text.contains("main question")
- && item.text.contains("research question"))),
- "a batch never mixes two agents"
- );
-}
diff --git a/crates/openhuman-core/src/memory/exit.rs b/crates/openhuman-core/src/memory/exit.rs
deleted file mode 100644
index cf44f14ca0..0000000000
--- a/crates/openhuman-core/src/memory/exit.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-//! What memory does on the way out of the process.
-//!
-//! Conversation turns are buffered per thread until `batch_turns` or
-//! `idle_secs` is reached ([`super::conversations`]), so a quit would drop
-//! whatever is still buffered. This stores it, bounded: a quit that hangs on an
-//! unreachable engine is worse than losing the last few turns of a thread.
-
-use std::time::Duration;
-
-use crate::config::Config;
-
-/// The whole of memory's exit work must fit in this. The Tauri shell sizes its
-/// drain wait from it, plus a short margin for the drain itself.
-pub const EXIT_BUDGET: Duration = Duration::from_secs(2);
-
-/// Stores every buffered conversation turn within [`EXIT_BUDGET`].
-///
-/// Returns how many thread batches were flushed, or `None` when the budget ran
-/// out first (the remaining turns are lost; nothing else is affected).
-pub async fn run(config: &Config) -> Option<usize> {
- run_within(config, EXIT_BUDGET).await
-}
-
-/// [`run`] with an explicit budget.
-pub async fn run_within(config: &Config, budget: Duration) -> Option<usize> {
- match tokio::time::timeout(budget, super::conversations::flush_all(config)).await {
- Ok(flushed) => {
- log::debug!("[memory:exit] flushed {flushed} buffered conversation batch(es)");
- Some(flushed)
- }
- Err(_) => {
- log::warn!("[memory:exit] conversation flush exceeded {budget:?}; dropping the rest");
- None
- }
- }
-}
-
-#[cfg(test)]
-#[path = "exit_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/exit_tests.rs b/crates/openhuman-core/src/memory/exit_tests.rs
deleted file mode 100644
index 7e5bb2c8c2..0000000000
--- a/crates/openhuman-core/src/memory/exit_tests.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use super::*;
-
-use chrono::Utc;
-use tinymemory_api::{ItemKind, MetaFilter};
-
-use crate::memory::conversations::{self, buffer::CommittedTurn};
-use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-
-fn turn(thread_id: &str) -> CommittedTurn {
- CommittedTurn {
- thread_id: thread_id.to_string(),
- agent_id: Some("orchestrator".into()),
- namespace: tinymemory_api::Namespace::ROOT,
- workspace: None,
- channel: None,
- user: "hello".into(),
- assistant: "hi".into(),
- tool_calls: Vec::new(),
- at: Utc::now(),
- }
-}
-
-#[tokio::test]
-async fn stores_buffered_turns_on_exit() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = config_in(&tmp);
- config.memory.conversations.batch_turns = 10;
- let engine = bind_reference(&config);
-
- conversations::record_turn(&config, turn("t-exit")).await;
- assert_eq!(
- conversations::pending_turns(&config.workspace_dir, "t-exit"),
- 1
- );
-
- assert_eq!(run(&config).await, Some(1));
- assert_eq!(
- conversations::pending_turns(&config.workspace_dir, "t-exit"),
- 0
- );
- let items = stored(
- &engine,
- MetaFilter {
- kinds: vec![ItemKind::Conversation],
- ..MetaFilter::default()
- },
- )
- .await;
- assert_eq!(items.len(), 1, "the buffered turn was stored");
-}
-
-#[tokio::test]
-async fn nothing_buffered_flushes_nothing() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let config = config_in(&tmp);
- assert_eq!(
- run_within(&config, Duration::from_millis(500)).await,
- Some(0)
- );
-}