Skip to content

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

wip(memory): partial engine shed across five lanes\n\nCheckpoint of in-progress work so it is not lost. The tree compiles clean on\nthe product feature set; the migration is not finished.\n\nLanded so far:\n- conversations: the JSONL thread store moved home under\n memory/conversations/store/ and its consumers repointed\n- archivist: store.rs brought home beside its tests\n- goals: doc.rs carries the goals document type host-side\n- tool_memory: store.rs brought home\n- learning/candidate and tinyagents/thread_context grew host-side tests\n- tree: several dead re-export globs identified and removed\n- the direct-engine ratchet's non-vacuity assertion unbroken (separate commit)\n\ntinycortex references 268 -> 211, tinymemory_core 235 -> 224.\n\nCargo.toml is deliberately untouched: the dependency lines cannot move until\nthe remaining production references are gone, and moving them early would break\nevery lane at once.\n\n

Shanu4b95d9619a1d
diff --git a/src/openhuman/agent/harness/archivist/hook_impl.rs b/src/openhuman/agent/harness/archivist/hook_impl.rs
index 5ea389143b..6b3e0a01ea 100644
--- a/src/openhuman/agent/harness/archivist/hook_impl.rs
+++ b/src/openhuman/agent/harness/archivist/hook_impl.rs
@@ -1,6 +1,7 @@
//! `PostTurnHook` implementation for `ArchivistHook`.
use super::helpers::extract_lesson_from_tools;
+use super::store::{record_turn, ArchivedTurn};
use super::types::ArchivistHook;
use crate::openhuman::agent::hooks::{PostTurnHook, TurnContext};
use crate::openhuman::memory::api::provider::EpisodicTurn;
@@ -75,32 +76,32 @@ impl PostTurnHook for ArchivistHook {
tracing::debug!("[archivist] episodic rows written: session={session_id}");
- // Dual-write into the crate-owned archivist store (md-backed) so we can
- // validate the FTS5 → md migration before flipping the read side.
+ // Dual-write into the md-backed archivist store so we can validate the
+ // FTS5 → md migration before flipping the read side.
// Best-effort: a write failure here must not break the turn. The
// user turn's assigned seq is captured into `current_seq` so the
// segment ops can store it alongside the FTS5 episodic id.
let mut current_seq: Option<u32> = None;
if let Some(cfg) = self.config.as_ref() {
- // The archivist store addresses `MemoryConfig::workspace` and
- // nothing else: `tinycortex::memory::archivist::store` computes its
- // own content root as `<workspace>/memory_tree/content` (a private
- // `content_root(config)` in that module) and never reads
- // `config.content_root` or `config.embedding`.
+ // The archivist store addresses the workspace root and nothing
+ // else: [`super::store`] derives its own content root as
+ // `<workspace>/memory_tree/content` and deliberately does not
+ // consult `Config::memory_tree_content_root`, whose
+ // `memory_tree.content_root` override would relocate an archive
+ // that is already on disk.
//
- // This used to build the config through
- // `tinymemory_core::tinycortex::memory_config_from`, which is the
- // engine crate's `Config` → `MemoryConfig` mapping. That mapping
- // sets two further fields — the content-root override and the
- // embedding signature — and neither reaches `record_turn` or
- // `session_entries`, so constructing the workspace-rooted config
- // directly is the same value where it is read. Naming it here also
- // drops the last `tinymemory_core::` reference in this file (#5560);
- // `tinycortex` stays a direct dependency of this crate and is where
- // the archivist store itself lives, two lines below.
- let engine_config = tinycortex::memory::MemoryConfig::new(cfg.workspace_dir.clone());
+ // The store used to be `tinycortex::memory::archivist::store`, and
+ // the call built a whole `MemoryConfig` for the sole purpose of
+ // carrying this one path — that type's other fields (the
+ // content-root override, the embedding signature) reached neither
+ // `record_turn` nor `session_entries`. Nothing in the engine ever
+ // called the store, so it now lives in this directory instead,
+ // which is what lets `tinycortex` leave this crate's dependencies
+ // (#5560). Same paths, same bytes: `store_tests` pins that against
+ // the engine's copy in both directions rather than asserting it.
+ let workspace = cfg.workspace_dir.as_path();
let ts_ms = (timestamp * 1000.0) as i64;
- let user_turn = tinycortex::memory::archivist::types::ArchivedTurn {
+ let user_turn = ArchivedTurn {
session_id: session_id.to_string(),
seq: 0, // assigned by record_turn
timestamp_ms: ts_ms,
@@ -110,7 +111,7 @@ impl PostTurnHook for ArchivistHook {
tool_calls_json: None,
cost_microdollars: 0,
};
- match tinycortex::memory::archivist::store::record_turn(&engine_config, user_turn) {
+ match record_turn(workspace, user_turn) {
Ok(stored) => current_seq = Some(stored.seq),
Err(e) => {
tracing::warn!("[archivist] memory_archivist user dual-write failed: {e}");
@@ -125,7 +126,7 @@ impl PostTurnHook for ArchivistHook {
} else {
Some(serde_json::to_string(&ctx.tool_calls).unwrap_or_default())
};
- let assistant_turn = tinycortex::memory::archivist::types::ArchivedTurn {
+ let assistant_turn = ArchivedTurn {
session_id: session_id.to_string(),
seq: 0,
timestamp_ms: ts_ms + 1,
@@ -135,9 +136,7 @@ impl PostTurnHook for ArchivistHook {
tool_calls_json: assistant_tool_calls,
cost_microdollars: 0,
};
- if let Err(e) =
- tinycortex::memory::archivist::store::record_turn(&engine_config, assistant_turn)
- {
+ if let Err(e) = record_turn(workspace, assistant_turn) {
tracing::warn!("[archivist] memory_archivist assistant dual-write failed: {e}");
}
}
diff --git a/src/openhuman/agent/harness/archivist/mod.rs b/src/openhuman/agent/harness/archivist/mod.rs
index 4d1c412ae5..def3af3aef 100644
--- a/src/openhuman/agent/harness/archivist/mod.rs
+++ b/src/openhuman/agent/harness/archivist/mod.rs
@@ -22,6 +22,11 @@ mod helpers;
mod hook_impl;
mod lifecycle;
mod recap;
+// The md-backed per-turn capture store the hook dual-writes into. It lives
+// here rather than behind the memory engine because nothing but this hook ever
+// called it — see the module's own docs for the round trip and for why the
+// contract's episodic family is not where it belongs (#5560).
+mod store;
#[cfg(test)]
mod test_constructors;
mod tree_ingest;
diff --git a/src/openhuman/agent/harness/archivist/recap.rs b/src/openhuman/agent/harness/archivist/recap.rs
index d923ad7a48..16289b506a 100644
--- a/src/openhuman/agent/harness/archivist/recap.rs
+++ b/src/openhuman/agent/harness/archivist/recap.rs
@@ -1,15 +1,37 @@
//! Summarization and rolling recap logic for `ArchivistHook`.
+use super::store::session_entries;
use super::types::ArchivistHook;
use crate::openhuman::memory::api::provider::{ConversationSegment, EpisodicTurn};
use crate::openhuman::memory::tree::summarise::{summarise, SummaryContext, SummaryInput};
+// `SummaryContext::tree_kind` is the engine's own enum. It is reached here
+// through the host's `memory::tree` shim — the same door `summarise`,
+// `SummaryContext` and `SummaryInput` on the line above already come through —
+// rather than by naming the engine crate. Every hop on that path
+// (`memory::tree::tree` → `tinymemory_core::tree::tree` → `store::trees` →
+// `engine::backend::tree::store`) is a re-export of one item, so this is the
+// same type under a shorter name, not a conversion (#5560).
+use crate::openhuman::memory::tree::tree::TreeKind;
#[cfg(test)]
use std::sync::Arc;
-// `SummaryContext::tree_kind` is TinyCortex's own enum, and
-// `tinymemory_core::store::trees::types::TreeKind` was a re-export of exactly
-// this item. Naming the owning crate changes no type — only which crate alias
-// holds it (#5560).
-use tinycortex::memory::tree::store::TreeKind;
+
+/// Total input/context budget for one summarisation fold.
+///
+/// A pinned copy of the engine's `INPUT_TOKEN_BUDGET`, and its sibling below of
+/// `SUMMARY_OVERHEAD_RESERVE_TOKENS`. Copies rather than imports because the
+/// second of the pair is reachable only by naming `tinycortex` — it is a
+/// `memory::config` constant that no re-export carries out to
+/// `tinymemory-core` — and splitting the pair across two provenances would
+/// hide that the summariser's arithmetic reads them together.
+///
+/// `recap_tests::summary_budget_constants_match_the_engine` asserts both still
+/// equal the engine's, so drift fails a test rather than silently changing
+/// every recap's prompt budget.
+const INPUT_TOKEN_BUDGET: u32 = 50_000;
+
+/// Prompt and formatting headroom withheld from the source inputs of a fold.
+/// See [`INPUT_TOKEN_BUDGET`] for why this is a copy.
+const SUMMARY_OVERHEAD_RESERVE_TOKENS: u32 = 2_048;
/// An episodic entry paired with the stable identity exposed by its backing
/// store. The md archivist uses a per-session sequence while the legacy FTS5
@@ -59,9 +81,9 @@ impl SessionEntry {
}
impl ArchivistHook {
- /// Read every entry recorded for `session_id`, preferring the
- /// crate-owned md-backed archivist store when `self.config` is set and
- /// falling back to the legacy FTS5 episodic table otherwise.
+ /// Read every entry recorded for `session_id`, preferring the md-backed
+ /// archivist store when `self.config` is set and falling back to the
+ /// legacy FTS5 episodic table otherwise.
///
/// Each entry retains the stable sequence or row identity needed for
/// segment selection. Timestamps are only a fallback for legacy records:
@@ -70,14 +92,12 @@ impl ArchivistHook {
pub(super) async fn read_session_entries(&self, session_id: &str) -> Vec<SessionEntry> {
if let Some(cfg) = self.config.as_ref() {
// Workspace-rooted and nothing else, for the same reason as the
- // write side in `hook_impl.rs`: `session_entries` resolves its
- // directory through the archivist store's own private
- // `<workspace>/memory_tree/content` root and reads neither
- // `content_root` nor `embedding`. See that call site for why this
- // replaced `tinymemory_core::tinycortex::memory_config_from`.
- let engine_config = tinycortex::memory::MemoryConfig::new(cfg.workspace_dir.clone());
- match tinycortex::memory::archivist::store::session_entries(&engine_config, session_id)
- {
+ // write side in `hook_impl.rs`: [`super::store::session_entries`]
+ // resolves its directory through the store's own private
+ // `<workspace>/memory_tree/content` root. See that call site for
+ // why the store now lives in this directory rather than behind
+ // `tinycortex` (#5560).
+ match session_entries(cfg.workspace_dir.as_path(), session_id) {
Ok(turns) => {
return turns
.into_iter()
@@ -93,7 +113,7 @@ impl ArchivistHook {
content: t.content,
lesson: t.lesson,
tool_calls_json: t.tool_calls_json,
- // The engine column is unsigned; the wire is a
+ // The stored field is unsigned; the wire is a
// plain signed number.
cost_microdollars: i64::try_from(t.cost_microdollars)
.unwrap_or(i64::MAX),
@@ -190,8 +210,8 @@ impl ArchivistHook {
tree_kind: TreeKind::Source,
target_level: 0,
token_budget: 2_000,
- input_token_budget: tinycortex::memory::config::INPUT_TOKEN_BUDGET,
- overhead_reserve_tokens: tinycortex::memory::config::SUMMARY_OVERHEAD_RESERVE_TOKENS,
+ input_token_budget: INPUT_TOKEN_BUDGET,
+ overhead_reserve_tokens: SUMMARY_OVERHEAD_RESERVE_TOKENS,
ask: None,
};
diff --git a/src/openhuman/agent/harness/archivist/recap_tests.rs b/src/openhuman/agent/harness/archivist/recap_tests.rs
index 50551d1e25..4a9ed34642 100644
--- a/src/openhuman/agent/harness/archivist/recap_tests.rs
+++ b/src/openhuman/agent/harness/archivist/recap_tests.rs
@@ -44,6 +44,25 @@ fn segment_membership_uses_sequence_instead_of_rounded_timestamp() {
assert!(!entry(Some(16), None, 100.001).is_in_segment(&segment));
}
+/// The two summariser budgets are copies of the engine's constants — see
+/// [`super::INPUT_TOKEN_BUDGET`] for why they had to be copied rather than
+/// imported. This is the pin that makes a drift a failing test instead of a
+/// silent change to the prompt budget of every recap the archivist produces.
+///
+/// The engine stays a `dev-dependency`, so naming it in a test is fine; naming
+/// it in `recap.rs` is the thing being removed (#5560).
+#[test]
+fn summary_budget_constants_match_the_engine() {
+ assert_eq!(
+ INPUT_TOKEN_BUDGET,
+ tinycortex::memory::config::INPUT_TOKEN_BUDGET
+ );
+ assert_eq!(
+ SUMMARY_OVERHEAD_RESERVE_TOKENS,
+ tinycortex::memory::config::SUMMARY_OVERHEAD_RESERVE_TOKENS
+ );
+}
+
#[test]
fn segment_membership_falls_back_to_episodic_id() {
let mut segment = segment();
diff --git a/src/openhuman/agent/harness/archivist/store.rs b/src/openhuman/agent/harness/archivist/store.rs
new file mode 100644
index 0000000000..86bdb8c275
--- /dev/null
+++ b/src/openhuman/agent/harness/archivist/store.rs
@@ -0,0 +1,384 @@
+//! The archivist's per-turn episodic capture store: one markdown file per
+//! turn, under the workspace's memory-tree content root.
+//!
+//! Layout, unchanged from the day the first turn was written:
+//!
+//! ```text
+//! <workspace>/memory_tree/content/episodic/<session_id>/<seq:06>.md
+//! ```
+//!
+//! Each file is a YAML front-matter block followed by the turn's prose body.
+//! Sequence numbers are per-session and derived from the directory's contents
+//! on every write, so the directory — not a counter held in memory or a row in
+//! a database — is the source of truth for "which turn is this".
+//!
+//! # Why this is here and not in the engine (#5560)
+//!
+//! It was ported *out* of OpenHuman into `tinycortex` as
+//! `memory::archivist::store` and is now back, for the same reason the
+//! conversation store came back: nothing in the engine ever called it. Its only
+//! caller has always been this hook — [`super::hook_impl`] writes both turns of
+//! every completed turn, [`super::recap`] reads a session back — and its
+//! imports are `std::fs`, `anyhow`, `serde_json` (as a string escaper, not as a
+//! document format), `sha2` and `uuid`. No SQLite, no engine internals, no
+//! `MemoryConfig` beyond one field. It was host code parked in a library.
+//!
+//! Bringing it home is what lets `tinycortex` leave this crate's
+//! `[dependencies]`: the archivist runs on **every agent turn**, so as long as
+//! its store lived behind that crate name, the engine was pinned into the
+//! shipped binary by the hottest path in the harness.
+//!
+//! # Why it is not routed at `MemoryEpisodic` instead
+//!
+//! This is the obvious-looking migration and it is wrong, so it is worth
+//! recording before someone re-derives it.
+//!
+//! The contract's episodic family (`insert_turn` / `session_turns`) is served
+//! by `TinycortexProvider` out of `tinymemory_core::store::fts5` — the SQLite
+//! full-text table. That is a **different store from this one**, not another
+//! door onto it. [`super::hook_impl`] already calls both in the same function:
+//! the FTS5 insert through the provider, and [`record_turn`] here. The pairing
+//! is deliberate — it is the dual-write that lets the md store be validated
+//! before the read side flips to it — and routing this half at the contract
+//! would not move the write, it would delete it, taking every archived turn on
+//! every user's disk with it.
+//!
+//! # What changed in the round trip, and what could not
+//!
+//! One signature: the engine's entry points took `&MemoryConfig` and read
+//! exactly one field off it (`workspace`), so these take the workspace path
+//! directly. The call sites previously built a `MemoryConfig::new(workspace)`
+//! for the sole purpose of handing it back — the config carried a content-root
+//! override and an embedding signature that this module has never read.
+//!
+//! Note that dropping it is what *preserves* behaviour rather than changing it.
+//! [`content_root`] joins `memory_tree/content` onto the workspace
+//! unconditionally; it deliberately does **not** consult
+//! `Config::memory_tree_content_root`, which honours the
+//! `memory_tree.content_root` override. A workspace that sets that override
+//! still keeps its episodic turns under the workspace-rooted path, because
+//! that is where they already are.
+//!
+//! Everything the on-disk bytes depend on is a verbatim copy: the `{:06}.md`
+//! filename, the front-matter key order and escaping, the blank line between
+//! front matter and body, the trailing-newline rule, the session-id sanitiser
+//! (including its Unicode `is_alphanumeric`, its SHA-256 suffix, and the exact
+//! six digest bytes it takes), and the create-new publish with its retry loop.
+//! `store_tests` pins that claim against the engine's own implementation rather
+//! than asserting it: it writes with one and reads with the other, in both
+//! directions, and compares the raw file bytes.
+//!
+//! The one thing not carried over is the `Serialize`/`Deserialize` derive on
+//! [`ArchivedTurn`]. The on-disk format is the hand-rolled front matter below,
+//! not serde's rendering of this struct, and no caller serialises it — keeping
+//! a derive that produces a *different* shape than the file it describes is an
+//! invitation to write the wrong one.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+
+/// Directory under the content root that holds per-session turn archives.
+const EPISODIC_DIR: &str = "episodic";
+
+/// One per-turn capture record, persisted by [`record_turn`] as a single md
+/// file.
+///
+/// The field names mirror the contract's `EpisodicTurn` (and the legacy FTS5
+/// `EpisodicEntry` before it) so the archivist's dual-write can hand the same
+/// payload to both surfaces. They are not the same type: this one carries a
+/// per-session `seq` assigned on write and epoch **milliseconds**, where the
+/// contract carries a driver-assigned row id and epoch **seconds** as `f64`.
+/// [`super::recap`] owns that conversion.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub(super) struct ArchivedTurn {
+ /// Session this turn belongs to.
+ pub(super) session_id: String,
+ /// Per-session sequence number, assigned by [`record_turn`] on write.
+ pub(super) seq: u32,
+ /// Wall-clock timestamp of the turn (epoch milliseconds).
+ pub(super) timestamp_ms: i64,
+ /// `"user"` / `"assistant"` / `"system"` / `"tool"`.
+ pub(super) role: String,
+ /// Natural-language body.
+ pub(super) content: String,
+ /// Optional post-turn lesson (kept verbatim from the harness).
+ pub(super) lesson: Option<String>,
+ /// Serialized tool-call payload, when the turn issued any.
+ pub(super) tool_calls_json: Option<String>,
+ /// Cost in microdollars; 0 when not yet billed.
+ pub(super) cost_microdollars: u64,
+}
+
+/// Content root for archivist episodic md files.
+///
+/// Workspace-rooted and nothing else — see the module docs for why this does
+/// not go through `Config::memory_tree_content_root`.
+fn content_root(workspace: &Path) -> PathBuf {
+ workspace.join("memory_tree").join("content")
+}
+
+/// Directory holding one session's turns.
+fn session_dir(workspace: &Path, session_id: &str) -> PathBuf {
+ content_root(workspace)
+ .join(EPISODIC_DIR)
+ .join(sanitize_session(session_id))
+}
+
+/// Map any non-`[A-Za-z0-9_-]` character to `_` so a session id is always a
+/// safe single path component.
+fn sanitize_session(s: &str) -> String {
+ sanitize_component_with_digest(s, |character| {
+ character.is_alphanumeric() || character == '-' || character == '_'
+ })
+}
+
+/// Sanitize one machine identifier into a path component while preserving
+/// collision resistance. Safe, non-empty inputs retain their spelling;
+/// transformed or empty inputs receive a short digest of the exact raw value.
+///
+/// The digest is what keeps `a/b` and `a?b` — which both sanitise to `a_b` —
+/// in separate directories. Its width (six bytes of the SHA-256, hex) is part
+/// of the derived path of every session whose id needed escaping, so it is not
+/// a tunable.
+fn sanitize_component_with_digest(raw: &str, allowed: impl Fn(char) -> bool) -> String {
+ use sha2::{Digest, Sha256};
+
+ let sanitized = raw
+ .chars()
+ .map(|character| if allowed(character) { character } else { '_' })
+ .collect::<String>();
+ if sanitized == raw && !sanitized.is_empty() {
+ return sanitized;
+ }
+ let digest = Sha256::digest(raw.as_bytes());
+ let suffix = digest[..6]
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect::<String>();
+ format!("{sanitized}-{suffix}")
+}
+
+/// Next free sequence number for a session: one past the highest `NNNNNN.md`
+/// already on disk (or 0 when the directory is empty/missing).
+fn next_seq(dir: &Path) -> u32 {
+ let mut max = -1i64;
+ if let Ok(rd) = fs::read_dir(dir) {
+ for entry in rd.flatten() {
+ let name = entry.file_name();
+ let s = name.to_string_lossy();
+ if let Some(stem) = s.strip_suffix(".md") {
+ if let Ok(n) = stem.parse::<i64>() {
+ if n > max {
+ max = n;
+ }
+ }
+ }
+ }
+ }
+ (max + 1) as u32
+}
+
+/// Render a turn as a YAML front-matter block followed by its body.
+///
+/// Key order, the two optional keys' omission when absent, the blank line
+/// after the closing `---`, and the appended newline for a body that lacks one
+/// are all load-bearing: they are the format every archived turn already on
+/// disk was written in, and [`parse_turn`] reads back.
+fn compose_turn(turn: &ArchivedTurn) -> String {
+ let mut yaml = String::from("---\n");
+ yaml.push_str(&format!("session_id: {}\n", yaml_escape(&turn.session_id)));
+ yaml.push_str(&format!("seq: {}\n", turn.seq));
+ yaml.push_str(&format!("timestamp_ms: {}\n", turn.timestamp_ms));
+ yaml.push_str(&format!("role: {}\n", yaml_escape(&turn.role)));
+ yaml.push_str(&format!("cost_microdollars: {}\n", turn.cost_microdollars));
+ if let Some(lesson) = turn.lesson.as_ref() {
+ yaml.push_str(&format!("lesson: {}\n", yaml_escape(lesson)));
+ }
+ if let Some(tc) = turn.tool_calls_json.as_ref() {
+ yaml.push_str(&format!("tool_calls_json: {}\n", yaml_escape(tc)));
+ }
+ yaml.push_str("---\n\n");
+ yaml.push_str(&turn.content);
+ if !turn.content.ends_with('\n') {
+ yaml.push('\n');
+ }
+ yaml
+}
+
+/// Encode a string as a JSON string literal. JSON quoted scalars are valid
+/// YAML, and serde's encoder correctly escapes newlines and every control
+/// character that must not appear literally in front matter.
+fn yaml_escape(s: &str) -> String {
+ serde_json::to_string(s).expect("serializing a string cannot fail")
+}
+
+/// Append a turn to its session's archive under `workspace`. Returns the
+/// assigned `seq`.
+///
+/// `turn.seq` is ignored on input — the on-disk directory is the source of
+/// truth and the returned [`ArchivedTurn`] carries the actually-assigned seq.
+/// [`super::hook_impl`] threads that seq into the segment ops, which pair it
+/// with the FTS5 episodic id, so the value returned here is the identity a
+/// segment is later selected by.
+pub(super) fn record_turn(workspace: &Path, mut turn: ArchivedTurn) -> Result<ArchivedTurn> {
+ let dir = session_dir(workspace, &turn.session_id);
+ fs::create_dir_all(&dir).with_context(|| format!("failed to mkdir -p {}", dir.display()))?;
+ loop {
+ turn.seq = next_seq(&dir);
+ let path = dir.join(format!("{:06}.md", turn.seq));
+ let bytes = compose_turn(&turn).into_bytes();
+ match write_if_new(&path, &bytes) {
+ Ok(true) => return Ok(turn),
+ // Another writer may have claimed the sequence after `next_seq`.
+ // `write_if_new` uses create-new semantics, so retrying computes a
+ // fresh sequence without ever overwriting the winning turn.
+ Ok(false) => continue,
+ Err(_) if path.exists() => continue,
+ Err(err) => {
+ return Err(err)
+ .with_context(|| format!("failed to write episodic turn {}", path.display()))
+ }
+ }
+ }
+}
+
+/// Read every turn for `session_id`, sorted by seq ascending. A missing session
+/// directory yields an empty vec.
+pub(super) fn session_entries(workspace: &Path, session_id: &str) -> Result<Vec<ArchivedTurn>> {
+ let dir = session_dir(workspace, session_id);
+ if !dir.exists() {
+ return Ok(Vec::new());
+ }
+ let mut files: Vec<(u32, PathBuf)> = fs::read_dir(&dir)
+ .with_context(|| format!("failed to read_dir {}", dir.display()))?
+ .filter_map(|e| e.ok())
+ .filter_map(|e| {
+ let name = e.file_name();
+ let s = name.to_string_lossy();
+ let stem = s.strip_suffix(".md")?;
+ let seq = stem.parse::<u32>().ok()?;
+ Some((seq, e.path()))
+ })
+ .collect();
+ files.sort_by_key(|(seq, _)| *seq);
+ let mut out = Vec::with_capacity(files.len());
+ for (_, path) in files {
+ let bytes =
+ fs::read(&path).with_context(|| format!("failed to read {}", path.display()))?;
+ let text = String::from_utf8_lossy(&bytes);
+ if let Some(turn) = parse_turn(&text) {
+ out.push(turn);
+ }
+ }
+ Ok(out)
+}
+
+/// Parse a front-matter + body md file back into an [`ArchivedTurn`].
+///
+/// Returns `None` for a file that is not front-matter shaped at all. A file
+/// that *is* but carries an unparseable scalar keeps the field's default
+/// rather than dropping the turn — a malformed cost must not lose the prose.
+fn parse_turn(text: &str) -> Option<ArchivedTurn> {
+ let body_start = text.strip_prefix("---\n")?;
+ let end = body_start.find("\n---\n")?;
+ let (yaml, rest) = body_start.split_at(end);
+ let body = rest.strip_prefix("\n---\n").unwrap_or(rest).to_string();
+ let mut turn = ArchivedTurn::default();
+ for line in yaml.lines() {
+ let Some((k, v)) = line.split_once(':') else {
+ continue;
+ };
+ let k = k.trim();
+ let v = v.trim();
+ let v_unquoted = serde_json::from_str::<String>(v).unwrap_or_else(|_| v.to_string());
+ match k {
+ "session_id" => turn.session_id = v_unquoted,
+ "seq" => turn.seq = v_unquoted.parse().unwrap_or(0),
+ "timestamp_ms" => turn.timestamp_ms = v_unquoted.parse().unwrap_or(0),
+ "role" => turn.role = v_unquoted,
+ "cost_microdollars" => turn.cost_microdollars = v_unquoted.parse().unwrap_or(0),
+ "lesson" => turn.lesson = Some(v_unquoted),
+ "tool_calls_json" => turn.tool_calls_json = Some(v_unquoted),
+ _ => {}
+ }
+ }
+ // Strip the single blank line compose() writes between the closing `---\n`
+ // and the body, then trim the trailing newline. Internal blank lines in the
+ // body are preserved.
+ turn.content = body
+ .strip_prefix('\n')
+ .unwrap_or(body.as_str())
+ .trim_end()
+ .to_string();
+ Some(turn)
+}
+
+/// Write `bytes` atomically to `abs_path` if the file does not already exist.
+///
+/// Returns `Ok(true)` when newly written, `Ok(false)` when it already existed.
+///
+/// **Immutability contract**: once a file exists at `abs_path` it is never
+/// overwritten. [`record_turn`]'s retry loop depends on that being enforced by
+/// the filesystem rather than by the `exists()` check above it — two writers
+/// can compute the same `next_seq` before either has published, and only a
+/// create-new publish makes the loser observable as a loser.
+fn write_if_new(abs_path: &Path, bytes: &[u8]) -> Result<bool> {
+ use std::io::Write;
+
+ if abs_path.exists() {
+ return Ok(false);
+ }
+
+ let parent = abs_path.parent().unwrap_or_else(|| Path::new("."));
+ std::fs::create_dir_all(parent)
+ .map_err(|e| anyhow::anyhow!("create_dir_all {:?}: {e}", parent))?;
+
+ let tmp_name = format!(".tmp_{}.md", uuid::Uuid::new_v4().simple());
+ let tmp_path = parent.join(&tmp_name);
+
+ {
+ let mut f = std::fs::File::create(&tmp_path)
+ .map_err(|e| anyhow::anyhow!("create tempfile {:?}: {e}", tmp_path))?;
+ f.write_all(bytes)
+ .map_err(|e| anyhow::anyhow!("write tempfile {:?}: {e}", tmp_path))?;
+ f.sync_all()
+ .map_err(|e| anyhow::anyhow!("fsync tempfile {:?}: {e}", tmp_path))?;
+ }
+
+ // Publish without replacement. A sibling hard link is atomic and fails
+ // with AlreadyExists when another writer won the same destination; plain
+ // `rename` cannot provide this contract because it replaces the target on
+ // Unix.
+ match std::fs::hard_link(&tmp_path, abs_path) {
+ Ok(()) => {
+ let _ = std::fs::remove_file(&tmp_path);
+ // fsync the parent directory so the rename is durable across a crash.
+ #[cfg(unix)]
+ if let Some(parent) = abs_path.parent() {
+ if let Ok(dir) = std::fs::File::open(parent) {
+ let _ = dir.sync_all();
+ }
+ }
+ Ok(true)
+ }
+ Err(e) => {
+ let _ = std::fs::remove_file(&tmp_path);
+ if abs_path.exists() {
+ // Lost the race — another writer created the file first.
+ Ok(false)
+ } else {
+ Err(anyhow::anyhow!(
+ "filesystem does not support required atomic hard-link publish {:?} -> {:?}: {e}",
+ tmp_path,
+ abs_path
+ ))
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "store_tests.rs"]
+mod tests;
diff --git a/src/openhuman/agent/harness/archivist/store_tests.rs b/src/openhuman/agent/harness/archivist/store_tests.rs
new file mode 100644
index 0000000000..b9d3880739
--- /dev/null
+++ b/src/openhuman/agent/harness/archivist/store_tests.rs
@@ -0,0 +1,349 @@
+//! Tests for the archivist's md-backed episodic capture store.
+//!
+//! Two halves, and the second one is the point.
+//!
+//! The first half is the behaviour suite the store came home with: round
+//! trips, sequence assignment, concurrent writers, session isolation.
+//!
+//! The second half is the **migration proof**. This store was moved out of
+//! `tinycortex` and back, and every turn any user has ever archived is already
+//! on disk in the format the engine's copy wrote. "The port is faithful" is
+//! therefore not a claim to assert, it is a claim to *check against the thing
+//! being replaced* — so [`derived_paths_and_bytes_match_the_engine_store`]
+//! writes the same turns through both implementations into two workspaces and
+//! compares the resulting trees byte for byte, and the two cross-read tests
+//! pin that each implementation reads the other's files.
+//!
+//! The engine stays a `dev-dependency` for exactly this kind of fixture, which
+//! is why naming `tinycortex` here is fine while naming it in `hook_impl.rs`
+//! is the thing being removed.
+
+use super::*;
+use std::collections::BTreeMap;
+use tempfile::TempDir;
+
+fn turn(session: &str, role: &str, content: &str) -> ArchivedTurn {
+ ArchivedTurn {
+ session_id: session.into(),
+ seq: 0,
+ timestamp_ms: 1_700_000_000_000,
+ role: role.into(),
+ content: content.into(),
+ lesson: None,
+ tool_calls_json: None,
+ cost_microdollars: 0,
+ }
+}
+
+#[test]
+fn round_trip_single_turn() {
+ let tmp = TempDir::new().unwrap();
+ let stored = record_turn(tmp.path(), turn("s1", "user", "hello world")).unwrap();
+ assert_eq!(stored.seq, 0);
+ let read = session_entries(tmp.path(), "s1").unwrap();
+ assert_eq!(read.len(), 1);
+ assert_eq!(read[0].content, "hello world");
+ assert_eq!(read[0].role, "user");
+ assert_eq!(read[0].session_id, "s1");
+ assert_eq!(read[0].seq, 0);
+}
+
+#[test]
+fn append_increments_seq() {
+ let tmp = TempDir::new().unwrap();
+ let a = record_turn(tmp.path(), turn("s1", "user", "one")).unwrap();
+ let b = record_turn(tmp.path(), turn("s1", "assistant", "two")).unwrap();
+ let c = record_turn(tmp.path(), turn("s1", "user", "three")).unwrap();
+ assert_eq!((a.seq, b.seq, c.seq), (0, 1, 2));
+ let read = session_entries(tmp.path(), "s1").unwrap();
+ assert_eq!(
+ read.iter().map(|t| t.seq).collect::<Vec<_>>(),
+ vec![0, 1, 2]
+ );
+ assert_eq!(read[1].role, "assistant");
+ assert_eq!(read[2].content, "three");
+}
+
+#[test]
+fn concurrent_record_turn_retries_sequence_collisions_without_loss() {
+ let tmp = TempDir::new().unwrap();
+ let writers = 24;
+ let barrier = std::sync::Arc::new(std::sync::Barrier::new(writers));
+ let mut threads = Vec::new();
+ for index in 0..writers {
+ let workspace = tmp.path().to_path_buf();
+ let barrier = barrier.clone();
+ threads.push(std::thread::spawn(move || {
+ barrier.wait();
+ record_turn(&workspace, turn("shared", "user", &format!("turn-{index}"))).unwrap()
+ }));
+ }
+ let mut assigned = Vec::new();
+ for thread in threads {
+ assigned.push(thread.join().unwrap().seq);
+ }
+ assigned.sort_unstable();
+ assert_eq!(assigned, (0..writers as u32).collect::<Vec<_>>());
+
+ let entries = session_entries(tmp.path(), "shared").unwrap();
+ assert_eq!(entries.len(), writers);
+ let contents: std::collections::HashSet<_> =
+ entries.into_iter().map(|entry| entry.content).collect();
+ assert_eq!(contents.len(), writers);
+}
+
+#[test]
+fn missing_session_returns_empty() {
+ let tmp = TempDir::new().unwrap();
+ assert!(session_entries(tmp.path(), "never").unwrap().is_empty());
+}
+
+#[test]
+fn preserves_lesson_and_tool_calls() {
+ let tmp = TempDir::new().unwrap();
+ let mut t = turn("s1", "assistant", "did the thing");
+ t.lesson = Some("be careful with X: it bites".into());
+ t.tool_calls_json = Some(r#"[{"name":"bash","args":{"cmd":"ls"}}]"#.into());
+ t.cost_microdollars = 1234;
+ record_turn(tmp.path(), t.clone()).unwrap();
+ let read = session_entries(tmp.path(), "s1").unwrap();
+ assert_eq!(
+ read[0].lesson.as_deref(),
+ Some("be careful with X: it bites")
+ );
+ assert_eq!(
+ read[0].tool_calls_json.as_deref(),
+ Some(r#"[{"name":"bash","args":{"cmd":"ls"}}]"#)
+ );
+ assert_eq!(read[0].cost_microdollars, 1234);
+}
+
+#[test]
+fn front_matter_round_trips_multiline_and_delimiter_like_scalars() {
+ let tmp = TempDir::new().unwrap();
+ let mut t = turn("session:one", "assistant\nadmin", "body stays separate");
+ t.lesson = Some("first line\n---\nsecond: line\\tail".into());
+ record_turn(tmp.path(), t.clone()).unwrap();
+
+ let read = session_entries(tmp.path(), &t.session_id).unwrap();
+ assert_eq!(read.len(), 1);
+ assert_eq!(read[0].session_id, t.session_id);
+ assert_eq!(read[0].role, t.role);
+ assert_eq!(read[0].lesson, t.lesson);
+ assert_eq!(read[0].content, t.content);
+}
+
+#[test]
+fn unsafe_session_ids_have_collision_resistant_directories() {
+ let tmp = TempDir::new().unwrap();
+ record_turn(tmp.path(), turn("a/b", "user", "slash")).unwrap();
+ record_turn(tmp.path(), turn("a?b", "user", "question")).unwrap();
+
+ assert_eq!(
+ session_entries(tmp.path(), "a/b").unwrap()[0].content,
+ "slash"
+ );
+ assert_eq!(
+ session_entries(tmp.path(), "a?b").unwrap()[0].content,
+ "question"
+ );
+}
+
+#[test]
+fn distinct_sessions_dont_mix() {
+ let tmp = TempDir::new().unwrap();
+ record_turn(tmp.path(), turn("a", "user", "hi a")).unwrap();
+ record_turn(tmp.path(), turn("b", "user", "hi b")).unwrap();
+ record_turn(tmp.path(), turn("a", "user", "more a")).unwrap();
+ let a = session_entries(tmp.path(), "a").unwrap();
+ let b = session_entries(tmp.path(), "b").unwrap();
+ assert_eq!(a.len(), 2);
+ assert_eq!(b.len(), 1);
+ assert_eq!(b[0].content, "hi b");
+}
+
+/// The literal path an archived turn lands at, spelled out rather than
+/// derived, so a change to `content_root` / the `{:06}` filename fails here
+/// instead of silently orphaning every existing archive.
+#[test]
+fn derived_path_is_the_documented_one() {
+ let tmp = TempDir::new().unwrap();
+ record_turn(tmp.path(), turn("sess-1", "user", "hi")).unwrap();
+ let expected = tmp
+ .path()
+ .join("memory_tree")
+ .join("content")
+ .join("episodic")
+ .join("sess-1")
+ .join("000000.md");
+ assert!(expected.is_file(), "expected {}", expected.display());
+}
+
+// ── Engine-equivalence: the migration proof ──────────────────────────────────
+
+/// The turns both implementations are driven with. Deliberately covers every
+/// branch the on-disk bytes can take: the two optional front-matter keys
+/// present and absent, a body with and without a trailing newline, a scalar
+/// that has to be escaped, a session id that has to be sanitised, and a
+/// non-zero cost.
+fn equivalence_fixtures() -> Vec<ArchivedTurn> {
+ let mut with_extras = turn("sess-a", "assistant", "did the thing");
+ with_extras.lesson = Some("careful: it\nbites\n---\nstill".into());
+ with_extras.tool_calls_json = Some(r#"[{"name":"bash","args":{"cmd":"ls"}}]"#.into());
+ with_extras.cost_microdollars = 4_242;
+
+ let mut trailing_newline = turn("sess-a", "user", "body already ends in a newline\n");
+ trailing_newline.timestamp_ms = -1;
+
+ vec![
+ turn("sess-a", "user", "plain body"),
+ with_extras,
+ trailing_newline,
+ turn("weird/id?x", "user", "sanitised session directory"),
+ turn("", "system", "empty session id"),
+ turn(
+ "s\u{00e9}ance-\u{4e2d}\u{6587}",
+ "user",
+ "unicode session id",
+ ),
+ ]
+}
+
+/// Same shape as [`ArchivedTurn`], on the engine's type, so both stores are
+/// driven with the identical payload.
+fn to_engine(turn: &ArchivedTurn) -> tinycortex::memory::archivist::types::ArchivedTurn {
+ tinycortex::memory::archivist::types::ArchivedTurn {
+ session_id: turn.session_id.clone(),
+ seq: turn.seq,
+ timestamp_ms: turn.timestamp_ms,
+ role: turn.role.clone(),
+ content: turn.content.clone(),
+ lesson: turn.lesson.clone(),
+ tool_calls_json: turn.tool_calls_json.clone(),
+ cost_microdollars: turn.cost_microdollars,
+ }
+}
+
+/// Every file under `root`, keyed by its path relative to `root` (forward
+/// slashes) and valued by its exact bytes.
+fn tree_snapshot(root: &Path) -> BTreeMap<String, Vec<u8>> {
+ fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ walk(&path, root, out);
+ } else {
+ let rel = path
+ .strip_prefix(root)
+ .expect("walked path is under root")
+ .components()
+ .map(|c| c.as_os_str().to_string_lossy().into_owned())
+ .collect::<Vec<_>>()
+ .join("/");
+ out.insert(rel, std::fs::read(&path).unwrap());
+ }
+ }
+ }
+ let mut out = BTreeMap::new();
+ walk(root, root, &mut out);
+ out
+}
+
+/// **The load-bearing test.** Drive both implementations with the same turns
+/// into two workspaces and assert the resulting trees are identical — same
+/// relative paths, same bytes. A one-character difference in the front matter,
+/// the filename width, the sanitiser's digest, or the content root fails here.
+#[test]
+fn derived_paths_and_bytes_match_the_engine_store() {
+ let host_ws = TempDir::new().unwrap();
+ let engine_ws = TempDir::new().unwrap();
+ let engine_cfg = tinycortex::memory::MemoryConfig::new(engine_ws.path().to_path_buf());
+
+ for fixture in equivalence_fixtures() {
+ let host_seq = record_turn(host_ws.path(), fixture.clone()).unwrap().seq;
+ let engine_seq =
+ tinycortex::memory::archivist::store::record_turn(&engine_cfg, to_engine(&fixture))
+ .unwrap()
+ .seq;
+ assert_eq!(
+ host_seq, engine_seq,
+ "assigned seq diverged for session {:?}",
+ fixture.session_id
+ );
+ }
+
+ let host_tree = tree_snapshot(host_ws.path());
+ let engine_tree = tree_snapshot(engine_ws.path());
+
+ assert!(
+ !host_tree.is_empty(),
+ "snapshot is empty — the walker, not the store, is what this would be testing"
+ );
+ assert_eq!(
+ host_tree.keys().collect::<Vec<_>>(),
+ engine_tree.keys().collect::<Vec<_>>(),
+ "derived on-disk paths diverged from the engine store"
+ );
+ for (path, host_bytes) in &host_tree {
+ assert_eq!(
+ String::from_utf8_lossy(host_bytes),
+ String::from_utf8_lossy(&engine_tree[path]),
+ "file contents diverged from the engine store at {path}"
+ );
+ }
+}
+
+/// Turns already on disk — written by the engine's copy before the move — must
+/// read back through the store that replaced it. This is the upgrade path.
+#[test]
+fn reads_back_turns_the_engine_store_wrote() {
+ let workspace = TempDir::new().unwrap();
+ let engine_cfg = tinycortex::memory::MemoryConfig::new(workspace.path().to_path_buf());
+ for fixture in equivalence_fixtures() {
+ tinycortex::memory::archivist::store::record_turn(&engine_cfg, to_engine(&fixture))
+ .unwrap();
+ }
+
+ for fixture in equivalence_fixtures() {
+ let read = session_entries(workspace.path(), &fixture.session_id).unwrap();
+ let found = read
+ .iter()
+ .find(|t| t.content == fixture.content.trim_end())
+ .unwrap_or_else(|| panic!("no engine-written turn matched {:?}", fixture.content));
+ assert_eq!(found.session_id, fixture.session_id);
+ assert_eq!(found.role, fixture.role);
+ assert_eq!(found.lesson, fixture.lesson);
+ assert_eq!(found.tool_calls_json, fixture.tool_calls_json);
+ assert_eq!(found.cost_microdollars, fixture.cost_microdollars);
+ assert_eq!(found.timestamp_ms, fixture.timestamp_ms);
+ }
+}
+
+/// And the other direction: a rollback, or a workspace shared with any engine
+/// build still running the old code, must still read what this store wrote.
+#[test]
+fn the_engine_store_reads_back_turns_this_store_wrote() {
+ let workspace = TempDir::new().unwrap();
+ for fixture in equivalence_fixtures() {
+ record_turn(workspace.path(), fixture.clone()).unwrap();
+ }
+
+ let engine_cfg = tinycortex::memory::MemoryConfig::new(workspace.path().to_path_buf());
+ for fixture in equivalence_fixtures() {
+ let read =
+ tinycortex::memory::archivist::store::session_entries(&engine_cfg, &fixture.session_id)
+ .unwrap();
+ assert!(
+ read.iter().any(|t| t.content == fixture.content.trim_end()
+ && t.role == fixture.role
+ && t.lesson == fixture.lesson
+ && t.tool_calls_json == fixture.tool_calls_json
+ && t.cost_microdollars == fixture.cost_microdollars),
+ "the engine store could not read back {:?}",
+ fixture.content
+ );
+ }
+}
diff --git a/src/openhuman/agent/harness/session/builder/helpers.rs b/src/openhuman/agent/harness/session/builder/helpers.rs
index 7152479aa0..c205c4fada 100644
--- a/src/openhuman/agent/harness/session/builder/helpers.rs
+++ b/src/openhuman/agent/harness/session/builder/helpers.rs
@@ -1,4 +1,21 @@
//! Utility helpers used during agent construction.
+//!
+//! # A note on the store this reaches (#5560)
+//!
+//! [`tool_memory_store`] is host-side now — see
+//! [`memory::tool_memory::store`](crate::openhuman::memory::tool_memory::store)
+//! — where it used to be `tinycortex`'s. No call site changed, because the
+//! convention it applies (the `tool-<name>` namespace, the `rule/<id>` key, the
+//! record's serde) comes from the contract that both ends read.
+//!
+//! **Do not "modernise" this onto `active_memory_guard().as_tool_memory()`.**
+//! `memory` here is the session's own subtree — `DriverMemory::for_subtree`,
+//! resolved in `factory` from the profile's `memory_subdir` — so a profile with
+//! `dedicatedMemory` prefetches its own rules. The ambient guard is the
+//! *shared* tree, and routing this through it would quietly merge every
+//! profile's tool rules into one prompt. The correct family call is the one
+//! reached through this session's own `binding::for_subtree(..)`, which needs
+//! the subtree passed in rather than the memory object.
use crate::openhuman::memory::tool_memory::{tool_memory_store, ToolMemoryRule};
use crate::openhuman::memory::Memory;
diff --git a/src/openhuman/agent/harness/session/turn/mod.rs b/src/openhuman/agent/harness/session/turn/mod.rs
index d4dd82978a..801cfb3e32 100644
--- a/src/openhuman/agent/harness/session/turn/mod.rs
+++ b/src/openhuman/agent/harness/session/turn/mod.rs
@@ -187,8 +187,8 @@ pub(super) fn collect_tree_root_summaries(
.collect()
}
-/// Read TinyCortex root summaries from an already-resolved `memory-*` subtree.
-/// TinyCortex's compatibility helper hardcodes `<workspace>/memory`; dedicated
+/// Read summary-tree root summaries from an already-resolved `memory-*` subtree.
+/// The engine's compatibility helper hardcodes `<workspace>/memory`; dedicated
/// profiles instead supply `<workspace>/memory-<id>`, so scan that equivalent
/// namespace layout directly rather than falling back to shared memory.
fn collect_profile_tree_root_summaries(
@@ -204,10 +204,7 @@ fn collect_profile_tree_root_summaries(
.filter_map(|entry| {
let namespace = entry.file_name().to_string_lossy().into_owned();
let raw = std::fs::read_to_string(entry.path().join("tree").join("root.md")).ok()?;
- let node = tinycortex::memory::tree::runtime::store::parse_node_markdown_pub(
- &raw, &namespace, "root",
- )
- .ok()?;
+ let node = parse_node_markdown(&raw, &namespace, "root");
Some((namespace, node))
})
.collect();
@@ -239,6 +236,151 @@ fn collect_profile_tree_root_summaries(
out
}
+/// Parse one summary-tree node's markdown file into a [`TreeNode`].
+///
+/// # Why this lives here rather than being called on the engine (#5560)
+///
+/// This is a verbatim port of `tinycortex`'s
+/// `memory::tree::runtime::store::parse_node_markdown`, which
+/// [`collect_profile_tree_root_summaries`] used to reach through
+/// `parse_node_markdown_pub`. It is brought home rather than routed at the
+/// module contract because there is nothing on the contract to route it *at*:
+/// `MemoryTree` is namespace-addressed and its summary members answer from the
+/// driver's own store, whereas this reads a `root.md` **the driver does not
+/// own** — a dedicated profile's `<workspace>/memory-<id>/namespaces/…` tree,
+/// which is exactly the subtree the engine's compatibility helper skips
+/// because it hardcodes `<workspace>/memory`. A bus round-trip cannot answer a
+/// question about a file the far end never opened.
+///
+/// It has no engine coupling to give up: every name it needs — [`TreeNode`],
+/// [`NodeLevel::from_str_label`], [`level_from_node_id`], [`derive_parent_id`]
+/// and [`estimate_tokens`] — is **contract** vocabulary, defined in
+/// `tinymemory-bus` and reached here through
+/// [`crate::openhuman::memory::api::tree`]. The engine crate re-exported the
+/// same items, so the types this produces are the same types it produced
+/// before, not host look-alikes.
+///
+/// # Two faithfulness notes for a reviewer
+///
+/// - **The engine's signature was `Result<TreeNode>`; this one is not.** Its
+/// body contains no `?` and no `Err` construction — every field falls back
+/// to a derived or default value, which is the documented point of it ("does
+/// not fail on malformed frontmatter", which is also what lets a truncated
+/// write go undetected). So the `.ok()?` the call site used could never skip
+/// a namespace, and dropping the `Result` changes no behaviour. Restore the
+/// `Result` if this ever grows a genuine failure.
+/// - **Timestamps fall back to `UNIX_EPOCH`, not to `now()`**, and
+/// `updated_at` falls back to `created_at` rather than to the epoch
+/// independently. `collect_profile_tree_root_summaries` returns
+/// `node.updated_at` straight to the prompt builder, so a node with no
+/// frontmatter reports 1970 — deliberately, since a missing timestamp
+/// sorting as "just updated" would be worse.
+fn parse_node_markdown(
+ raw: &str,
+ namespace: &str,
+ node_id: &str,
+) -> crate::openhuman::memory::api::tree::TreeNode {
+ use crate::openhuman::memory::api::tree::{
+ derive_parent_id, estimate_tokens, level_from_node_id, NodeLevel, TreeNode,
+ };
+ use chrono::{DateTime, Utc};
+
+ let (frontmatter, body_raw) = split_frontmatter(raw);
+ let body = body_raw.trim_end().to_string();
+
+ let level = frontmatter
+ .get("level")
+ .and_then(|v| NodeLevel::from_str_label(v))
+ .unwrap_or_else(|| level_from_node_id(node_id));
+ let parent_id = frontmatter
+ .get("parent_id")
+ .and_then(|v| {
+ let trimmed = v.trim().trim_matches('"');
+ if trimmed == "~" || trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }
+ })
+ .or_else(|| derive_parent_id(node_id));
+ let token_count = frontmatter
+ .get("token_count")
+ .and_then(|v| v.parse::<u32>().ok())
+ .unwrap_or_else(|| estimate_tokens(&body));
+ let child_count = frontmatter
+ .get("child_count")
+ .and_then(|v| v.parse::<u32>().ok())
+ .unwrap_or(0);
+ let created_at = frontmatter
+ .get("created_at")
+ .and_then(|v| DateTime::parse_from_rfc3339(v).ok())
+ .map(|dt| dt.with_timezone(&Utc))
+ .unwrap_or(DateTime::<Utc>::UNIX_EPOCH);
+ let updated_at = frontmatter
+ .get("updated_at")
+ .and_then(|v| DateTime::parse_from_rfc3339(v).ok())
+ .map(|dt| dt.with_timezone(&Utc))
+ .unwrap_or(created_at);
+ let metadata = frontmatter.get("metadata").map(|v| v.to_string());
+
+ TreeNode {
+ node_id: node_id.to_string(),
+ namespace: namespace.to_string(),
+ level,
+ parent_id,
+ summary: body,
+ token_count,
+ child_count,
+ created_at,
+ updated_at,
+ metadata,
+ }
+}
+
+/// Split markdown into a (frontmatter key-value map, body text) pair.
+///
+/// Ported alongside [`parse_node_markdown`] — it is that function's only
+/// helper and is `pub(crate)` in the engine for the engine's own callers, none
+/// of which exist here.
+///
+/// Looks for a leading `---` fence and the first subsequent `\n---`; each
+/// `key: value` line in between is parsed with a single `find(':')` split
+/// (values are trimmed and unwrapped of one layer of surrounding `"`). If the
+/// content doesn't start with `---`, or no closing fence is found, the whole
+/// input is returned unmodified as the body with an empty map — this function
+/// never errors, it degrades to "no frontmatter" instead. That degradation is
+/// what makes [`parse_node_markdown`] total.
+fn split_frontmatter(raw: &str) -> (std::collections::HashMap<String, String>, String) {
+ let mut map = std::collections::HashMap::new();
+ let trimmed = raw.trim_start();
+ if !trimmed.starts_with("---") {
+ return (map, raw.to_string());
+ }
+ let after_open = &trimmed[3..];
+ if let Some(close_pos) = after_open.find("\n---") {
+ let fm_block = &after_open[..close_pos];
+ let body = after_open[close_pos + 4..]
+ .trim_start_matches('\n')
+ .to_string();
+ for line in fm_block.lines() {
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+ if let Some(colon_pos) = line.find(':') {
+ let key = line[..colon_pos].trim().to_string();
+ let raw_value = line[colon_pos + 1..].trim();
+ let value = serde_json::from_str::<String>(raw_value)
+ .unwrap_or_else(|_| raw_value.trim_matches('"').to_string());
+ map.insert(key, value);
+ }
+ }
+ (map, body)
+ } else {
+ (map, raw.to_string())
+ }
+}
+
/// Sanitize a learned memory entry before injecting into the system prompt.
/// Strips raw data, limits length, and removes potential secrets.
pub(super) fn sanitize_learned_entry(content: &str) -> String {
diff --git a/src/openhuman/agent/harness/subagent_runner/ops/graph_part_02.rs b/src/openhuman/agent/harness/subagent_runner/ops/graph_part_02.rs
index 08c129256b..0d01d0e379 100644
--- a/src/openhuman/agent/harness/subagent_runner/ops/graph_part_02.rs
+++ b/src/openhuman/agent/harness/subagent_runner/ops/graph_part_02.rs
@@ -1,4 +1,3 @@
-
/// Persist a **failed** sub-agent run (#4466): write whatever rounds the live
/// transcript-snapshot middleware captured before the harness error to
/// `session_raw` (so `learning/transcript_ingest` can still ingest a failed run,
@@ -53,7 +52,7 @@ fn persist_failed_run(
}
}
-/// Append a worker-thread [`StoredMessage`](tinycortex::memory::conversations::ConversationMessage)
+/// Append a worker-thread [`StoredMessage`](crate::openhuman::memory::conversations::ConversationMessage)
/// with the restored legacy [`SubagentObserver`] metadata (#4466): `scope`,
/// `agent_id`, `task_id`, plus the per-message `iteration`, `final`, `mode`, and
/// (for assistant tool rounds / tool results) `tool_calls` / `tool_call_id` /
@@ -69,7 +68,9 @@ fn append_worker_message(
sender: &str,
metadata: serde_json::Value,
) {
- use tinycortex::memory::conversations::{append_message, ConversationMessage as StoredMessage};
+ use crate::openhuman::memory::conversations::{
+ append_message, ConversationMessage as StoredMessage,
+ };
let mut extra = serde_json::json!({
"scope": "worker_thread",
"agent_id": agent_id,
diff --git a/src/openhuman/agent/learning/candidate.rs b/src/openhuman/agent/learning/candidate.rs
index b3137b7ac7..7ea2562537 100644
--- a/src/openhuman/agent/learning/candidate.rs
+++ b/src/openhuman/agent/learning/candidate.rs
@@ -1,32 +1,48 @@
//! Learning candidates — observations the stability detector may promote into
//! durable profile facts.
//!
-//! The definitions **moved to `tinymemory_core::learning_candidate`** during
-//! the memory extraction. The queue is a process-global that the memory side
-//! *pushes into* — the Composio provider-profile sync emits an identity
-//! candidate on every run — while the agent's learning loop drains it. Two
-//! copies of that global, one per crate, would mean the producer and the
-//! consumer never seeing the same queue.
+//! Two halves live here, and they arrived from different places:
//!
-//! It could not go in `tinymemory-api`, which stays dependency-light;
-//! the queue needs `parking_lot`. [`EvidenceRef`] *is* in the contract crate,
-//! because the memory store persists it — see
-//! [`tinymemory_api::host::EvidenceRef`].
+//! - the **taxonomy** ([`FacetClass`], [`CueFamily`], [`LearningCandidate`],
+//! [`EvidenceRef`]) is defined in `tinymemory-api`, the contract crate the
+//! host and the loadable memory module both compile against, and is
+//! re-exported below so the ~30 call sites that already spell
+//! `candidate::FacetClass` keep resolving;
+//! - the **buffer** ([`Buffer`] and its [`global`] singleton) is this process's
+//! own, and is defined here.
//!
-//! Every existing `agent::learning::candidate::…` path keeps resolving.
+//! # Why the buffer came home (#5560)
//!
-//! # The two halves, named apart (#5560)
+//! It used to be `pub use tinymemory_core::learning_candidate::*;` — the last
+//! line in this file that named the memory engine, and therefore a compile-time
+//! link to it bought for a `VecDeque` behind a `parking_lot::Mutex`. The engine
+//! crate's own module docs explain why the type could not follow the taxonomy
+//! down into `tinymemory-api`: **a `static` is not a payload.** The contract
+//! crate is compiled into both the host binary and the module `cdylib`, so
+//! moving `global()` there would not give the two sides one queue, it would
+//! give them two.
//!
-//! The glob below carried both, which made a contract type and a process-global
-//! look like one engine import. They are not the same ask:
+//! That is exactly why moving the definition *up* into the host is free. The
+//! split it looks like it might create is **already live and cannot be closed
+//! by a re-export**: the one producer inside the memory workspace is
+//! `sync::composio::providers::profile`, which runs inside the module and
+//! pushes into the module's copy of the static; the host's stability detector
+//! drains the host's copy. Every producer in *this* process —
+//! `learning::extract::heuristics`, `extract::summary_facets`,
+//! `extract::signature`, `learning::reflection` — reaches the buffer through
+//! `candidate::global()`, i.e. through this file, and so does the only
+//! consumer, `learning::stability_detector`. Defining the static here keeps
+//! them on one buffer, which is the property that matters; delivering a
+//! candidate across the module boundary needs a bus member or an event, and is
+//! tracked upstream rather than papered over here.
//!
-//! - the **taxonomy** ([`FacetClass`], [`CueFamily`], [`LearningCandidate`],
-//! [`EvidenceRef`]) is defined in `tinymemory-api` and merely re-exported by
-//! the engine crate, so naming the contract is the same item under a shorter
-//! chain, and these paths survive `tinymemory-core` leaving the build with no
-//! edit at any of the ~30 call sites that spell them;
-//! - the **buffer** ([`Buffer`], `global()`) is a `static`, and a `static` is
-//! not a payload. It stays where it is defined.
+//! The capacity, the FIFO-overflow eviction and every method signature are
+//! carried over unchanged, so a producer that used to evict at 1024 still does.
+
+use std::collections::VecDeque;
+use std::sync::OnceLock;
+
+use parking_lot::Mutex;
// The taxonomy, on the contract crate. Named on `tinymemory_api` rather than
// through `memory::api`, which deliberately re-exports only what crosses the
@@ -36,9 +52,91 @@
pub use tinymemory_api::host::EvidenceRef;
pub use tinymemory_api::learning::{CueFamily, FacetClass, LearningCandidate};
-// The buffer, still the engine's. `tinymemory-api` is dependency-light by
-// contract and the queue needs `parking_lot`, so this cannot follow the types
-// down — and it is the line that keeps this file on the direct-reference
-// allowlist. An explicit `use` shadows a glob, so the four names above win over
-// the identical ones this would supply.
-pub use tinymemory_core::learning_candidate::*;
+// ── Buffer ───────────────────────────────────────────────────────────────────
+
+/// Thread-safe, bounded ring-buffer of [`LearningCandidate`] items.
+///
+/// Backed by a `parking_lot::Mutex<VecDeque<LearningCandidate>>`. When full the
+/// oldest entry is evicted to make room (FIFO overflow), which keeps memory
+/// bounded and naturally prioritises recent evidence.
+///
+/// [`global`] is the singleton every producer in this process pushes into and
+/// the stability detector drains; tests build their own with [`Buffer::new`].
+pub struct Buffer {
+ inner: Mutex<VecDeque<LearningCandidate>>,
+ capacity: usize,
+}
+
+impl Buffer {
+ /// Create a new buffer with the given capacity.
+ ///
+ /// `capacity` must be ≥ 1. A capacity of zero would make every `push` a
+ /// silent no-op, so it is clamped rather than honoured.
+ pub fn new(capacity: usize) -> Self {
+ let cap = capacity.max(1);
+ Self {
+ inner: Mutex::new(VecDeque::with_capacity(cap)),
+ capacity: cap,
+ }
+ }
+
+ /// Push a candidate onto the buffer.
+ ///
+ /// If the buffer is already at capacity the oldest entry is evicted first
+ /// (FIFO overflow), so the buffer always reflects the most recent evidence.
+ pub fn push(&self, candidate: LearningCandidate) {
+ let mut guard = self.inner.lock();
+ if guard.len() >= self.capacity {
+ guard.pop_front(); // evict oldest
+ }
+ guard.push_back(candidate);
+ }
+
+ /// Drain all candidates from the buffer and return them in FIFO order.
+ ///
+ /// After this call the buffer is empty.
+ pub fn drain(&self) -> Vec<LearningCandidate> {
+ let mut guard = self.inner.lock();
+ guard.drain(..).collect()
+ }
+
+ /// Clone all candidates without removing them.
+ ///
+ /// Useful for inspection or debugging.
+ pub fn peek(&self) -> Vec<LearningCandidate> {
+ let guard = self.inner.lock();
+ guard.iter().cloned().collect()
+ }
+
+ /// Current number of candidates in the buffer.
+ pub fn len(&self) -> usize {
+ self.inner.lock().len()
+ }
+
+ /// Returns `true` when the buffer holds no candidates.
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ /// Maximum number of candidates the buffer will hold.
+ pub fn capacity(&self) -> usize {
+ self.capacity
+ }
+}
+
+// ── Global singleton ─────────────────────────────────────────────────────────
+
+static GLOBAL_BUFFER: OnceLock<Buffer> = OnceLock::new();
+
+/// Return the global [`Buffer`] singleton.
+///
+/// Initialised on first call with a capacity of 1024 — the same default the
+/// engine's copy carried, so a run that overflows evicts at the same point it
+/// did before this definition moved.
+pub fn global() -> &'static Buffer {
+ GLOBAL_BUFFER.get_or_init(|| Buffer::new(1024))
+}
+
+#[cfg(test)]
+#[path = "candidate_tests.rs"]
+mod tests;
diff --git a/src/openhuman/agent/learning/candidate_tests.rs b/src/openhuman/agent/learning/candidate_tests.rs
new file mode 100644
index 0000000000..38a378f5b7
--- /dev/null
+++ b/src/openhuman/agent/learning/candidate_tests.rs
@@ -0,0 +1,113 @@
+//! Tests for the surrounding module.
+//!
+//! These cover the ring-buffer this file owns, not the taxonomy it re-exports:
+//! `FacetClass`, `CueFamily`, `LearningCandidate` and `EvidenceRef` are
+//! `tinymemory-api`'s and are tested there. What is worth pinning here is the
+//! behaviour that came home with the buffer in #5560 — FIFO order, the
+//! overflow eviction, and `global()` being one instance — because a producer
+//! and the stability detector agreeing on a single queue is the whole reason
+//! the `static` lives in this crate rather than in the contract crate.
+
+use super::*;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+fn now_secs() -> f64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs_f64()
+}
+
+fn make_candidate(value: &str) -> LearningCandidate {
+ LearningCandidate {
+ class: FacetClass::Style,
+ key: "verbosity".into(),
+ value: value.into(),
+ cue_family: CueFamily::Explicit,
+ evidence: EvidenceRef::Episodic { episodic_id: 1 },
+ initial_confidence: 0.8,
+ observed_at: now_secs(),
+ }
+}
+
+#[test]
+fn push_then_drain_preserves_fifo_order() {
+ let buf = Buffer::new(10);
+ buf.push(make_candidate("a"));
+ buf.push(make_candidate("b"));
+ buf.push(make_candidate("c"));
+
+ let drained = buf.drain();
+ assert_eq!(drained.len(), 3);
+ assert_eq!(drained[0].value, "a");
+ assert_eq!(drained[1].value, "b");
+ assert_eq!(drained[2].value, "c");
+}
+
+#[test]
+fn drain_empties_the_buffer() {
+ let buf = Buffer::new(10);
+ buf.push(make_candidate("x"));
+ buf.push(make_candidate("y"));
+ assert_eq!(buf.len(), 2);
+
+ let _ = buf.drain();
+ assert_eq!(buf.len(), 0);
+ assert!(buf.is_empty());
+}
+
+#[test]
+fn bounded_capacity_evicts_oldest() {
+ let buf = Buffer::new(3);
+ buf.push(make_candidate("first"));
+ buf.push(make_candidate("second"));
+ buf.push(make_candidate("third"));
+ // Buffer is full — the next push evicts "first".
+ buf.push(make_candidate("fourth"));
+
+ assert_eq!(buf.len(), 3);
+ let items = buf.drain();
+ assert_eq!(items[0].value, "second");
+ assert_eq!(items[1].value, "third");
+ assert_eq!(items[2].value, "fourth");
+}
+
+#[test]
+fn peek_does_not_remove() {
+ let buf = Buffer::new(10);
+ buf.push(make_candidate("p"));
+ buf.push(make_candidate("q"));
+
+ let peeked = buf.peek();
+ assert_eq!(peeked.len(), 2);
+ // Buffer still holds the items.
+ assert_eq!(buf.len(), 2);
+
+ let drained = buf.drain();
+ assert_eq!(drained[0].value, "p");
+ assert_eq!(drained[1].value, "q");
+}
+
+/// A zero capacity would make every `push` a silent no-op — evidence collected
+/// and dropped with nothing to show for it — so it is clamped to one.
+#[test]
+fn zero_capacity_is_clamped_to_one() {
+ let buf = Buffer::new(0);
+ assert_eq!(buf.capacity(), 1);
+
+ buf.push(make_candidate("only"));
+ buf.push(make_candidate("newest"));
+
+ let items = buf.drain();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].value, "newest");
+}
+
+/// The producers and the stability detector must see one queue; a `global()`
+/// that handed out a fresh buffer would lose every candidate silently.
+#[test]
+fn global_returns_same_instance_across_calls() {
+ let a = global() as *const Buffer;
+ let b = global() as *const Buffer;
+ assert_eq!(a, b, "global() must return the same static instance");
+}
diff --git a/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs b/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs
index fbc0fdbf77..e81802f5bc 100644
--- a/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs
+++ b/src/openhuman/agent/orchestration/tools/spawn_async_subagent.rs
@@ -17,10 +17,10 @@ use crate::openhuman::agent::orchestration::subagent_sessions::{
SubagentSessionUpsert,
};
use crate::openhuman::agent::progress::AgentProgress;
+use crate::openhuman::memory::conversations::{self as conversations, ConversationMessage};
use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
use async_trait::async_trait;
use serde_json::json;
-use tinycortex::memory::conversations::{self as conversations, ConversationMessage};
use tinytools::ToolRunContext;
pub struct SpawnAsyncSubagentTool;
diff --git a/src/openhuman/agent/orchestration/tools/spawn_async_subagent_tests.rs b/src/openhuman/agent/orchestration/tools/spawn_async_subagent_tests.rs
index d26a3a09ca..c4209fa79c 100644
--- a/src/openhuman/agent/orchestration/tools/spawn_async_subagent_tests.rs
+++ b/src/openhuman/agent/orchestration/tools/spawn_async_subagent_tests.rs
@@ -161,7 +161,7 @@ fn extract_workflow_proposal_ignores_non_proposal_history() {
#[test]
fn attach_workflow_proposal_persists_thread_message_and_extends_summary() {
- use tinycortex::memory::conversations::CreateConversationThread;
+ use crate::openhuman::memory::conversations::CreateConversationThread;
let temp = tempfile::tempdir().expect("tempdir");
conversations::ensure_thread(
temp.path().to_path_buf(),
diff --git a/src/openhuman/agent/orchestration/tools/spawn_subagent.rs b/src/openhuman/agent/orchestration/tools/spawn_subagent.rs
index d1fcc1a532..49dde9395b 100644
--- a/src/openhuman/agent/orchestration/tools/spawn_subagent.rs
+++ b/src/openhuman/agent/orchestration/tools/spawn_subagent.rs
@@ -18,13 +18,13 @@ use crate::openhuman::agent::harness::subagent_runner::{
run_subagent, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,
};
use crate::openhuman::agent::progress::AgentProgress;
+use crate::openhuman::memory::conversations::{
+ self as conversations, ConversationMessage, CreateConversationThread,
+};
use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
use async_trait::async_trait;
use serde_json::json;
use std::path::PathBuf;
-use tinycortex::memory::conversations::{
- self as conversations, ConversationMessage, CreateConversationThread,
-};
use tinytools::ToolRunContext;
/// Spawns a sub-agent of the requested type to handle a delegated task.
diff --git a/src/openhuman/agent/orchestration/tools/spawn_worker_thread.rs b/src/openhuman/agent/orchestration/tools/spawn_worker_thread.rs
index efe55111c7..1298366bbc 100644
--- a/src/openhuman/agent/orchestration/tools/spawn_worker_thread.rs
+++ b/src/openhuman/agent/orchestration/tools/spawn_worker_thread.rs
@@ -12,10 +12,10 @@
use crate::openhuman::agent::harness::definition::AgentDefinitionRegistry;
use crate::openhuman::agent::harness::fork_context::current_parent;
use crate::openhuman::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions};
+use crate::openhuman::memory::conversations;
use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
use async_trait::async_trait;
use serde_json::json;
-use tinycortex::memory::conversations;
use tinytools::ToolRunContext;
/// Spawns a sub-agent in a dedicated worker thread.
diff --git a/src/openhuman/agent/orchestration/tools/spawn_worker_thread_tests.rs b/src/openhuman/agent/orchestration/tools/spawn_worker_thread_tests.rs
index c31044e09f..38aa01a7de 100644
--- a/src/openhuman/agent/orchestration/tools/spawn_worker_thread_tests.rs
+++ b/src/openhuman/agent/orchestration/tools/spawn_worker_thread_tests.rs
@@ -1,10 +1,10 @@
use super::*;
use crate::openhuman::agent::harness::fork_context::with_parent_context;
use crate::openhuman::agent::harness::ParentExecutionContext;
+use crate::openhuman::memory::conversations::CreateConversationThread;
use std::path::PathBuf;
use std::sync::Arc;
use tempfile::TempDir;
-use tinycortex::memory::conversations::CreateConversationThread;
struct MockMemory;
#[async_trait]
diff --git a/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs b/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs
index 138da84bfb..b3d39014dc 100644
--- a/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs
+++ b/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs
@@ -5,6 +5,7 @@ use crate::openhuman::agent::context::prompt::{ConnectedIntegration, ToolCallFor
use crate::openhuman::agent::harness::definition::AgentDefinitionRegistry;
use crate::openhuman::agent::harness::{with_parent_context, ParentExecutionContext};
use crate::openhuman::agent::messages::ChatMessage;
+use crate::openhuman::memory::conversations;
use crate::openhuman::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
use crate::openhuman::tools::Tool;
use async_trait::async_trait;
@@ -12,7 +13,6 @@ use parking_lot::Mutex;
use serde_json::json;
use std::path::Path;
use std::sync::Arc;
-use tinycortex::memory::conversations;
use tinyinference::message::Message;
use tinyinference::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
diff --git a/src/openhuman/agent/orchestration/tools/worker_thread.rs b/src/openhuman/agent/orchestration/tools/worker_thread.rs
index 5e177f9620..b62bb6f024 100644
--- a/src/openhuman/agent/orchestration/tools/worker_thread.rs
+++ b/src/openhuman/agent/orchestration/tools/worker_thread.rs
@@ -14,7 +14,7 @@ use std::path::PathBuf;
use serde_json::json;
-use tinycortex::memory::conversations::{
+use crate::openhuman::memory::conversations::{
self as conversations, ConversationMessage, CreateConversationThread,
};
diff --git a/src/openhuman/agent/task_session.rs b/src/openhuman/agent/task_session.rs
index bd00ac16e1..80c5e06dde 100644
--- a/src/openhuman/agent/task_session.rs
+++ b/src/openhuman/agent/task_session.rs
@@ -29,7 +29,7 @@ use std::path::PathBuf;
use serde_json::json;
use crate::openhuman::agent::task_board::TaskBoardCard;
-use tinycortex::memory::conversations::{
+use crate::openhuman::memory::conversations::{
self as conversations, ConversationMessage, CreateConversationThread,
};
diff --git a/src/openhuman/agent/tinyagents/host/agent_memory.rs b/src/openhuman/agent/tinyagents/host/agent_memory.rs
index e366aa5ffb..a0c567fd36 100644
--- a/src/openhuman/agent/tinyagents/host/agent_memory.rs
+++ b/src/openhuman/agent/tinyagents/host/agent_memory.rs
@@ -520,7 +520,7 @@ impl AgentMemory for OpenHumanAgentMemory {
/// "no summary" rather than concatenating recall output.
///
// TODO(phase4): if a real per-thread rollup lands (the natural home is a
- // summary column on `tinycortex::memory::conversations::ConversationThread`,
+ // summary column on `crate::openhuman::memory::conversations::ConversationThread`,
// or a thread-scoped digest in `memory_tree::summarise`), return it here.
async fn thread_summary(&self, _thread: &ThreadId) -> TaResult<Option<String>> {
Ok(None)
diff --git a/src/openhuman/agent/tinyagents/thread_context.rs b/src/openhuman/agent/tinyagents/thread_context.rs
index 398ff08993..4752c01823 100644
--- a/src/openhuman/agent/tinyagents/thread_context.rs
+++ b/src/openhuman/agent/tinyagents/thread_context.rs
@@ -1,35 +1,96 @@
//! Ambient chat-thread id for the current async scope.
//!
-//! The definition **moved to `tinymemory_core::thread_context`** during the
-//! memory extraction. The memory store is its heaviest consumer — recall has to
-//! exclude the thread it is being called from — and the task-local cannot be
-//! two different task-locals in two crates or the scope would not be visible
-//! across the seam.
-//!
-//! It could not go in `tinymemory-api`, which must not depend on an async
-//! runtime; `tokio::task_local!` needs one. Every existing
-//! `agent::tinyagents::thread_context::…` path keeps resolving and keeps
-//! naming the same task-local.
-//!
-//! # Bringing the definition home is a Phase F move, not a free one (#5560)
-//!
-//! This looks like a shim that could be replaced by a host-side
-//! `tokio::task_local!` in one commit. It cannot, while the in-process engine
-//! is still linked, and the failure would be silent.
-//!
-//! The engine reads this task-local in exactly one production place:
-//! `tinymemory_core::store::recall_policy::current_self_echo_exclusion`, which
-//! is how an in-process recall stops returning the very thread it was called
-//! from. Two `task_local!` invocations are two distinct keys, so moving the
-//! definition here would leave the engine's key permanently unset — and unset
-//! means *exclude nothing*, a permission-shaped check that fails open. Recall
-//! would start echoing the caller's own thread back at it, with no error
-//! anywhere.
-//!
-//! That read is already dead in module mode, for the reason `AGENTS.md` states:
-//! a task-local set in this process is invisible inside a separately compiled
-//! `cdylib`, so callers must pass `RecallOpts::exclude_session_id` explicitly
-//! and the host's own call sites do. So the definition comes home **with** the
-//! engine's removal, in the same commit — not before it.
+//! The web channel keys runtime sessions by `(client_id, thread_id)` and the
+//! backend's `/openai/v1/chat/completions` endpoint accepts an optional
+//! `thread_id` field so it can group inference logs and align KV-cache keys
+//! with the same logical chat the user sees on screen.
+//!
+//! Threading the identifier through every layer (`Agent` → tool loop →
+//! sub-agent runner → `Provider` impl) would touch dozens of call sites and
+//! tests. Instead the channel sets a [`tokio::task_local`] before invoking the
+//! agent loop, and the OpenAI-compatible provider reads it when serialising the
+//! request body. Other call paths see `None` and omit the field — backward
+//! compatible with backends that do not accept it.
+//!
+//! ```ignore
+//! use crate::openhuman::agent::tinyagents::thread_context::{current_thread_id, with_thread_id};
+//!
+//! with_thread_id("abc123", async {
+//! // any provider.chat() call inside this future sees thread_id=Some("abc123")
+//! assert_eq!(current_thread_id().as_deref(), Some("abc123"));
+//! }).await;
+//! ```
+//!
+//! # Why the definition is here again (#5560)
+//!
+//! It was `pub use tinymemory_core::thread_context::{…}` — the task-local was
+//! defined in the memory engine because the engine's own recall read it, and
+//! two `tokio::task_local!` invocations are two distinct keys. The previous
+//! revision of these docs said the move back "comes with the engine's removal,
+//! in the same commit — not before it", because leaving the engine's key unset
+//! would make its self-echo exclusion fail **open**: recall would start echoing
+//! the caller's own thread back at it, with no error anywhere.
+//!
+//! That condition is met, and by a stronger route than the docs anticipated.
+//! The engine reads this task-local in exactly one place —
+//! `store::recall_policy::current_self_echo_exclusion`, reached only from
+//! `impl Memory for UnifiedMemory`'s `recall`, and only as the fallback when
+//! the caller passed no `RecallOpts::exclude_session_id`. Nothing in this
+//! binary constructs a `UnifiedMemory` any more: `memory::binding` refuses
+//! `DriverClass::Embedded` outright, `memory::mod`'s alias list dropped
+//! `MemoryClient` / `UnifiedMemory` for want of consumers, and
+//! `tinymemory_core::global::init` survives in `memory::ops::test_support`
+//! alone. So the engine-side read is already unreachable in a production build
+//! — and where it *is* reachable, from a test that boots an in-process client,
+//! that test names the engine crate directly and gets the engine's own key.
+//!
+//! The host's own call sites are unaffected either way: every one of them
+//! reaches this path (`agent::tinyagents::thread_context`) for both `with_` and
+//! `current_`, so the scope they set is the scope they read. A caller that
+//! needs the exclusion applied by the *module* driver must still pass
+//! `RecallOpts::exclude_session_id` explicitly — a task-local set in this
+//! process is invisible inside a separately compiled `cdylib`, which is why
+//! `agent::tinyagents::host::agent_memory` and `agent::harness::memory_context`
+//! already do.
+
+use std::future::Future;
+
+tokio::task_local! {
+ static THREAD_ID: Option<String>;
+}
+
+/// Run `fut` with the given `thread_id` available to any descendant task that
+/// calls [`current_thread_id`]. Empty / whitespace-only ids are normalised to
+/// `None` so callers can pass user input through without guarding for it.
+pub async fn with_thread_id<F, T>(thread_id: impl Into<String>, fut: F) -> T
+where
+ F: Future<Output = T>,
+{
+ let id = thread_id.into();
+ let trimmed = id.trim();
+ let value = if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ };
+ log::debug!(
+ "[thread-context] entering scope thread_id={}",
+ value.as_deref().unwrap_or("<none>")
+ );
+ THREAD_ID.scope(value, fut).await
+}
+
+/// Return the ambient `thread_id` set by an enclosing [`with_thread_id`] scope,
+/// or `None` when called outside one (tests, CLI, sub-systems that do not
+/// participate in chat sessions).
+pub fn current_thread_id() -> Option<String> {
+ THREAD_ID
+ .try_with(|v| v.clone())
+ .ok()
+ .flatten()
+ .filter(|s| !s.is_empty())
+}
-pub use tinymemory_core::thread_context::{current_thread_id, with_thread_id};
+#[cfg(test)]
+#[path = "thread_context_tests.rs"]
+mod tests;
diff --git a/src/openhuman/agent/tinyagents/thread_context_tests.rs b/src/openhuman/agent/tinyagents/thread_context_tests.rs
new file mode 100644
index 0000000000..b46f9daeec
--- /dev/null
+++ b/src/openhuman/agent/tinyagents/thread_context_tests.rs
@@ -0,0 +1,69 @@
+//! Tests for the surrounding module.
+//!
+//! The task-local came home in #5560, so its normalisation and scoping rules
+//! are this crate's to pin: an unset scope must read as `None` (the provider
+//! then omits the field rather than sending an empty one), whitespace-only ids
+//! must normalise to `None` rather than reaching the wire, and a nested scope
+//! must shadow its parent for the duration and no longer.
+
+use super::{current_thread_id, with_thread_id};
+
+#[tokio::test]
+async fn reads_the_id_set_by_the_enclosing_scope() {
+ with_thread_id("abc123", async {
+ assert_eq!(current_thread_id().as_deref(), Some("abc123"));
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn outside_any_scope_there_is_no_ambient_id() {
+ assert_eq!(current_thread_id(), None);
+}
+
+#[tokio::test]
+async fn blank_ids_normalise_to_none() {
+ with_thread_id(" ", async {
+ assert_eq!(current_thread_id(), None);
+ })
+ .await;
+ with_thread_id("", async {
+ assert_eq!(current_thread_id(), None);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn surrounding_whitespace_is_trimmed() {
+ with_thread_id(" t-42\n", async {
+ assert_eq!(current_thread_id().as_deref(), Some("t-42"));
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn a_nested_scope_shadows_its_parent_and_then_restores_it() {
+ with_thread_id("outer", async {
+ assert_eq!(current_thread_id().as_deref(), Some("outer"));
+ with_thread_id("inner", async {
+ assert_eq!(current_thread_id().as_deref(), Some("inner"));
+ })
+ .await;
+ assert_eq!(current_thread_id().as_deref(), Some("outer"));
+ })
+ .await;
+}
+
+/// A spawned task does not inherit the parent's task-local, which is why the
+/// orchestrator's async sub-agent path re-enters `with_thread_id` explicitly
+/// rather than relying on the scope it was spawned from.
+#[tokio::test]
+async fn a_spawned_task_does_not_inherit_the_scope() {
+ with_thread_id("parent", async {
+ let inherited = tokio::spawn(async { current_thread_id() })
+ .await
+ .expect("spawned task panicked");
+ assert_eq!(inherited, None);
+ })
+ .await;
+}
diff --git a/src/openhuman/channels/host/adapters.rs b/src/openhuman/channels/host/adapters.rs
index 35e9a6a524..4b5b7f5600 100644
--- a/src/openhuman/channels/host/adapters.rs
+++ b/src/openhuman/channels/host/adapters.rs
@@ -217,7 +217,7 @@ impl ConversationStore for ConversationHistoryStore {
session_key: &str,
limit: usize,
) -> anyhow::Result<Vec<ConversationMessage>> {
- let messages = tinycortex::memory::conversations::get_messages(
+ let messages = crate::openhuman::memory::conversations::get_messages(
self.workspace_dir.clone(),
session_key,
)
@@ -236,9 +236,9 @@ impl ConversationStore for ConversationHistoryStore {
async fn append(&self, session_key: &str, message: ConversationMessage) -> anyhow::Result<()> {
let now = chrono::Utc::now().to_rfc3339();
// `append_message` requires the thread to exist; create-or-noop first.
- tinycortex::memory::conversations::ensure_thread(
+ crate::openhuman::memory::conversations::ensure_thread(
self.workspace_dir.clone(),
- tinycortex::memory::conversations::CreateConversationThread {
+ crate::openhuman::memory::conversations::CreateConversationThread {
id: session_key.to_string(),
title: session_key.to_string(),
created_at: now.clone(),
@@ -248,7 +248,7 @@ impl ConversationStore for ConversationHistoryStore {
},
)
.map_err(|e| anyhow::anyhow!(e))?;
- let stored = tinycortex::memory::conversations::ConversationMessage {
+ let stored = crate::openhuman::memory::conversations::ConversationMessage {
id: uuid::Uuid::new_v4().to_string(),
content: message.content,
message_type: message.role.clone(),
@@ -256,7 +256,7 @@ impl ConversationStore for ConversationHistoryStore {
sender: message.role,
created_at: now,
};
- tinycortex::memory::conversations::append_message(
+ crate::openhuman::memory::conversations::append_message(
self.workspace_dir.clone(),
session_key,
stored,
diff --git a/src/openhuman/channels/providers/telegram/remote_control.rs b/src/openhuman/channels/providers/telegram/remote_control.rs
index 2bd811b904..0a6265f0fb 100644
--- a/src/openhuman/channels/providers/telegram/remote_control.rs
+++ b/src/openhuman/channels/providers/telegram/remote_control.rs
@@ -5,7 +5,7 @@ use crate::openhuman::channels::context::{
clear_sender_history, conversation_history_key, ChannelRouteSelection, ChannelRuntimeContext,
};
use crate::openhuman::channels::traits::ChannelMessage;
-use tinycortex::memory::conversations::{
+use crate::openhuman::memory::conversations::{
self as conversations, ConversationThread, CreateConversationThread,
};
diff --git a/src/openhuman/desktop/app_state/ops_part_01.rs b/src/openhuman/desktop/app_state/ops_part_01.rs
index 42e23ce54d..a4a2845f3f 100644
--- a/src/openhuman/desktop/app_state/ops_part_01.rs
+++ b/src/openhuman/desktop/app_state/ops_part_01.rs
@@ -654,7 +654,7 @@ async fn activate_revalidated_user_dir(user_id: &str) -> Result<Config, String>
);
if previous_active.is_none() {
let pre_ws = crate::openhuman::config::pre_login_user_dir(&root_dir).join("workspace");
- if let Err(error) = tinycortex::memory::conversations::purge_threads(pre_ws) {
+ if let Err(error) = crate::openhuman::memory::conversations::purge_threads(pre_ws) {
debug!(
"{LOG_PREFIX} pre-login conversation purge skipped after pending session revalidation: {error}"
);
diff --git a/src/openhuman/integrations/composio/ops/memory_cleanup.rs b/src/openhuman/integrations/composio/ops/memory_cleanup.rs
index c3b77b6a0e..b51059ba89 100644
--- a/src/openhuman/integrations/composio/ops/memory_cleanup.rs
+++ b/src/openhuman/integrations/composio/ops/memory_cleanup.rs
@@ -6,13 +6,21 @@ use tinymemory_api::chunks::SourceKind;
use tinymemory_api::provider::ForgetSelector;
/// KV namespace the Composio sync pipelines keep their per-connection cursor
-/// state under.
+/// state under, and the state record itself.
///
-/// `tinycortex`'s `memory::sync::state::STATE_NAMESPACE`, which
-/// `tinymemory-core`'s `sync_state::KV_NAMESPACE` aliases — one namespace, two
-/// crates naming it, and the row this module reads is written by whichever of
-/// them ran the last sync.
-const SYNC_STATE_NAMESPACE: &str = "composio-sync-state";
+/// Both named at the **contract** (#5560). This file used to hold the namespace
+/// as a hand-copied literal, with a comment explaining that two engine crates
+/// also spelled it and that the row could have been written by either. The
+/// contract publishes it — and marks it, with the record's serde field names, a
+/// compatibility surface — so there is one spelling now, and it is the one the
+/// driver that writes these rows reads.
+///
+/// [`SyncState`] likewise: this module only ever deserialised it to reach
+/// `synced_ids`, and the contract's declaration is the engine's field for
+/// field, in the same order, under the same `#[serde(default)]`s. Naming the
+/// contract's is what makes "the shape this reads is the shape that was
+/// written" a fact about the build rather than about two files agreeing.
+use tinymemory_api::composio::{SyncState, STATE_NAMESPACE as SYNC_STATE_NAMESPACE};
/// One thing a connection delete has to remove from memory.
///
@@ -116,7 +124,7 @@ impl MemoryCleanupTarget {
/// **Takes a `&Config`, not a memory handle, and that is the openhuman#5560
/// change.** This used to take `&MemoryClientRef` — the caller's handle on the
/// live in-process store — because the notion arm loaded sync state through
-/// `tinymemory_core::tinycortex::HostSyncAdapter`. That adapter is two lines
+/// the engine's `HostSyncAdapter`. That adapter is two lines
/// (`kv_get` / `kv_set` on the client), the contract's `MemoryGraph` serves
/// exactly those, and the in-process engine is gone — so the read goes over the
/// bus and the parameter became the config the binding is keyed on.
@@ -207,7 +215,7 @@ async fn notion_memory_targets_for_connection(
.map_err(sync_state_load_error)?;
let synced_ids = match record {
Some(record) => {
- serde_json::from_value::<tinycortex::memory::sync::SyncState>(record.value)
+ serde_json::from_value::<SyncState>(record.value)
.map_err(sync_state_load_error)?
.synced_ids
}
diff --git a/src/openhuman/memory/binding.rs b/src/openhuman/memory/binding.rs
index fd88221f0d..969a7a1d69 100644
--- a/src/openhuman/memory/binding.rs
+++ b/src/openhuman/memory/binding.rs
@@ -8,10 +8,9 @@
//! The binding is resolved by
//! [`CoreContext::memory_binding`](crate::core::runtime::CoreContext::memory_binding),
//! which keys on the context's workspace dir. The cache below is deliberately
-//! shaped like
-//! [`memory::people::store::for_workspace`](crate::openhuman::memory::people::store::for_workspace)
-//! — a **workspace-keyed map** — and deliberately *not* like
-//! [`memory::global`](crate::openhuman::memory::global), which is a single slot
+//! shaped like the engine's `people::store::for_workspace`
+//! — a **workspace-keyed map** — and deliberately *not* like the engine's
+//! `global` slot, which is a single slot
//! holding "the one active-user workspace".
//!
//! That shape choice carries a real correctness property for free.
diff --git a/src/openhuman/memory/conversations/blocking.rs b/src/openhuman/memory/conversations/blocking.rs
index 09adb769bb..2af5f8e402 100644
--- a/src/openhuman/memory/conversations/blocking.rs
+++ b/src/openhuman/memory/conversations/blocking.rs
@@ -10,16 +10,15 @@
//! is a move home rather than a re-routing — the same shape as
//! `memory::rpc_models`, whose forty-five types were named only by this host.
//!
-//! The only edit is the crate the store is addressed through:
-//! `crate::engine::backend::conversations` was
-//! `pub use tinycortex::memory::conversations`, so the item set is unchanged
-//! and `tinycortex` is a direct dependency this crate keeps. Function
-//! signatures, argument order, error strings and the `[conversations]` log
-//! prefix are byte-identical, because `web_chat::run_task` and the RPC layer
-//! read them.
+//! The store these wrappers address has since followed them home: `store` is
+//! now [`super`]'s own subtree rather than `tinycortex::memory::conversations`,
+//! and the import below is the only line that changed for it. The item set is
+//! the same one the engine exported, so function signatures, argument order,
+//! error strings and the `[conversations]` log prefix stay byte-identical —
+//! `web_chat::run_task` and the RPC layer read them.
//!
-//! Every `tinycortex::memory::conversations` entry point is synchronous, and
-//! each one takes the process-global `CONVERSATION_STORE_LOCK` — a
+//! Every store entry point is synchronous, and each one takes the
+//! process-global `CONVERSATION_STORE_LOCK` — a
//! `parking_lot::Mutex` — and then does fsync'd JSONL file IO while holding it.
//! Calling one directly from an `async fn` therefore parks a tokio **worker**
//! thread for the whole wait, and the wait is not short:
@@ -52,9 +51,9 @@
use std::path::PathBuf;
-use tinycortex::memory::conversations as store;
+use crate::openhuman::memory::conversations as store;
-use tinycortex::memory::conversations::{
+use super::{
ConversationMessage, ConversationMessagePatch, ConversationPurgeStats, ConversationStore,
ConversationThread, CreateConversationThread, CrossThreadHit,
};
diff --git a/src/openhuman/memory/conversations/bus.rs b/src/openhuman/memory/conversations/bus.rs
index 240c3afed3..ef565083df 100644
--- a/src/openhuman/memory/conversations/bus.rs
+++ b/src/openhuman/memory/conversations/bus.rs
@@ -1,6 +1,25 @@
//! Event-bus subscriber that mirrors inbound channel messages into the
//! workspace-backed conversation store, so non-web channels (Slack, Telegram,
//! etc.) persist alongside UI-driven threads.
+//!
+//! # The engine's `bus.rs` is not this file, and did not replace it (#5560)
+//!
+//! When the conversation store lived in the memory engine it carried a second
+//! subscriber of its own. That one existed only because the engine could not
+//! name the host's channel layer: it declared a `ConversationEventBus` trait
+//! for a host to implement, a self-contained `ChannelEvent` enum standing in
+//! for `DomainEvent::ChannelMessage*`, and an inlined copy of
+//! `conversation_history_key`'s thread-id derivation — with a comment
+//! promising the copy stayed byte-identical to this one.
+//!
+//! No host ever implemented that trait. This file has always been the live
+//! subscriber, wired to `crate::core::bus::BUS` and calling the real
+//! [`conversation_history_key`], and moving the store home means the
+//! abstraction has nothing left to abstract. So the engine's version stayed
+//! where it was and only the store import below changed. Two things follow:
+//! there is exactly one thread-id derivation again rather than a copy and a
+//! promise, and this file's behaviour is untouched by the move — which matters,
+//! because it decides the id under which channel turns are persisted.
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock, RwLock};
@@ -15,7 +34,7 @@ use tinybus::SubscriptionHandle;
use tinychannels_bus::context::conversation_history_key;
use tinychannels_bus::ChannelMessage;
-use tinycortex::memory::conversations::{
+use super::{
append_message, ensure_thread, get_messages, ConversationMessage, CreateConversationThread,
};
diff --git a/src/openhuman/memory/conversations/bus_tests.rs b/src/openhuman/memory/conversations/bus_tests.rs
index 6e8aa52966..f5fc854fe7 100644
--- a/src/openhuman/memory/conversations/bus_tests.rs
+++ b/src/openhuman/memory/conversations/bus_tests.rs
@@ -61,14 +61,16 @@ async fn persists_inbound_and_processed_turns_into_workspace_thread() {
})
.await;
- let threads = tinycortex::memory::conversations::list_threads(temp.path().to_path_buf())
+ let threads = crate::openhuman::memory::conversations::list_threads(temp.path().to_path_buf())
.expect("threads");
assert_eq!(threads.len(), 1);
assert_eq!(threads[0].id, "channel:slack_alice_general_thread:thread-1");
- let messages =
- tinycortex::memory::conversations::get_messages(temp.path().to_path_buf(), &threads[0].id)
- .expect("messages");
+ let messages = crate::openhuman::memory::conversations::get_messages(
+ temp.path().to_path_buf(),
+ &threads[0].id,
+ )
+ .expect("messages");
assert_eq!(messages.len(), 2);
assert_eq!(messages[0].id, "user:m1");
assert_eq!(messages[0].sender, "user");
@@ -114,7 +116,7 @@ async fn telegram_thread_ts_does_not_split_persisted_thread() {
})
.await;
- let threads = tinycortex::memory::conversations::list_threads(temp.path().to_path_buf())
+ let threads = crate::openhuman::memory::conversations::list_threads(temp.path().to_path_buf())
.expect("threads");
assert_eq!(threads.len(), 1);
assert_eq!(threads[0].id, "channel:telegram_alice_chat-1");
@@ -139,7 +141,7 @@ async fn duplicate_events_do_not_append_duplicate_messages() {
subscriber.handle(&event).await;
subscriber.handle(&event).await;
- let messages = tinycortex::memory::conversations::get_messages(
+ let messages = crate::openhuman::memory::conversations::get_messages(
temp.path().to_path_buf(),
"channel:discord_alice_room-1",
)
@@ -196,7 +198,7 @@ async fn received_matching_workspace_is_persisted() {
})
.await;
- let messages = tinycortex::memory::conversations::get_messages(
+ let messages = crate::openhuman::memory::conversations::get_messages(
temp.path().to_path_buf(),
"channel:slack_bob_dev",
)
@@ -227,7 +229,7 @@ async fn received_stale_workspace_is_dropped() {
.await;
// No thread should have been created in temp (the subscriber's workspace).
- let threads = tinycortex::memory::conversations::list_threads(temp.path().to_path_buf())
+ let threads = crate::openhuman::memory::conversations::list_threads(temp.path().to_path_buf())
.expect("threads");
assert!(
threads.is_empty(),
@@ -273,7 +275,7 @@ async fn processed_matching_workspace_is_appended() {
})
.await;
- let messages = tinycortex::memory::conversations::get_messages(
+ let messages = crate::openhuman::memory::conversations::get_messages(
temp.path().to_path_buf(),
"channel:slack_alice_general",
)
@@ -323,7 +325,7 @@ async fn processed_stale_workspace_is_dropped() {
})
.await;
- let messages = tinycortex::memory::conversations::get_messages(
+ let messages = crate::openhuman::memory::conversations::get_messages(
temp.path().to_path_buf(),
"channel:slack_alice_general",
)
@@ -395,7 +397,7 @@ async fn workspace_switch_mid_conversation() {
})
.await;
- let messages = tinycortex::memory::conversations::get_messages(
+ let messages = crate::openhuman::memory::conversations::get_messages(
workspace_a.path().to_path_buf(),
"channel:telegram_alice_chat-1",
)
@@ -435,7 +437,7 @@ async fn multiple_stale_workspaces_all_dropped() {
.await;
}
- let threads = tinycortex::memory::conversations::list_threads(temp.path().to_path_buf())
+ let threads = crate::openhuman::memory::conversations::list_threads(temp.path().to_path_buf())
.expect("threads");
assert!(
threads.is_empty(),
@@ -479,7 +481,7 @@ async fn correct_workspace_after_stale_events() {
})
.await;
- let messages = tinycortex::memory::conversations::get_messages(
+ let messages = crate::openhuman::memory::conversations::get_messages(
temp.path().to_path_buf(),
"channel:slack_alice_general",
)
diff --git a/src/openhuman/memory/conversations/mod.rs b/src/openhuman/memory/conversations/mod.rs
index ff552bf875..550635119f 100644
--- a/src/openhuman/memory/conversations/mod.rs
+++ b/src/openhuman/memory/conversations/mod.rs
@@ -1,29 +1,60 @@
-//! Host-side wiring for workspace-backed conversation thread/message storage.
+//! Workspace-backed conversation thread/message storage — the whole thing,
+//! store and wiring both.
//!
-//! Conversations are stored as JSONL files under the workspace (thread metadata
-//! append-only in `threads.jsonl`; each thread's messages in a dedicated JSONL
-//! file). The store / inverted-index / tokenizer / types engine is
-//! `tinycortex::memory::conversations`, and consumers name that directly —
-//! roughly a dozen files across `threads`, `channels` and `agent` already do.
+//! Conversations are JSONL files under `<workspace>/memory/conversations/`:
+//! thread metadata as an append-only upsert/delete log in `threads.jsonl`, and
+//! each thread's messages in a dedicated file under
+//! `threads/<hex(thread_id)>.jsonl`. This is **transcript persistence** — the
+//! raw records plus a trigram/CJK-bigram index for cross-thread substring
+//! search over them. The summary-tree archival of the same transcripts is
+//! [`crate::openhuman::memory::tree`], a different index answering a different
+//! question.
//!
-//! Host-retained:
-//! - `bus` — the `core::bus` persistence subscriber that bridges typed channel
-//! events onto the store (the store abstracts the bus behind its own
-//! `ConversationEventBus` trait; the host wires the real one).
-//! - [`blocking`] — `spawn_blocking` wrappers around the store's synchronous
-//! entry points. Request paths must use these, never the sync API (#5156).
+//! Three parts, and the split is about ownership rather than size:
//!
-//! # What changed for #5560
+//! - `store` — the implementation: on-disk format, the process-wide write
+//! lock, the warm index cache, CRUD and search. Everything below is
+//! re-exported from here, so callers name
+//! `crate::openhuman::memory::conversations::{…}` and never the subtree.
+//! - [`blocking`] — `spawn_blocking` wrappers. Every store entry point is
+//! synchronous and takes a `parking_lot` mutex across fsync'd file IO, so an
+//! `async fn` that calls one directly parks a tokio **worker** thread for the
+//! whole wait. Request paths must use these (#5156).
+//! - `bus` — the `core::bus` subscriber that mirrors inbound and processed
+//! channel turns into the store, so Slack/Telegram/… persist alongside the
+//! UI's own threads.
//!
-//! This module used to open with `pub use tinymemory_core::conversations::*;`,
-//! and that glob carried exactly one item: `blocking`. The engine crate's own
-//! docs already labelled it *host-retained* — nothing inside `tinymemory` ever
-//! called it — so it moved here rather than being re-routed, and this file no
-//! longer names the engine crate at all. See [`blocking`]'s module docs for the
-//! one-line difference the move made.
+//! # What #5560 changed here
+//!
+//! Until this change, `store` was `tinycortex::memory::conversations` and
+//! roughly a dozen files across `threads`, `channels` and `agent` named that
+//! crate directly — 72 of this host's ~156 `tinycortex::` call sites, the
+//! single largest block of them. The store is back in the host now, and those
+//! call sites name this module instead.
+//!
+//! It came back because the lift was never load-bearing: nothing inside the
+//! engine ever called into this code, its imports are std plus
+//! `async_trait`/`chrono`/`parking_lot`/`serde`/`serde_json`/`uuid`, and its
+//! sole tie to the rest of the engine was a one-line `from_config` constructor
+//! that no host caller used. The engine's own module docs recorded the code as
+//! "ported from OpenHuman", which is the tell: it was host code parked in a
+//! library. `store`'s module docs carry the full accounting of what the
+//! round trip cost and what deliberately did not come back with it.
+//!
+//! Nothing about the on-disk format moved. The root is still
+//! `<workspace>/memory/conversations`, derived by the same line of code from
+//! the same argument every caller was already passing, so an existing
+//! installation reads and writes exactly the files it did before.
pub mod blocking;
mod bus;
+mod store;
pub use bus::register_conversation_persistence_subscriber;
+pub use store::{
+ append_message, delete_thread, ensure_thread, get_messages, list_threads, purge_threads,
+ update_message, update_thread_labels, update_thread_title, ConversationMessage,
+ ConversationMessagePatch, ConversationPurgeStats, ConversationStore, ConversationThread,
+ CreateConversationThread, CrossThreadHit,
+};
diff --git a/src/openhuman/memory/conversations/store/inverted_index.rs b/src/openhuman/memory/conversations/store/inverted_index.rs
new file mode 100644
index 0000000000..e29ca14b86
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/inverted_index.rs
@@ -0,0 +1,445 @@
+//! In-memory inverted index for `search_cross_thread_messages`.
+//!
+//! ## Architecture (v1)
+//!
+//! ```text
+//! ┌───────────────┐
+//! query "cat" ───▶ │ Phase 1: │ posting-list intersection
+//! │ ngram lookup │ on character n-grams
+//! └──────┬────────┘
+//! │ candidate doc ids per term
+//! ┌──────▼────────┐
+//! │ Phase 2: │ exact substring verify on
+//! │ verify+score │ normalized content, score
+//! └──────┬────────┘ by `matched_terms / total_terms`
+//! │
+//! ▼
+//! Vec<Hit>
+//! ```
+//!
+//! ## Ownership choices for scale
+//!
+//! Conversation corpora can grow to hundreds of thousands of messages per
+//! workspace. The data structures here are picked to keep the resident-set
+//! size predictable at that scale:
+//!
+//! - **`thread_id` and `role` are interned `Arc<str>`** (see
+//! `intern_thread_id` / `intern_role`). A workspace with one thread of
+//! N messages would otherwise store N copies of the same thread id; a
+//! role string only ever takes two distinct values in practice. The
+//! interner amortises both to a single heap allocation per distinct
+//! value, plus one `Arc` clone per `DocEntry`.
+//! - **Posting-map keys are `Box<str>`** (16 bytes) rather than `String`
+//! (24 bytes). Saves 8 bytes per distinct ngram in the corpus — at
+//! ~17k Latin trigrams plus CJK bigrams that adds up.
+//! - **Posting lists are still `BTreeSet<u32>`** for ergonomic ordered
+//! iteration. The Phase 1 intersection is performed against a
+//! single-allocation `Vec<u32>` accumulator via a two-pointer
+//! sort-merge (no per-iteration `BTreeSet` rebuilds), so the BTreeSet
+//! shape only affects insertion and removal, not query latency.
+//! Roaring Bitmaps + FST + LSM segments are the long-term destination
+//! (Gemini Deep Research write-up); we defer that until corpus sizes
+//! justify the complexity.
+//! - **Whole index lives in RAM**, rebuilt from JSONL on first access in
+//! the process. The JSONL files remain the source of truth.
+//! - **Scoring matches the previous linear scan**:
+//! `score = matched_terms / total_terms` with a `created_at` tiebreaker.
+//! - **Pathological query short-circuit**: if Phase 1 produces a
+//! candidate set larger than `LARGE_CANDIDATE_LIMIT` for any term, the
+//! index returns recency-ordered hits without running Phase 2. This
+//! genuinely caps tail latency — the check fires *before* the
+//! substring-verification loop, not after.
+
+use std::collections::{BTreeSet, HashMap};
+use std::sync::Arc;
+
+use super::tokenize::{ngrams, normalize};
+use super::types::{ConversationMessage, CrossThreadHit};
+
+/// Minimum byte length for a query term to be considered. Matches the
+/// historical behaviour of `search_cross_thread_messages` so existing
+/// callers (and tests) see no change. Single-byte ASCII tokens like "a"
+/// or "is" are filtered out; a single CJK character (3 bytes in UTF-8)
+/// passes through.
+const MIN_TERM_BYTES: usize = 3;
+
+/// When Phase 1 returns more than this many candidates we skip Phase 2
+/// verification and fall back to a pure recency-ranked truncation. This
+/// is the mitigation for the "user types `e`" pathological case.
+const LARGE_CANDIDATE_LIMIT: usize = 10_000;
+
+/// One indexed message. Carries enough state to (a) reconstruct a
+/// `CrossThreadHit` without re-reading JSONL on the hot path and (b)
+/// verify Phase 1 candidates by exact substring match on the normalized
+/// form.
+///
+/// `thread_id` and `role` are `Arc<str>` because they repeat heavily
+/// across messages (N messages per thread → N references to the same
+/// thread id; only ~2 distinct role values across the entire corpus).
+/// `message_id`, `content`, `content_normalized` and `created_at` are
+/// per-message unique so they stay as `String`.
+#[derive(Debug, Clone)]
+struct DocEntry {
+ thread_id: Arc<str>,
+ message_id: String,
+ role: Arc<str>,
+ content: String, // original, returned verbatim in hits
+ content_normalized: String, // for Phase 2 substring verification
+ created_at: String,
+ created_at_ms: i64,
+}
+
+/// In-memory trigram/bigram inverted index over conversation messages.
+///
+/// Documents are addressed by a dense `u32` doc-id assigned in insertion
+/// order. Deletes leave tombstones (`docs[i] = None`) rather than shifting
+/// the array, so posting-list integers stay valid without rebuilding.
+#[derive(Debug, Default)]
+pub(crate) struct InvertedIndex {
+ /// `ngram -> sorted set of doc-ids`. BTreeSet so per-doc removals
+ /// are O(log n) and iteration is in sorted order (drives the
+ /// sort-merge intersect in `candidates_for_term`). Keys are
+ /// `Box<str>` to shave 8 bytes per entry vs `String`.
+ postings: HashMap<Box<str>, BTreeSet<u32>>,
+ /// Tombstoned: `docs[i] == None` means the message was deleted. We
+ /// keep the slot so existing doc-ids in posting lists stay valid.
+ docs: Vec<Option<DocEntry>>,
+ /// Reverse lookup for incremental removal: `(thread_id, message_id)`
+ /// → `doc_id`. Letting us drop a single message without re-walking
+ /// the corpus.
+ by_message: HashMap<(String, String), u32>,
+ /// Interner pools. Keep a single `Arc<str>` per distinct thread id
+ /// and role so every `DocEntry` referencing them can hold a cheap
+ /// 16-byte `Arc` clone instead of a 24-byte `String`.
+ thread_id_pool: HashMap<String, Arc<str>>,
+ role_pool: HashMap<String, Arc<str>>,
+}
+
+impl InvertedIndex {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Insert one message. Takes the message by value so the caller's
+ /// owned strings can be moved into the index without an internal
+ /// clone of each field. If the (thread, message_id) pair is already
+ /// in the index this is a no-op (messages are append-only in the
+ /// store, so duplicate IDs indicate a corrupt JSONL — silently
+ /// ignore rather than panic).
+ pub fn insert(&mut self, thread_id: &str, msg: ConversationMessage) {
+ let ConversationMessage {
+ id,
+ content,
+ sender,
+ created_at,
+ message_type: _,
+ extra_metadata: _,
+ } = msg;
+
+ let key = (thread_id.to_string(), id.clone());
+ if self.by_message.contains_key(&key) {
+ return;
+ }
+ let normalized = normalize(&content);
+ let created_at_ms = chrono::DateTime::parse_from_rfc3339(&created_at)
+ .map(|value| value.timestamp_millis())
+ .unwrap_or(i64::MIN);
+ let doc_id = self.docs.len() as u32;
+ for ngram in ngrams(&normalized) {
+ if let Some(posting) = self.postings.get_mut(ngram) {
+ posting.insert(doc_id);
+ } else {
+ let mut set = BTreeSet::new();
+ set.insert(doc_id);
+ self.postings.insert(ngram.into(), set);
+ }
+ }
+ let thread_arc = self.intern_thread_id(thread_id);
+ let role_arc = self.intern_role(&sender);
+ self.docs.push(Some(DocEntry {
+ thread_id: thread_arc,
+ message_id: id,
+ role: role_arc,
+ content,
+ content_normalized: normalized,
+ created_at,
+ created_at_ms,
+ }));
+ self.by_message.insert(key, doc_id);
+ }
+
+ /// Drop every document belonging to a thread. Used by
+ /// `delete_thread` and during full purge.
+ pub fn remove_thread(&mut self, thread_id: &str) {
+ let to_remove: Vec<u32> = self
+ .by_message
+ .iter()
+ .filter(|((t, _), _)| t == thread_id)
+ .map(|(_, id)| *id)
+ .collect();
+ for doc_id in to_remove {
+ self.remove_doc(doc_id);
+ }
+ self.thread_id_pool.remove(thread_id);
+ }
+
+ /// Reset the index to its empty state. Cheaper than dropping and
+ /// re-allocating when a workspace is being rebuilt. Retained from the
+ /// OpenHuman port for callers that rebuild in place.
+ #[allow(dead_code)]
+ pub fn clear(&mut self) {
+ self.postings.clear();
+ self.docs.clear();
+ self.by_message.clear();
+ self.thread_id_pool.clear();
+ self.role_pool.clear();
+ }
+
+ fn remove_doc(&mut self, doc_id: u32) {
+ let idx = doc_id as usize;
+ let Some(entry) = self.docs.get_mut(idx).and_then(|slot| slot.take()) else {
+ return;
+ };
+ self.by_message
+ .remove(&(entry.thread_id.to_string(), entry.message_id.clone()));
+ // Remove doc_id from every posting list referencing it. We re-
+ // tokenize the normalized content rather than tracking the
+ // per-doc ngram set; tokenization is allocation-free now that
+ // `ngrams` returns borrowed slices, so this stays cheap.
+ for ngram in ngrams(&entry.content_normalized) {
+ if let Some(posting) = self.postings.get_mut(ngram) {
+ posting.remove(&doc_id);
+ if posting.is_empty() {
+ self.postings.remove(ngram);
+ }
+ }
+ }
+ }
+
+ /// The Phase 1 + Phase 2 query pipeline. Mirrors the contract of
+ /// `ConversationStore::search_cross_thread_messages` so the store
+ /// method can be a thin shim.
+ pub fn search(
+ &self,
+ query: &str,
+ limit: usize,
+ exclude_thread_id: Option<&str>,
+ ) -> Vec<CrossThreadHit> {
+ if limit == 0 {
+ return Vec::new();
+ }
+ let query_lower = normalize(query);
+ // Filter terms by raw byte length (matches the historical
+ // 3-byte threshold; single CJK chars are 3 bytes and pass).
+ let terms: Vec<String> = query_lower
+ .split_whitespace()
+ .filter(|t| t.len() >= MIN_TERM_BYTES)
+ .map(|s| s.to_string())
+ .collect();
+ if terms.is_empty() {
+ return Vec::new();
+ }
+
+ // Phase 1: collect candidate doc-ids per term. Short-circuit to
+ // recency-only ordering if any single term's candidate set
+ // already exceeds the pathological threshold — this is the cap
+ // on tail latency, and it must fire BEFORE we run the substring
+ // verification loop.
+ let mut per_term: Vec<Vec<u32>> = Vec::with_capacity(terms.len());
+ for term in &terms {
+ let candidates = match self.candidates_for_term(term) {
+ Some(v) => {
+ if v.len() > LARGE_CANDIDATE_LIMIT {
+ return self.recency_fallback(exclude_thread_id, limit);
+ }
+ v
+ }
+ // Terms too short for an ngram (notably one CJK character)
+ // require exact verification over the corpus. Returning the
+ // recency fallback here would manufacture unrelated score-0
+ // hits instead of answering the query.
+ None => self
+ .docs
+ .iter()
+ .enumerate()
+ .filter_map(|(i, slot)| slot.as_ref().map(|_| i as u32))
+ .collect::<Vec<u32>>(),
+ };
+ per_term.push(candidates);
+ }
+
+ // Phase 2: verify each candidate by exact substring match.
+ // Count distinct terms per doc for the score.
+ let mut hit_counts: HashMap<u32, usize> = HashMap::new();
+ for (term, candidates) in terms.iter().zip(per_term) {
+ for doc_id in candidates {
+ let Some(entry) = self.docs[doc_id as usize].as_ref() else {
+ continue;
+ };
+ if exclude_thread_id == Some(entry.thread_id.as_ref()) {
+ continue;
+ }
+ if entry.content_normalized.contains(term.as_str()) {
+ *hit_counts.entry(doc_id).or_insert(0) += 1;
+ }
+ }
+ }
+
+ let total_terms = terms.len() as f64;
+ // Rank on cheap keys first — the match count and a borrowed `created_at`
+ // — then materialize the heavy CrossThreadHit (which clones the KB-sized
+ // `content`) only for the `limit` survivors. Phase 2 can leave thousands
+ // of candidates in `hit_counts` while callers ask for 3-10 results, so
+ // cloning every candidate's content before truncating is ~99% wasted.
+ // Ranking by `matched` (usize) is order-equivalent to ranking by
+ // `score = matched / total_terms` since `total_terms` is a positive
+ // constant, so the returned order is unchanged.
+ let mut ranked: Vec<(u32, usize, i64)> = hit_counts
+ .into_iter()
+ .map(|(doc_id, matched)| {
+ let entry = self.docs[doc_id as usize]
+ .as_ref()
+ .expect("doc_id from hit_counts must be live");
+ (doc_id, matched, entry.created_at_ms)
+ })
+ .collect();
+ ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| b.2.cmp(&a.2)));
+ ranked.truncate(limit);
+
+ ranked
+ .into_iter()
+ .map(|(doc_id, matched, _)| {
+ let entry = self.docs[doc_id as usize]
+ .as_ref()
+ .expect("doc_id from hit_counts must be live");
+ CrossThreadHit {
+ thread_id: entry.thread_id.to_string(),
+ message_id: entry.message_id.clone(),
+ role: entry.role.to_string(),
+ content: entry.content.clone(),
+ created_at: entry.created_at.clone(),
+ score: matched as f64 / total_terms,
+ }
+ })
+ .collect()
+ }
+
+ /// Build the Phase 1 candidate set for one query term.
+ ///
+ /// Returns `Some(vec)` containing the sorted intersection of posting
+ /// lists for every ngram of `term`. If `term` is too short to
+ /// produce any ngram (e.g. a single CJK char of length 1) returns
+ /// `None` so the caller can fall back to a linear scan.
+ ///
+ /// The intersect is a two-pointer sort-merge over the already-sorted
+ /// posting lists: `acc` is rewritten in place once per remaining
+ /// ngram, allocating zero intermediate sets.
+ ///
+ /// The `None` case intentionally performs an uncapped full-corpus scan and
+ /// does not invoke the recency fallback. This avoids fabricating score-0.0
+ /// hits for short or single-CJK terms, at the cost of scanning every live
+ /// document for those queries.
+ fn candidates_for_term(&self, term: &str) -> Option<Vec<u32>> {
+ let term_ngrams = ngrams(term);
+ if term_ngrams.is_empty() {
+ return None;
+ }
+ let mut iter = term_ngrams.iter();
+ let first = iter.next().expect("non-empty by check above");
+ let mut acc: Vec<u32> = match self.postings.get(*first) {
+ Some(p) => p.iter().copied().collect(),
+ None => return Some(Vec::new()),
+ };
+ for ng in iter {
+ if acc.is_empty() {
+ return Some(acc);
+ }
+ match self.postings.get(*ng) {
+ Some(p) => intersect_sorted_with_btreeset(&mut acc, p),
+ None => return Some(Vec::new()),
+ }
+ }
+ Some(acc)
+ }
+
+ fn intern_thread_id(&mut self, thread_id: &str) -> Arc<str> {
+ if let Some(existing) = self.thread_id_pool.get(thread_id) {
+ return Arc::clone(existing);
+ }
+ let arc: Arc<str> = Arc::from(thread_id);
+ self.thread_id_pool
+ .insert(thread_id.to_string(), Arc::clone(&arc));
+ arc
+ }
+
+ fn intern_role(&mut self, role: &str) -> Arc<str> {
+ if let Some(existing) = self.role_pool.get(role) {
+ return Arc::clone(existing);
+ }
+ let arc: Arc<str> = Arc::from(role);
+ self.role_pool.insert(role.to_string(), Arc::clone(&arc));
+ arc
+ }
+
+ fn recency_fallback(
+ &self,
+ exclude_thread_id: Option<&str>,
+ limit: usize,
+ ) -> Vec<CrossThreadHit> {
+ let mut entries: Vec<&DocEntry> = self
+ .docs
+ .iter()
+ .filter_map(|slot| slot.as_ref())
+ .filter(|entry| exclude_thread_id != Some(entry.thread_id.as_ref()))
+ .collect();
+ entries.sort_by_key(|entry| std::cmp::Reverse(entry.created_at_ms));
+ entries.truncate(limit);
+ entries
+ .into_iter()
+ .map(|entry| CrossThreadHit {
+ thread_id: entry.thread_id.to_string(),
+ message_id: entry.message_id.clone(),
+ role: entry.role.to_string(),
+ content: entry.content.clone(),
+ created_at: entry.created_at.clone(),
+ // Score 0.0 signals "matched via recency fallback only" —
+ // documented in the function rustdoc above. Callers
+ // sorting by `(score desc, created_at desc)` still see
+ // the newest entries first.
+ score: 0.0,
+ })
+ .collect()
+ }
+}
+
+/// Two-pointer sort-merge intersect. `acc` and `other` are both sorted
+/// ascending; on return `acc` contains only the elements present in
+/// both, in the same sorted order. Runs in O(|acc| + |other|) with zero
+/// allocations.
+fn intersect_sorted_with_btreeset(acc: &mut Vec<u32>, other: &BTreeSet<u32>) {
+ let mut other_iter = other.iter().copied().peekable();
+ let mut write = 0usize;
+ for read in 0..acc.len() {
+ let target = acc[read];
+ // Advance `other_iter` past everything strictly less than the
+ // current `target`. After this loop the next peeked value is
+ // either equal to `target` (keep) or strictly greater (drop).
+ while let Some(&o) = other_iter.peek() {
+ if o < target {
+ other_iter.next();
+ } else {
+ break;
+ }
+ }
+ if other_iter.peek().copied() == Some(target) {
+ acc[write] = target;
+ write += 1;
+ other_iter.next();
+ }
+ }
+ acc.truncate(write);
+}
+
+#[cfg(test)]
+#[path = "inverted_index_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/conversations/store/inverted_index_tests.rs b/src/openhuman/memory/conversations/store/inverted_index_tests.rs
new file mode 100644
index 0000000000..7f577f4895
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/inverted_index_tests.rs
@@ -0,0 +1,254 @@
+//! Phase 1 + Phase 2 query pipeline tests for the in-memory inverted index.
+
+use serde_json::json;
+
+use super::*;
+
+fn msg(id: &str, content: &str, created: &str) -> ConversationMessage {
+ ConversationMessage {
+ id: id.to_string(),
+ content: content.to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: created.to_string(),
+ }
+}
+
+#[test]
+fn substring_inside_word_matches() {
+ // Canonical substring-inside-word case: querying "cat" must find
+ // "concatenate" — a token-boundary tokenizer would miss this.
+ let mut idx = InvertedIndex::new();
+ idx.insert(
+ "t1",
+ msg("m1", "concatenate the strings", "2026-04-10T10:00:00Z"),
+ );
+
+ let hits = idx.search("cat", 10, None);
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].message_id, "m1");
+}
+
+#[test]
+fn polish_diacritics_normalized_both_sides() {
+ let mut idx = InvertedIndex::new();
+ idx.insert(
+ "t1",
+ msg("m1", "Lecę dziś do Krakowa", "2026-04-10T10:00:00Z"),
+ );
+ // Query with no diacritics finds content with diacritics.
+ let hits = idx.search("krakow", 10, None);
+ assert_eq!(hits.len(), 1, "krakow should match Krakowa");
+}
+
+#[test]
+fn japanese_bigram_match() {
+ let mut idx = InvertedIndex::new();
+ idx.insert(
+ "t1",
+ msg("m1", "東京タワーが見える", "2026-04-10T10:00:00Z"),
+ );
+ let hits = idx.search("東京", 10, None);
+ assert_eq!(hits.len(), 1, "two-char CJK query should match");
+}
+
+#[test]
+fn arabic_harakat_stripped() {
+ let mut idx = InvertedIndex::new();
+ // "wrote" with full vocalization vs bare consonants.
+ idx.insert("t1", msg("m1", "كَتَبَ الطالب", "2026-04-10T10:00:00Z"));
+ // The bare-consonant form should still find the vocalized one.
+ let hits = idx.search("كتب", 10, None);
+ assert_eq!(hits.len(), 1, "harakat stripping should equalize forms");
+}
+
+#[test]
+fn excludes_active_thread() {
+ let mut idx = InvertedIndex::new();
+ idx.insert(
+ "active",
+ msg("ma", "postgres deploy", "2026-04-10T10:00:00Z"),
+ );
+ idx.insert(
+ "other",
+ msg("mo", "postgres deploy", "2026-04-10T10:01:00Z"),
+ );
+ let hits = idx.search("postgres", 10, Some("active"));
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].thread_id, "other");
+}
+
+#[test]
+fn empty_query_returns_empty() {
+ let mut idx = InvertedIndex::new();
+ idx.insert("t", msg("m", "anything here", "2026-04-10T10:00:00Z"));
+ assert!(idx.search("", 10, None).is_empty());
+}
+
+#[test]
+fn short_terms_only_returns_empty() {
+ // Mirrors the legacy `search_cross_thread_messages_skips_short_terms`
+ // behaviour — terms < 3 bytes are dropped.
+ let mut idx = InvertedIndex::new();
+ idx.insert("t", msg("m", "Postgres", "2026-04-10T10:00:00Z"));
+ assert!(idx.search("a is on", 10, None).is_empty());
+}
+
+#[test]
+fn limit_zero_returns_empty() {
+ let mut idx = InvertedIndex::new();
+ idx.insert("t", msg("m", "Postgres", "2026-04-10T10:00:00Z"));
+ assert!(idx.search("postgres", 0, None).is_empty());
+}
+
+#[test]
+fn score_matches_legacy_semantics() {
+ // 5-term query, 2 substring matches → score = 0.4.
+ let mut idx = InvertedIndex::new();
+ idx.insert(
+ "t1",
+ msg(
+ "m1",
+ "Remember: my project is called Phoenix and uses Go and PostgreSQL.",
+ "2026-04-10T10:00:00Z",
+ ),
+ );
+ let hits = idx.search("What database does my project use", 10, None);
+ assert_eq!(hits.len(), 1);
+ // "project" + "use" (substring of "uses") → 2 of 5 terms.
+ assert!(
+ (hits[0].score - 0.4).abs() < 1e-9,
+ "score = {}",
+ hits[0].score
+ );
+}
+
+#[test]
+fn remove_thread_drops_all_messages() {
+ let mut idx = InvertedIndex::new();
+ idx.insert("t1", msg("m1", "postgres deploy", "2026-04-10T10:00:00Z"));
+ idx.insert("t1", msg("m2", "postgres backup", "2026-04-10T10:01:00Z"));
+ idx.insert("t2", msg("m3", "postgres replica", "2026-04-10T10:02:00Z"));
+ assert_eq!(idx.search("postgres", 10, None).len(), 3);
+ idx.remove_thread("t1");
+ let hits = idx.search("postgres", 10, None);
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].thread_id, "t2");
+}
+
+#[test]
+fn duplicate_message_id_is_idempotent() {
+ let mut idx = InvertedIndex::new();
+ let m = msg("m1", "postgres deploy", "2026-04-10T10:00:00Z");
+ idx.insert("t1", m.clone());
+ idx.insert("t1", m); // dup — should be ignored
+ let hits = idx.search("postgres", 10, None);
+ assert_eq!(hits.len(), 1, "duplicate insert must not duplicate hits");
+}
+
+#[test]
+fn pathological_query_short_circuits_to_recency() {
+ // Build a corpus big enough to trip LARGE_CANDIDATE_LIMIT.
+ let mut idx = InvertedIndex::new();
+ let n = LARGE_CANDIDATE_LIMIT + 50;
+ for i in 0..n {
+ // "common" appears in every doc, so the trigram "com" hits
+ // all of them.
+ let created = format!("2026-04-10T10:{:02}:{:02}Z", i / 60, i % 60);
+ idx.insert("bulk", msg(&format!("m{i}"), "common payload", &created));
+ }
+ let hits = idx.search("common", 5, None);
+ assert_eq!(hits.len(), 5, "fallback must still respect limit");
+ // Score 0.0 is the recency-fallback marker.
+ assert!(hits.iter().all(|h| h.score == 0.0));
+
+ idx.insert("bulk", msg("cjk", "猫だけ", "2026-04-11T10:00:00Z"));
+ let exact = idx.search("猫", 5, None);
+ assert_eq!(exact.len(), 1);
+ assert_eq!(exact[0].message_id, "cjk");
+ assert_eq!(exact[0].score, 1.0);
+}
+
+#[test]
+fn intern_pool_dedupes_repeated_thread_id_and_role() {
+ // Smoke-test the Arc<str> interning: many messages on one
+ // thread must share a single Arc backing the thread_id.
+ let mut idx = InvertedIndex::new();
+ for i in 0..5 {
+ let ts = format!("2026-04-10T10:00:{:02}Z", i);
+ idx.insert("shared-thread", msg(&format!("m{i}"), "payload", &ts));
+ }
+ assert_eq!(idx.thread_id_pool.len(), 1);
+ assert_eq!(idx.role_pool.len(), 1);
+ // After removing the thread, the pool entry is dropped too.
+ idx.remove_thread("shared-thread");
+ assert_eq!(idx.thread_id_pool.len(), 0);
+}
+
+#[test]
+fn intersect_sorted_with_btreeset_basic() {
+ let other: BTreeSet<u32> = [2, 4, 5, 9].into_iter().collect();
+ let mut acc: Vec<u32> = vec![1, 2, 3, 5, 7, 9];
+ intersect_sorted_with_btreeset(&mut acc, &other);
+ assert_eq!(acc, vec![2, 5, 9]);
+}
+
+#[test]
+fn intersect_sorted_with_btreeset_empty_other() {
+ let other: BTreeSet<u32> = BTreeSet::new();
+ let mut acc: Vec<u32> = vec![1, 2, 3];
+ intersect_sorted_with_btreeset(&mut acc, &other);
+ assert!(acc.is_empty());
+}
+
+#[test]
+fn ranks_by_score_then_recency_before_truncating() {
+ // More matches than `limit`, so truncation must keep the top-ranked hits by
+ // (score desc, created_at desc) — this pins that ranking still happens
+ // before the result set is cut, not after (the rank-before-materialize
+ // refactor must stay order-equivalent to the old clone-then-rank path).
+ let mut idx = InvertedIndex::new();
+ // Both terms → score 1.0, but oldest.
+ idx.insert(
+ "t1",
+ msg("both", "alpha beta gamma", "2026-04-10T10:00:00Z"),
+ );
+ // One term → score 0.5, newest of the 0.5 group.
+ idx.insert("t1", msg("newest", "alpha delta", "2026-04-10T10:03:00Z"));
+ // One term → score 0.5, middle.
+ idx.insert("t1", msg("middle", "alpha epsilon", "2026-04-10T10:02:00Z"));
+ // One term → score 0.5, oldest of the 0.5 group.
+ idx.insert("t1", msg("oldest", "beta zeta", "2026-04-10T10:01:00Z"));
+
+ let hits = idx.search("alpha beta", 2, None);
+ assert_eq!(hits.len(), 2, "must respect the limit");
+ // Highest score wins outright; the recency tiebreak then picks the newest of
+ // the equal-score remainder. "middle"/"oldest" are dropped.
+ assert_eq!(hits[0].message_id, "both");
+ assert!(
+ (hits[0].score - 1.0).abs() < 1e-9,
+ "score = {}",
+ hits[0].score
+ );
+ assert_eq!(hits[1].message_id, "newest");
+ assert!(
+ (hits[1].score - 0.5).abs() < 1e-9,
+ "score = {}",
+ hits[1].score
+ );
+}
+
+#[test]
+fn recency_tiebreak_compares_instants_across_rfc3339_offsets() {
+ let mut idx = InvertedIndex::new();
+ idx.insert(
+ "t1",
+ msg("older", "alpha match", "2026-04-10T12:30:00+02:00"),
+ );
+ idx.insert("t1", msg("newer", "alpha match", "2026-04-10T11:00:00Z"));
+
+ let hits = idx.search("alpha", 2, None);
+ assert_eq!(hits[0].message_id, "newer");
+ assert_eq!(hits[1].message_id, "older");
+}
diff --git a/src/openhuman/memory/conversations/store/mod.rs b/src/openhuman/memory/conversations/store/mod.rs
new file mode 100644
index 0000000000..795989ebab
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/mod.rs
@@ -0,0 +1,91 @@
+//! Workspace-backed conversation thread/message storage — the implementation,
+//! not the wiring.
+//!
+//! Conversations are stored as JSONL files under
+//! `<workspace>/memory/conversations/`. Thread metadata is an append-only
+//! upsert/delete log in `threads.jsonl`; each thread's messages live in a
+//! dedicated JSONL file under `threads/<hex(thread_id)>.jsonl` for
+//! straightforward inspection and recovery.
+//!
+//! This is **transcript persistence**, not semantic indexing: it owns the raw
+//! thread/message records and a local trigram/CJK-bigram inverted index for
+//! cross-thread substring search over those transcripts. The richer
+//! summary-tree archival of the same transcripts lives in
+//! [`crate::openhuman::memory::tree`].
+//!
+//! ## Layout
+//!
+//! - [`types`] — the on-disk wire types (threads, messages, patches, hits).
+//! - [`tokenize`] — multilingual normalization + character n-gram tokenizer.
+//! - [`inverted_index`] — in-memory trigram/bigram index over message content.
+//! - [`store`] — the JSONL [`ConversationStore`] (append/read/update/delete,
+//! process-wide write serialization, warm-index cache, cross-thread search).
+//!
+//! The channel-persistence subscriber that mirrors inbound/processed channel
+//! turns into this store is the host's own [`super::bus`], not part of this
+//! subtree — see the note on the round trip below.
+//!
+//! # Why this code is here again (#5560)
+//!
+//! This store *originated* in OpenHuman as `memory_conversations`, was lifted
+//! out into the memory engine, and is now back. The lift was never justified
+//! by the engine: nothing in `tinycortex` ever called into this module, its
+//! only imports are `std` + `async_trait`/`chrono`/`parking_lot`/`serde`/
+//! `serde_json`/`uuid`, and its sole coupling to the rest of the engine was a
+//! one-line `from_config` constructor. It was, in effect, host code parked in
+//! a library, and it made up roughly half of this host's remaining
+//! `tinycortex::` call sites. Bringing it home is what lets the host stop
+//! compiling against that crate.
+//!
+//! ## What the round trip cost, and what did not come back
+//!
+//! The port out made four mechanical substitutions to avoid touching the
+//! engine's `Cargo.toml`. All four are kept, and it is worth being explicit
+//! that three of them are kept for a *different* reason than the one that
+//! introduced them — `hex` and `tempfile` are both ordinary dependencies of
+//! this crate, so nothing forces the substitutions any more:
+//!
+//! - `once_cell::sync::Lazy` → [`std::sync::LazyLock`] for the process-wide
+//! statics. Same semantics, and `LazyLock` is std now, so there is nothing
+//! to undo.
+//! - `hex::encode` → the local `hex_encode` helper for per-thread filenames.
+//! This one function derives the path every existing transcript already
+//! lives at, so it stays byte-for-byte the code that wrote them.
+//! - `tempfile::NamedTempFile` → write-to-temp + atomic-rename in
+//! `rewrite_jsonl`. Restoring `NamedTempFile` would change the temp file's
+//! name, its permissions and who deletes it on failure — a real change to
+//! the crash-safety path for a user's transcript, dressed as a cleanup.
+//! - OpenHuman's `log`/`tracing` diagnostics were dropped because the engine
+//! had no logging facade. That one is a genuine loss rather than a wash, and
+//! re-adding the lines is still deliberately out of scope: it would mean
+//! edits inside the functions that write user transcripts, on a change whose
+//! entire claim is that nothing behavioural moved.
+//!
+//! Undoing any of the last three is a reasonable follow-up. It is a *separate*
+//! follow-up, reviewed on its own merits, with the diff visible — not a
+//! tidy-up smuggled into a move.
+//!
+//! The engine's `bus.rs` did not come back either. It existed only to abstract
+//! the host's event bus behind a `ConversationEventBus` trait so the engine
+//! could carry the subscriber without depending on the host's channel layer.
+//! The host never used it — [`super::bus`] has always held the live subscriber,
+//! wired directly to `core::bus::BUS` and to the real
+//! `conversation_history_key`. With the store back home, the abstraction has
+//! nothing left to abstract, so the host's version is simply repointed at the
+//! local store and the engine's copy is left where it is.
+
+mod inverted_index;
+#[allow(clippy::module_inception)]
+mod store;
+mod tokenize;
+mod types;
+
+pub use store::{
+ append_message, delete_thread, ensure_thread, get_messages, list_threads, purge_threads,
+ update_message, update_thread_labels, update_thread_title, ConversationPurgeStats,
+ ConversationStore,
+};
+pub use types::{
+ ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
+ CrossThreadHit,
+};
diff --git a/src/openhuman/memory/conversations/store/store.rs b/src/openhuman/memory/conversations/store/store.rs
new file mode 100644
index 0000000000..4dd82060eb
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/store.rs
@@ -0,0 +1,423 @@
+//! JSONL-backed thread and message store. Thread metadata lives in
+//! `threads.jsonl` (append-only upsert/delete log); each thread's messages
+//! are appended to a per-thread JSONL file under
+//! `threads/<hex(thread_id)>.jsonl` so arbitrary provider ids remain
+//! filesystem-safe.
+//!
+//! All on-disk mutations serialise through a single process-wide mutex so
+//! concurrent RPC handlers don't interleave writes.
+//!
+//! This file is the store as it came back from the memory engine (#5560),
+//! unchanged apart from the one constructor described below. The three
+//! dependency substitutions the round trip introduced — [`std::sync::LazyLock`]
+//! for the statics, the local [`hex_encode`] for per-thread filenames, and the
+//! hand-rolled temp-write in [`rewrite_jsonl`] — are all kept: they produce the
+//! bytes and the paths that every existing transcript already lives at, and a
+//! move must not rewrite those. See [`super`]'s module docs for the full
+//! accounting of what the trip cost.
+//!
+//! # The one thing that did change: `from_config`
+//!
+//! The engine's [`ConversationStore`] carried a second constructor,
+//! `from_config(&MemoryConfig)`, whose whole body was
+//! `Self::new(config.workspace.clone())`. It is gone rather than translated,
+//! and that is the point of the move: it was this module's *only* coupling to
+//! the rest of the engine, and re-expressing it here would either drag
+//! `MemoryConfig` back in or add a second name for a constructor that already
+//! exists. [`ConversationStore::new`] takes the workspace directory, every
+//! caller in this host already has one, and no caller ever used `from_config`
+//! — so nothing needed a translation and the derived on-disk root
+//! (`<workspace>/memory/conversations`, see `ConversationStore::root_dir` in
+//! `store_index.rs`) is byte-identical either way.
+//!
+//! # File split
+//!
+//! To respect the repo's file-size limit the `impl ConversationStore` is split
+//! across two child modules — [`ops`] (the public CRUD + search API) and
+//! [`index`] (private thread-folding and inverted-index helpers). Both are
+//! descendant modules of `store`, so they share access to the private statics,
+//! constants, log-entry enum, and JSONL helpers defined here.
+
+use std::collections::HashMap;
+use std::fs::{self, File, OpenOptions};
+use std::io::{BufRead, BufReader, Write};
+use std::path::{Path, PathBuf};
+use std::sync::LazyLock;
+
+use parking_lot::Mutex;
+use uuid::Uuid;
+
+use super::inverted_index::InvertedIndex;
+use super::types::{
+ ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
+};
+
+#[path = "store_ops.rs"]
+mod ops;
+
+#[path = "store_index.rs"]
+mod index;
+
+/// Filename of the append-only thread metadata log, relative to the
+/// `memory/conversations` root.
+pub(super) const THREADS_FILENAME: &str = "threads.jsonl";
+/// Subdirectory (relative to the `memory/conversations` root) holding the
+/// per-thread message JSONL files, named `<hex(thread_id)>.jsonl`.
+pub(super) const THREAD_MESSAGES_DIR: &str = "threads";
+
+/// Serialises every on-disk mutation so concurrent handlers can't interleave
+/// writes to `threads.jsonl` or the per-thread message logs.
+static CONVERSATION_STORE_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
+
+/// Per-workspace inverted index cache. Keyed by the workspace's
+/// `memory/conversations` root so multiple `ConversationStore` clones
+/// pointing at the same workspace share one index. The cache outlives
+/// individual store handles (which are cloneable PathBuf wrappers); it
+/// is bounded by the number of distinct workspaces a single process
+/// touches, which in practice is one. Tests using `TempDir` paths leave
+/// behind dead entries when the dir is removed — acceptable for an
+/// in-process cache.
+///
+/// # Lock ordering
+///
+/// When BOTH `CONVERSATION_STORE_LOCK` and `CONVERSATION_INDEX_CACHE`
+/// must be held simultaneously, `CONVERSATION_STORE_LOCK` MUST be
+/// acquired first. This applies to `append_message` (writes JSONL then
+/// updates the warm index) and `with_index` (caller holds the outer
+/// lock, then takes the cache lock to run the search closure).
+///
+/// `prime_index_if_cold` minimises shared locking. It may hold both
+/// locks only momentarily, and always in the `CONVERSATION_STORE_LOCK`
+/// → `CONVERSATION_INDEX_CACHE` order above: while holding the outer
+/// lock to snapshot live thread IDs via `thread_index_unlocked`
+/// (header-only, no per-thread I/O) it re-checks the cache once. It then
+/// releases `CONVERSATION_STORE_LOCK` before reading per-thread JSONL
+/// content (no lock held) and finally acquires `CONVERSATION_INDEX_CACHE`
+/// alone to insert the built index. It never holds both across the slow
+/// JSONL walk, and neither operation calls back into a function that
+/// would acquire the other lock.
+///
+/// `list_threads_unlocked` MUST NOT be used inside the locked snapshot —
+/// it calls `measure_messages_unlocked` per legacy thread (no Stats
+/// history), which reads every per-thread JSONL file and appends a
+/// `Stats` entry to `threads.jsonl`, reintroducing the multi-second
+/// stall under the outer lock that this design was built to avoid.
+static CONVERSATION_INDEX_CACHE: LazyLock<Mutex<HashMap<PathBuf, InvertedIndex>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+/// Counts returned by [`ConversationStore::purge_threads`] — how much was deleted.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct ConversationPurgeStats {
+ /// Number of threads removed.
+ pub thread_count: usize,
+ /// Total messages removed across all purged threads.
+ pub message_count: usize,
+}
+
+/// Workspace-rooted handle that reads and writes the JSONL conversation log.
+#[derive(Debug, Clone)]
+pub struct ConversationStore {
+ workspace_dir: PathBuf,
+}
+
+impl ConversationStore {
+ /// Construct a store rooted at the given workspace directory.
+ ///
+ /// This is the only constructor. The conversation root is derived from
+ /// `workspace_dir` alone (`<workspace>/memory/conversations`, see
+ /// `root_dir` in `store_index.rs`), so the caller's workspace is the whole
+ /// input and there is nothing for a config type to add.
+ pub fn new(workspace_dir: PathBuf) -> Self {
+ Self { workspace_dir }
+ }
+}
+
+/// One line in `threads.jsonl`. The append-only log is folded into the current
+/// thread state by [`ConversationStore::thread_index_unlocked`].
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(tag = "op", rename_all = "snake_case")]
+pub(super) enum ThreadLogEntry {
+ /// Create-or-replace the metadata for `thread_id`. The latest `Upsert`
+ /// wins when the log is folded; `op` wire string is `upsert`.
+ ///
+ /// NOTE (audit TR-8): `labels: Some(_)` always **replaces** the folded
+ /// label set (see `thread_index_unlocked`'s `Upsert` handling) — it is
+ /// not a merge. Callers that want to touch a thread without disturbing
+ /// its labels (e.g. per-message thread upserts) must pass `labels: None`;
+ /// `bus::persist_channel_turn` currently does not, and so resets a
+ /// user-set label back to `["general"]` on every channel message.
+ Upsert {
+ thread_id: String,
+ title: String,
+ created_at: String,
+ updated_at: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ parent_thread_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ labels: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ personality_id: Option<String>,
+ },
+ /// Tombstone removing `thread_id` from the folded state; `op` wire string
+ /// is `delete`.
+ Delete {
+ thread_id: String,
+ deleted_at: String,
+ },
+ /// Single message appended to a thread. Increments `message_count` by 1
+ /// and overwrites `last_message_at`. Emitted by `append_message` to keep
+ /// list_threads O(threads.jsonl) instead of O(total messages).
+ MessageAppended {
+ thread_id: String,
+ last_message_at: String,
+ },
+ /// Absolute stat snapshot — overrides the running count + timestamp.
+ /// Used to backfill legacy threads whose messages were written before
+ /// `MessageAppended` existed.
+ Stats {
+ thread_id: String,
+ message_count: usize,
+ last_message_at: String,
+ },
+}
+
+/// Folded current state for a single thread, derived from the log.
+#[derive(Debug, Clone)]
+pub(super) struct ThreadIndexEntry {
+ /// Human-readable thread title from the latest `Upsert`.
+ pub(super) title: String,
+ /// Thread creation timestamp from the first `Upsert`.
+ pub(super) created_at: String,
+ /// Parent thread id for nested/threaded conversations, if any.
+ pub(super) parent_thread_id: Option<String>,
+ /// Folded labels (already normalised/inferred) bucketing this thread.
+ pub(super) labels: Vec<String>,
+ /// Folded message count. `None` means we have no `MessageAppended` /
+ /// `Stats` history for this thread yet (legacy data) — `list_threads`
+ /// backfills by doing a one-shot read of the per-thread messages file.
+ pub(super) message_count: Option<usize>,
+ /// Timestamp of the newest message, or `None` if unknown (legacy).
+ pub(super) last_message_at: Option<String>,
+ /// Personality/persona id bound to this thread, if any.
+ pub(super) personality_id: Option<String>,
+}
+
+/// Default labels for a thread whose `Upsert` carried none, inferred from its
+/// id namespace (proactive briefings/notifications vs ordinary chats).
+pub(super) fn infer_labels(thread_id: &str) -> Vec<String> {
+ if thread_id == "proactive:morning_briefing" {
+ vec!["briefing".to_string()]
+ } else if thread_id.starts_with("proactive:") {
+ vec!["notification".to_string()]
+ } else {
+ vec!["general".to_string()]
+ }
+}
+
+/// Canonicalise legacy label spellings into their current buckets and dedupe.
+pub(super) fn normalize_labels(labels: Vec<String>) -> Vec<String> {
+ let mut normalized = Vec::with_capacity(labels.len());
+ for label in labels {
+ let next = match label.as_str() {
+ "work" => "general".to_string(),
+ "from_reflection" | "subconscious_tick" => "subconscious".to_string(),
+ "agent-task" | "worker" => "tasks".to_string(),
+ _ => label,
+ };
+ if !normalized.contains(&next) {
+ normalized.push(next);
+ }
+ }
+ normalized
+}
+
+/// Lowercase hex-encode bytes — used to derive a filesystem-safe per-thread
+/// messages filename from an arbitrary thread id.
+///
+/// This exists because the memory engine had no `hex` dependency; this crate
+/// does, so `hex::encode` would work here. It is kept anyway: this is the
+/// function that decides which file a user's transcript is read from and
+/// written to, and swapping it is only provably safe, never *obviously* safe.
+/// The three lines are cheaper than the argument.
+pub(super) fn hex_encode(bytes: &[u8]) -> String {
+ const HEX: [u8; 16] = *b"0123456789abcdef";
+ let mut out = String::with_capacity(bytes.len() * 2);
+ for &b in bytes {
+ out.push(HEX[(b >> 4) as usize] as char);
+ out.push(HEX[(b & 0x0f) as usize] as char);
+ }
+ out
+}
+
+/// Read a JSONL file into a vector, skipping blank and invalid lines so a
+/// single corrupt line never loses the rest of the transcript.
+pub(super) fn read_jsonl<T>(path: &Path) -> Result<Vec<T>, String>
+where
+ T: for<'de> serde::Deserialize<'de>,
+{
+ if !path.exists() {
+ return Ok(Vec::new());
+ }
+ let file = File::open(path).map_err(|e| format!("open {}: {e}", path.display()))?;
+ let reader = BufReader::new(file);
+ let mut items = Vec::new();
+ for (line_no, line) in reader.lines().enumerate() {
+ let line =
+ line.map_err(|e| format!("read {} line {}: {e}", path.display(), line_no + 1))?;
+ let trimmed = line.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ if let Ok(value) = serde_json::from_str::<T>(trimmed) {
+ items.push(value);
+ }
+ }
+ Ok(items)
+}
+
+/// Append one serialized value as a JSONL line, fsync'd before returning.
+pub(super) fn append_jsonl<T>(path: &Path, value: &T) -> Result<(), String>
+where
+ T: serde::Serialize,
+{
+ let parent = path
+ .parent()
+ .ok_or_else(|| format!("resolve parent dir for {}", path.display()))?;
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("create jsonl dir {}: {e}", parent.display()))?;
+ let mut file = OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(path)
+ .map_err(|e| format!("open {} for append: {e}", path.display()))?;
+ let line = serde_json::to_string(value)
+ .map_err(|e| format!("serialize jsonl line for {}: {e}", path.display()))?;
+ writeln!(file, "{line}").map_err(|e| format!("write {}: {e}", path.display()))?;
+ file.sync_all()
+ .map_err(|e| format!("sync {}: {e}", path.display()))?;
+ Ok(())
+}
+
+/// Atomically rewrite `path` with `values`, one JSON object per line.
+///
+/// Writes to a sibling temp file then renames over the target so a crash
+/// mid-write never leaves a partially-written transcript.
+///
+/// This hand-rolls what OpenHuman originally got from
+/// `tempfile::NamedTempFile`, because the memory engine carried `tempfile` as
+/// a dev-dependency only. This crate has it in full, so the substitution is no
+/// longer forced — but reverting it would change the temp file's name, its
+/// permissions, and which side deletes it when a write fails. That is a change
+/// to the crash-safety path for a user's transcript, and it belongs in a
+/// change that is about that, not in a module move.
+pub(super) fn rewrite_jsonl<T>(path: &Path, values: &[T]) -> Result<(), String>
+where
+ T: serde::Serialize,
+{
+ let parent = path
+ .parent()
+ .ok_or_else(|| format!("resolve parent dir for {}", path.display()))?;
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("create jsonl dir {}: {e}", parent.display()))?;
+ let tmp_path = parent.join(format!(".conversations-{}.tmp", Uuid::new_v4()));
+ let write_result = (|| -> Result<(), String> {
+ let mut temp = File::create(&tmp_path)
+ .map_err(|e| format!("create temp jsonl in {}: {e}", parent.display()))?;
+ for value in values {
+ let line = serde_json::to_string(value)
+ .map_err(|e| format!("serialize jsonl line for {}: {e}", path.display()))?;
+ writeln!(temp, "{line}")
+ .map_err(|e| format!("write temp jsonl for {}: {e}", path.display()))?;
+ }
+ temp.sync_all()
+ .map_err(|e| format!("sync temp jsonl for {}: {e}", path.display()))?;
+ Ok(())
+ })();
+ if let Err(error) = write_result {
+ let _ = fs::remove_file(&tmp_path);
+ return Err(error);
+ }
+ if let Err(error) = fs::rename(&tmp_path, path) {
+ let _ = fs::remove_file(&tmp_path);
+ return Err(format!("persist {}: {error}", path.display()));
+ }
+ Ok(())
+}
+
+/// Free-function shim around [`ConversationStore::ensure_thread`].
+pub fn ensure_thread(
+ workspace_dir: PathBuf,
+ request: CreateConversationThread,
+) -> Result<ConversationThread, String> {
+ ConversationStore::new(workspace_dir).ensure_thread(request)
+}
+
+/// Free-function shim around [`ConversationStore::list_threads`].
+pub fn list_threads(workspace_dir: PathBuf) -> Result<Vec<ConversationThread>, String> {
+ ConversationStore::new(workspace_dir).list_threads()
+}
+
+/// Free-function shim around [`ConversationStore::get_messages`].
+pub fn get_messages(
+ workspace_dir: PathBuf,
+ thread_id: &str,
+) -> Result<Vec<ConversationMessage>, String> {
+ ConversationStore::new(workspace_dir).get_messages(thread_id)
+}
+
+/// Free-function shim around [`ConversationStore::append_message`].
+pub fn append_message(
+ workspace_dir: PathBuf,
+ thread_id: &str,
+ message: ConversationMessage,
+) -> Result<ConversationMessage, String> {
+ ConversationStore::new(workspace_dir).append_message(thread_id, message)
+}
+
+/// Free-function shim around [`ConversationStore::update_thread_title`].
+pub fn update_thread_title(
+ workspace_dir: PathBuf,
+ thread_id: &str,
+ title: &str,
+ updated_at: &str,
+) -> Result<ConversationThread, String> {
+ ConversationStore::new(workspace_dir).update_thread_title(thread_id, title, updated_at)
+}
+
+/// Free-function shim around [`ConversationStore::update_thread_labels`].
+pub fn update_thread_labels(
+ workspace_dir: PathBuf,
+ thread_id: &str,
+ labels: Vec<String>,
+ updated_at: &str,
+) -> Result<ConversationThread, String> {
+ ConversationStore::new(workspace_dir).update_thread_labels(thread_id, labels, updated_at)
+}
+
+/// Free-function shim around [`ConversationStore::update_message`].
+pub fn update_message(
+ workspace_dir: PathBuf,
+ thread_id: &str,
+ message_id: &str,
+ patch: ConversationMessagePatch,
+) -> Result<ConversationMessage, String> {
+ ConversationStore::new(workspace_dir).update_message(thread_id, message_id, patch)
+}
+
+/// Free-function shim around [`ConversationStore::purge_threads`].
+pub fn purge_threads(workspace_dir: PathBuf) -> Result<ConversationPurgeStats, String> {
+ ConversationStore::new(workspace_dir).purge_threads()
+}
+
+/// Free-function shim around [`ConversationStore::delete_thread`].
+pub fn delete_thread(
+ workspace_dir: PathBuf,
+ thread_id: &str,
+ deleted_at: &str,
+) -> Result<bool, String> {
+ ConversationStore::new(workspace_dir).delete_thread(thread_id, deleted_at)
+}
+
+#[cfg(test)]
+#[path = "store_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/conversations/store/store_index.rs b/src/openhuman/memory/conversations/store/store_index.rs
new file mode 100644
index 0000000000..ce4432201b
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/store_index.rs
@@ -0,0 +1,407 @@
+//! Internal thread-folding and inverted-index helpers for
+//! [`ConversationStore`]. Split out of `store.rs` to respect the repo's
+//! 500-line-per-file limit. Every method here is `pub(super)` so the public
+//! API in `store_ops.rs` (and the unit tests) can call it, but it stays out of
+//! the crate's public surface.
+
+use std::collections::BTreeMap;
+use std::fs::{self, File};
+use std::path::PathBuf;
+
+use super::super::inverted_index::InvertedIndex;
+use super::super::types::{ConversationMessage, ConversationThread};
+use super::{
+ append_jsonl, hex_encode, infer_labels, normalize_labels, read_jsonl, ConversationPurgeStats,
+ ConversationStore, ThreadIndexEntry, ThreadLogEntry, CONVERSATION_INDEX_CACHE,
+ CONVERSATION_STORE_LOCK, THREADS_FILENAME, THREAD_MESSAGES_DIR,
+};
+
+impl ConversationStore {
+ /// If no index entry exists for this workspace, snapshot the live thread
+ /// IDs under `CONVERSATION_STORE_LOCK` (fast — reads only `threads.jsonl`,
+ /// no per-thread I/O), release that lock, read all per-thread JSONL files
+ /// with no lock held (safe — append-only), then insert the built index
+ /// into `CONVERSATION_INDEX_CACHE` using `entry().or_insert()` so a
+ /// concurrent prime that finished first wins and ours is discarded.
+ ///
+ /// After this call returns, `with_index` will always find a warm entry and
+ /// will not re-enter `populate_index_unlocked`.
+ pub(super) fn prime_index_if_cold(&self) -> Result<(), String> {
+ let key = self.root_dir();
+ // Fast path: already warm — one tiny lock acquisition and out.
+ if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {
+ return Ok(());
+ }
+ // Snapshot live thread IDs while holding the outer lock.
+ // `thread_index_unlocked` reads only `threads.jsonl` (header-only,
+ // O(threads), no per-thread file I/O) — the lock is released
+ // immediately after, so the slow content reads below never block
+ // concurrent writers.
+ //
+ // Do NOT call `list_threads_unlocked` here. For workspaces where any
+ // thread has no `MessageAppended`/`Stats` history (common before the
+ // Stats log was introduced), `list_threads_unlocked` triggers
+ // `measure_messages_unlocked` + a `Stats` append per thread — all under
+ // `CONVERSATION_STORE_LOCK` — reintroducing the multi-second stall this
+ // function is designed to avoid.
+ let thread_ids: Vec<String> = {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ // Re-check after acquiring: a concurrent prime may have just
+ // finished while we waited for the outer lock.
+ if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {
+ return Ok(());
+ }
+ self.thread_index_unlocked()?.into_keys().collect()
+ };
+ // Build the index with no locks held. The per-thread JSONL files are
+ // append-only so reads are safe without synchronisation. A message
+ // appended during this window stays absent from the in-memory index
+ // until the next cold rebuild — the accepted tradeoff for issue #2849.
+ let mut idx = InvertedIndex::new();
+ for thread_id in &thread_ids {
+ let path = self.thread_messages_path(thread_id);
+ if !path.exists() {
+ continue;
+ }
+ if let Ok(messages) = read_jsonl::<ConversationMessage>(&path) {
+ for msg in messages {
+ idx.insert(thread_id, msg);
+ }
+ }
+ }
+ // Insert only if the key is still absent — a concurrent prime that
+ // finished first wins; ours is discarded.
+ {
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ cache.entry(key).or_insert(idx);
+ }
+ Ok(())
+ }
+
+ /// Acquire the cached inverted index for this workspace (building it from
+ /// JSONL on first access) and run `f` against it. Caller MUST hold
+ /// `CONVERSATION_STORE_LOCK` for the duration of the closure.
+ ///
+ /// In the normal path the index has already been warmed by
+ /// `prime_index_if_cold`, so the cold-build branch here is a safety net for
+ /// any future callers that bypass the priming step.
+ pub(super) fn with_index<R>(
+ &self,
+ f: impl FnOnce(&mut InvertedIndex) -> R,
+ ) -> Result<R, String> {
+ let key = self.root_dir();
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ if !cache.contains_key(&key) {
+ let mut idx = InvertedIndex::new();
+ self.populate_index_unlocked(&mut idx)?;
+ cache.insert(key.clone(), idx);
+ }
+ let idx = cache.get_mut(&key).expect("inserted above if absent");
+ Ok(f(idx))
+ }
+
+ /// Walk every per-thread JSONL file in the workspace and insert each
+ /// message into `idx`. Used as the fallback cold-build path inside
+ /// `with_index`; `prime_index_if_cold` handles the normal first-access
+ /// case outside the outer lock. The JSONL files are the source of truth so
+ /// a rebuild after a process crash is always safe.
+ pub(super) fn populate_index_unlocked(&self, idx: &mut InvertedIndex) -> Result<(), String> {
+ // Caller (`with_index`) already holds `CONVERSATION_STORE_LOCK`, so we
+ // must NOT re-acquire it here — `parking_lot::Mutex` is not reentrant
+ // and doing so would deadlock. Use the `_unlocked` thread reader
+ // directly.
+ let threads = self.list_threads_unlocked()?;
+ for thread in threads {
+ let path = self.thread_messages_path(&thread.id);
+ if !path.exists() {
+ continue;
+ }
+ let messages = match read_jsonl::<ConversationMessage>(&path) {
+ Ok(m) => m,
+ Err(_) => continue,
+ };
+ for msg in messages {
+ idx.insert(&thread.id, msg);
+ }
+ }
+ Ok(())
+ }
+
+ /// Ensure the `memory/conversations` directory tree (and an empty
+ /// `threads.jsonl`) exists, returning the conversation root.
+ pub(super) fn ensure_root(&self) -> Result<PathBuf, String> {
+ let root = self.root_dir();
+ let threads_dir = root.join(THREAD_MESSAGES_DIR);
+ fs::create_dir_all(&threads_dir)
+ .map_err(|e| format!("create conversation dir {}: {e}", threads_dir.display()))?;
+ let threads_file = root.join(THREADS_FILENAME);
+ if !threads_file.exists() {
+ File::create(&threads_file)
+ .map_err(|e| format!("create threads log {}: {e}", threads_file.display()))?;
+ }
+ Ok(root)
+ }
+
+ /// Absolute path to this workspace's `memory/conversations` root.
+ pub(super) fn root_dir(&self) -> PathBuf {
+ self.workspace_dir.join("memory").join("conversations")
+ }
+
+ /// Absolute path to a thread's per-thread messages JSONL file. The thread
+ /// id is hex-encoded so arbitrary ids map to filesystem-safe names.
+ pub(super) fn thread_messages_path(&self, thread_id: &str) -> PathBuf {
+ self.root_dir()
+ .join(THREAD_MESSAGES_DIR)
+ .join(format!("{}.jsonl", hex_encode(thread_id.as_bytes())))
+ }
+
+ pub(super) fn list_threads_unlocked(&self) -> Result<Vec<ConversationThread>, String> {
+ let mut index = self.thread_index_unlocked()?;
+ // Reconcile only cold/recovery entries whose derived stat trail is
+ // absent. Once stats exist, routine list calls stay header-only rather
+ // than rescanning every message file.
+ let thread_ids = index
+ .iter()
+ .filter(|(_, entry)| entry.message_count.is_none() || entry.last_message_at.is_none())
+ .map(|(thread_id, _)| thread_id.clone())
+ .collect::<Vec<_>>();
+ if !thread_ids.is_empty() {
+ let threads_path = self.ensure_root()?.join(THREADS_FILENAME);
+ for thread_id in &thread_ids {
+ let Ok((count, last_message_at)) = self.measure_messages_unlocked(thread_id) else {
+ // One unreadable transcript must not make thread
+ // navigation unavailable. Leave it unreconciled so a
+ // later call can retry after repair.
+ continue;
+ };
+ // Treat created_at as last_message_at when there are no
+ // messages — keeps the sort key meaningful and matches the
+ // pre-refactor semantics.
+ let resolved_last = last_message_at.unwrap_or_else(|| {
+ index
+ .get(thread_id)
+ .map(|e| e.created_at.clone())
+ .unwrap_or_default()
+ });
+ let differs = index.get(thread_id).is_none_or(|entry| {
+ entry.message_count != Some(count)
+ || entry.last_message_at.as_deref() != Some(resolved_last.as_str())
+ });
+ if differs {
+ append_jsonl(
+ &threads_path,
+ &ThreadLogEntry::Stats {
+ thread_id: thread_id.clone(),
+ message_count: count,
+ last_message_at: resolved_last.clone(),
+ },
+ )?;
+ }
+ if let Some(entry) = index.get_mut(thread_id) {
+ entry.message_count = Some(count);
+ entry.last_message_at = Some(resolved_last);
+ }
+ }
+ }
+
+ let mut threads: Vec<ConversationThread> = index
+ .iter()
+ .map(|(thread_id, entry)| {
+ let message_count = entry.message_count.unwrap_or(0);
+ let last_message_at = entry
+ .last_message_at
+ .clone()
+ .unwrap_or_else(|| entry.created_at.clone());
+ ConversationThread {
+ id: thread_id.clone(),
+ title: entry.title.clone(),
+ chat_id: None,
+ is_active: true,
+ message_count,
+ last_message_at,
+ created_at: entry.created_at.clone(),
+ parent_thread_id: entry.parent_thread_id.clone(),
+ labels: normalize_labels(entry.labels.clone()),
+ personality_id: entry.personality_id.clone(),
+ }
+ })
+ .collect();
+ threads.sort_by(|a, b| {
+ timestamp_millis(&b.last_message_at)
+ .cmp(&timestamp_millis(&a.last_message_at))
+ .then_with(|| timestamp_millis(&b.created_at).cmp(&timestamp_millis(&a.created_at)))
+ });
+ Ok(threads)
+ }
+
+ /// Count messages and find the newest timestamp by reading the per-thread
+ /// JSONL file. This is the authoritative source used to reconcile the
+ /// compact thread stat trail after either side of a two-file append crash.
+ pub(super) fn measure_messages_unlocked(
+ &self,
+ thread_id: &str,
+ ) -> Result<(usize, Option<String>), String> {
+ let path = self.thread_messages_path(thread_id);
+ if !path.exists() {
+ return Ok((0, None));
+ }
+ let messages = read_jsonl::<ConversationMessage>(&path)?;
+ let count = messages.len();
+ let last = messages.last().map(|m| m.created_at.clone());
+ Ok((count, last))
+ }
+
+ pub(super) fn thread_summary_unlocked(
+ &self,
+ thread_id: &str,
+ ) -> Result<Option<ConversationThread>, String> {
+ let index = self.thread_index_unlocked()?;
+ let entry = match index.get(thread_id) {
+ Some(entry) => entry,
+ None => return Ok(None),
+ };
+ let (message_count, last_message_at) = match (entry.message_count, &entry.last_message_at) {
+ (Some(count), Some(last)) => (count, last.clone()),
+ _ => match self.measure_messages_unlocked(thread_id) {
+ Ok((count, last)) => (count, last.unwrap_or_else(|| entry.created_at.clone())),
+ Err(_) => (
+ entry.message_count.unwrap_or(0),
+ entry
+ .last_message_at
+ .clone()
+ .unwrap_or_else(|| entry.created_at.clone()),
+ ),
+ },
+ };
+ Ok(Some(ConversationThread {
+ id: thread_id.to_string(),
+ title: entry.title.clone(),
+ chat_id: None,
+ is_active: true,
+ message_count,
+ last_message_at,
+ created_at: entry.created_at.clone(),
+ parent_thread_id: entry.parent_thread_id.clone(),
+ labels: normalize_labels(entry.labels.clone()),
+ personality_id: entry.personality_id.clone(),
+ }))
+ }
+
+ pub(super) fn thread_exists_unlocked(&self, thread_id: &str) -> Result<bool, String> {
+ Ok(self.thread_index_unlocked()?.contains_key(thread_id))
+ }
+
+ /// Fold `threads.jsonl` into the current per-thread state. Header-only:
+ /// reads no per-thread message files.
+ pub(super) fn thread_index_unlocked(
+ &self,
+ ) -> Result<BTreeMap<String, ThreadIndexEntry>, String> {
+ self.ensure_root()?;
+ let path = self.root_dir().join(THREADS_FILENAME);
+ let mut index: BTreeMap<String, ThreadIndexEntry> = BTreeMap::new();
+ for entry in read_jsonl::<ThreadLogEntry>(&path)? {
+ match entry {
+ ThreadLogEntry::Upsert {
+ thread_id,
+ title,
+ created_at,
+ parent_thread_id,
+ labels,
+ personality_id,
+ ..
+ } => {
+ let (
+ created_at_value,
+ parent_thread_id_value,
+ labels_value,
+ message_count_value,
+ last_message_at_value,
+ personality_id_value,
+ ) = match index.get(&thread_id) {
+ Some(existing) => (
+ existing.created_at.clone(),
+ parent_thread_id.or_else(|| existing.parent_thread_id.clone()),
+ labels
+ .map(normalize_labels)
+ .unwrap_or_else(|| existing.labels.clone()),
+ existing.message_count,
+ existing.last_message_at.clone(),
+ personality_id.or_else(|| existing.personality_id.clone()),
+ ),
+ None => {
+ let inferred = labels
+ .map(normalize_labels)
+ .unwrap_or_else(|| infer_labels(&thread_id));
+ (
+ created_at,
+ parent_thread_id,
+ inferred,
+ None,
+ None,
+ personality_id,
+ )
+ }
+ };
+ index.insert(
+ thread_id,
+ ThreadIndexEntry {
+ title,
+ created_at: created_at_value,
+ parent_thread_id: parent_thread_id_value,
+ labels: labels_value,
+ message_count: message_count_value,
+ last_message_at: last_message_at_value,
+ personality_id: personality_id_value,
+ },
+ );
+ }
+ ThreadLogEntry::Delete { thread_id, .. } => {
+ index.remove(&thread_id);
+ }
+ ThreadLogEntry::MessageAppended {
+ thread_id,
+ last_message_at,
+ } => {
+ if let Some(entry) = index.get_mut(&thread_id) {
+ // Increment from a known baseline. If we have no
+ // baseline yet (legacy thread with messages but no
+ // Stats snapshot), leave count as `None` so the
+ // backfill path in `list_threads_unlocked` can do the
+ // one-shot file read instead of producing a wrong "1"
+ // here.
+ if let Some(count) = entry.message_count.as_mut() {
+ *count += 1;
+ }
+ entry.last_message_at = Some(last_message_at);
+ }
+ }
+ ThreadLogEntry::Stats {
+ thread_id,
+ message_count,
+ last_message_at,
+ } => {
+ if let Some(entry) = index.get_mut(&thread_id) {
+ entry.message_count = Some(message_count);
+ entry.last_message_at = Some(last_message_at);
+ }
+ }
+ }
+ }
+ Ok(index)
+ }
+
+ pub(super) fn purge_stats_unlocked(&self) -> Result<ConversationPurgeStats, String> {
+ let threads = self.list_threads_unlocked()?;
+ let message_count = threads.iter().map(|thread| thread.message_count).sum();
+ Ok(ConversationPurgeStats {
+ thread_count: threads.len(),
+ message_count,
+ })
+ }
+}
+
+fn timestamp_millis(value: &str) -> i64 {
+ chrono::DateTime::parse_from_rfc3339(value)
+ .map(|timestamp| timestamp.timestamp_millis())
+ .unwrap_or(i64::MIN)
+}
diff --git a/src/openhuman/memory/conversations/store/store_ops.rs b/src/openhuman/memory/conversations/store/store_ops.rs
new file mode 100644
index 0000000000..1189cb1d16
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/store_ops.rs
@@ -0,0 +1,298 @@
+//! Public CRUD + search surface of [`ConversationStore`]. Split out of
+//! `store.rs` to keep each source file under the repo's 500-line limit; this
+//! is a descendant module of `store`, so it shares access to the private
+//! statics, log-entry enum, and JSONL helpers defined there.
+
+use std::fs;
+
+use super::super::types::{
+ ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
+ CrossThreadHit,
+};
+use super::{
+ append_jsonl, normalize_labels, read_jsonl, rewrite_jsonl, ConversationPurgeStats,
+ ConversationStore, ThreadLogEntry, CONVERSATION_INDEX_CACHE, CONVERSATION_STORE_LOCK,
+ THREADS_FILENAME,
+};
+
+impl ConversationStore {
+ /// Create or update a thread, appending an `Upsert` entry to `threads.jsonl`.
+ pub fn ensure_thread(
+ &self,
+ request: CreateConversationThread,
+ ) -> Result<ConversationThread, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ let root = self.ensure_root()?;
+ let threads_path = root.join(THREADS_FILENAME);
+ let now = request.created_at.clone();
+ let labels = request.labels.clone().map(normalize_labels);
+ append_jsonl(
+ &threads_path,
+ &ThreadLogEntry::Upsert {
+ thread_id: request.id.clone(),
+ title: request.title.clone(),
+ created_at: request.created_at.clone(),
+ updated_at: now,
+ parent_thread_id: request.parent_thread_id.clone(),
+ labels,
+ personality_id: request.personality_id.clone(),
+ },
+ )?;
+ self.thread_summary_unlocked(&request.id)?
+ .ok_or_else(|| format!("thread {} missing after ensure", request.id))
+ }
+
+ /// List all live threads (folding the upsert/delete log).
+ pub fn list_threads(&self) -> Result<Vec<ConversationThread>, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ self.list_threads_unlocked()
+ }
+
+ /// Read every persisted message for a thread in append order.
+ pub fn get_messages(&self, thread_id: &str) -> Result<Vec<ConversationMessage>, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ if !self.thread_exists_unlocked(thread_id)? {
+ return Ok(Vec::new());
+ }
+ let path = self.thread_messages_path(thread_id);
+ if !path.exists() {
+ return Ok(Vec::new());
+ }
+ read_jsonl::<ConversationMessage>(&path)
+ }
+
+ /// Substring-match messages across **every** thread in the workspace,
+ /// optionally excluding one thread (the active chat). Returns up to
+ /// `limit` of the most-recent matching messages, newest first.
+ ///
+ /// Workspace scope is enforced by the store's `workspace_dir` — one
+ /// workspace dir per user — so this helper cannot cross that boundary.
+ /// Issue #1505: the conversational durable-fact pipeline is async and
+ /// batched, so cross-chat continuity needs a direct cross-thread reader to
+ /// surface context the user shared in chat A when they ask a dependent
+ /// question in chat B.
+ ///
+ /// Backed by an in-memory trigram/CJK-bigram inverted index
+ /// (`super::super::inverted_index`). The legacy implementation walked every
+ /// JSONL file and did `content.to_lowercase().contains(term)` per message,
+ /// which is O(threads × messages × content_len). The index turns that into
+ /// O(|posting lists|) for typical queries while preserving the previous
+ /// scoring contract (`score = matched_terms / total_terms`, recency
+ /// tiebreak).
+ ///
+ /// # Lock strategy (issue #2849)
+ ///
+ /// **Fast path (warm cache):** acquires only `CONVERSATION_INDEX_CACHE`
+ /// — no outer store lock — and returns immediately.
+ ///
+ /// **Cold path (first access):** snapshots the thread list under
+ /// `CONVERSATION_STORE_LOCK` (brief), then releases it before reading JSONL
+ /// files to build the inverted index. This avoids blocking other store
+ /// operations during the potentially-long rebuild. JSONL files are
+ /// append-only, so a concurrent write during the rebuild may mean the
+ /// rebuilt index misses that one message until the cache is evicted and
+ /// rebuilt — an accepted tradeoff for issue #2849.
+ pub fn search_cross_thread_messages(
+ &self,
+ query: &str,
+ limit: usize,
+ exclude_thread_id: Option<&str>,
+ ) -> Result<Vec<CrossThreadHit>, String> {
+ // Warm the index outside the outer lock so concurrent
+ // append_message / get_messages calls are not stalled during the
+ // cold JSONL rebuild. After this returns the cache entry is
+ // guaranteed to exist, so with_index will not trigger a second
+ // rebuild.
+ self.prime_index_if_cold()?;
+
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ self.with_index(|idx| idx.search(query, limit, exclude_thread_id))
+ }
+
+ /// Append a message to the thread's JSONL file. Errors if the thread is missing.
+ ///
+ /// Persists via two separate fsync'd appends — the authoritative message
+ /// row, then a compact `MessageAppended` stat entry. Thread reads reconcile
+ /// that stat trail against the message file, repairing a crash between the
+ /// two appends.
+ pub fn append_message(
+ &self,
+ thread_id: &str,
+ message: ConversationMessage,
+ ) -> Result<ConversationMessage, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ if !self.thread_exists_unlocked(thread_id)? {
+ return Err(format!("thread {} not found", thread_id));
+ }
+ let path = self.thread_messages_path(thread_id);
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("create conversation dir {}: {e}", parent.display()))?;
+ }
+ append_jsonl(&path, &message)?;
+ // Bump the threads-log stat trail so subsequent `list_threads`
+ // calls can compute (message_count, last_message_at) without
+ // re-reading this file.
+ let threads_path = self.root_dir().join(THREADS_FILENAME);
+ append_jsonl(
+ &threads_path,
+ &ThreadLogEntry::MessageAppended {
+ thread_id: thread_id.to_string(),
+ last_message_at: message.created_at.clone(),
+ },
+ )?;
+ // Keep the inverted index in sync. We only update if the index has
+ // already been materialized for this workspace — otherwise the next
+ // search will lazily rebuild and pick up this message anyway, and we
+ // avoid paying the rebuild cost on a write path.
+ {
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ if let Some(idx) = cache.get_mut(&self.root_dir()) {
+ idx.insert(thread_id, message.clone());
+ }
+ }
+ Ok(message)
+ }
+
+ /// Rewrite the thread title via a new `Upsert` log entry, preserving labels.
+ pub fn update_thread_title(
+ &self,
+ thread_id: &str,
+ title: &str,
+ updated_at: &str,
+ ) -> Result<ConversationThread, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ let index = self.thread_index_unlocked()?;
+ let entry = index
+ .get(thread_id)
+ .ok_or_else(|| format!("thread {} not found", thread_id))?;
+ let threads_path = self.ensure_root()?.join(THREADS_FILENAME);
+ append_jsonl(
+ &threads_path,
+ &ThreadLogEntry::Upsert {
+ thread_id: thread_id.to_string(),
+ title: title.to_string(),
+ created_at: entry.created_at.clone(),
+ updated_at: updated_at.to_string(),
+ parent_thread_id: entry.parent_thread_id.clone(),
+ labels: Some(entry.labels.clone()),
+ personality_id: entry.personality_id.clone(),
+ },
+ )?;
+ self.thread_summary_unlocked(thread_id)?
+ .ok_or_else(|| format!("thread {} missing after title update", thread_id))
+ }
+
+ /// Replace the label set on a thread via a new `Upsert` log entry.
+ pub fn update_thread_labels(
+ &self,
+ thread_id: &str,
+ labels: Vec<String>,
+ updated_at: &str,
+ ) -> Result<ConversationThread, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ let index = self.thread_index_unlocked()?;
+ let entry = index
+ .get(thread_id)
+ .ok_or_else(|| format!("thread {} not found", thread_id))?;
+ let threads_path = self.ensure_root()?.join(THREADS_FILENAME);
+ let labels = normalize_labels(labels);
+ append_jsonl(
+ &threads_path,
+ &ThreadLogEntry::Upsert {
+ thread_id: thread_id.to_string(),
+ title: entry.title.clone(),
+ created_at: entry.created_at.clone(),
+ updated_at: updated_at.to_string(),
+ parent_thread_id: entry.parent_thread_id.clone(),
+ labels: Some(labels),
+ personality_id: entry.personality_id.clone(),
+ },
+ )?;
+ self.thread_summary_unlocked(thread_id)?
+ .ok_or_else(|| format!("thread {} missing after labels update", thread_id))
+ }
+
+ /// Apply a patch to one message and rewrite the thread's JSONL file in place.
+ pub fn update_message(
+ &self,
+ thread_id: &str,
+ message_id: &str,
+ patch: ConversationMessagePatch,
+ ) -> Result<ConversationMessage, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ let path = self.thread_messages_path(thread_id);
+ let mut messages = read_jsonl::<ConversationMessage>(&path)?;
+ let mut updated: Option<ConversationMessage> = None;
+ for message in &mut messages {
+ if message.id == message_id {
+ if let Some(extra_metadata) = patch.extra_metadata.clone() {
+ message.extra_metadata = extra_metadata;
+ }
+ updated = Some(message.clone());
+ break;
+ }
+ }
+ let updated = updated
+ .ok_or_else(|| format!("message {} not found in thread {}", message_id, thread_id))?;
+ rewrite_jsonl(&path, &messages)?;
+ Ok(updated)
+ }
+
+ /// Append a `Delete` entry and remove the thread's messages file. Returns
+ /// `false` if the thread did not exist.
+ pub fn delete_thread(&self, thread_id: &str, deleted_at: &str) -> Result<bool, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ if !self.thread_exists_unlocked(thread_id)? {
+ return Ok(false);
+ }
+ let root = self.ensure_root()?;
+ let threads_path = root.join(THREADS_FILENAME);
+ append_jsonl(
+ &threads_path,
+ &ThreadLogEntry::Delete {
+ thread_id: thread_id.to_string(),
+ deleted_at: deleted_at.to_string(),
+ },
+ )?;
+ let messages_path = self.thread_messages_path(thread_id);
+ match fs::remove_file(&messages_path) {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => {
+ return Err(format!(
+ "delete conversation messages {}: {error}",
+ messages_path.display()
+ ));
+ }
+ }
+ // Drop every indexed message for this thread so future searches
+ // don't surface stale content.
+ {
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ if let Some(idx) = cache.get_mut(&self.root_dir()) {
+ idx.remove_thread(thread_id);
+ }
+ }
+ Ok(true)
+ }
+
+ /// Wipe the entire conversation directory and re-create an empty layout.
+ pub fn purge_threads(&self) -> Result<ConversationPurgeStats, String> {
+ let _guard = CONVERSATION_STORE_LOCK.lock();
+ let stats = self.purge_stats_unlocked()?;
+ let root = self.root_dir();
+ if root.exists() {
+ fs::remove_dir_all(&root)
+ .map_err(|e| format!("remove conversation dir {}: {e}", root.display()))?;
+ }
+ self.ensure_root()?;
+ // Drop the cached inverted index — the workspace is now empty, and any
+ // next search will lazily rebuild from the (now empty) JSONL tree.
+ {
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ cache.remove(&root);
+ }
+ Ok(stats)
+ }
+}
diff --git a/src/openhuman/memory/conversations/store/store_tests.rs b/src/openhuman/memory/conversations/store/store_tests.rs
new file mode 100644
index 0000000000..a47d879ffa
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/store_tests.rs
@@ -0,0 +1,472 @@
+//! Unit tests for the JSONL-backed [`ConversationStore`], exercising thread
+//! upsert, message append, label/title updates, deletion and purge semantics.
+
+use tempfile::TempDir;
+
+use super::*;
+use serde_json::json;
+
+fn make_store() -> (TempDir, ConversationStore) {
+ let temp = TempDir::new().expect("tempdir");
+ let store = ConversationStore::new(temp.path().to_path_buf());
+ (temp, store)
+}
+
+#[test]
+fn store_roundtrips_threads_and_messages() {
+ let (_temp, store) = make_store();
+ let created_at = "2026-04-10T12:00:00Z".to_string();
+ let thread = store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "default-thread".to_string(),
+ title: "Conversation".to_string(),
+ created_at: created_at.clone(),
+ labels: None,
+ personality_id: None,
+ })
+ .expect("ensure thread");
+ assert_eq!(thread.message_count, 0);
+
+ store
+ .append_message(
+ "default-thread",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "hello".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .expect("append message");
+
+ let threads = store.list_threads().expect("list threads");
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].message_count, 1);
+ assert_eq!(threads[0].last_message_at, "2026-04-10T12:01:00Z");
+
+ let messages = store.get_messages("default-thread").expect("get messages");
+ assert_eq!(messages.len(), 1);
+ assert_eq!(messages[0].content, "hello");
+}
+
+#[test]
+fn get_messages_for_new_empty_thread_returns_empty_list() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "empty-thread".to_string(),
+ title: "Conversation".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .expect("ensure thread");
+
+ let messages = store.get_messages("empty-thread").expect("get messages");
+ assert!(messages.is_empty());
+}
+
+#[test]
+fn store_updates_message_metadata() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "default-thread".to_string(),
+ title: "Conversation".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .expect("ensure thread");
+ store
+ .append_message(
+ "default-thread",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "hello".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .expect("append message");
+
+ let updated = store
+ .update_message(
+ "default-thread",
+ "m1",
+ ConversationMessagePatch {
+ extra_metadata: Some(json!({ "myReactions": ["👍"] })),
+ },
+ )
+ .expect("update message");
+
+ assert_eq!(updated.extra_metadata, json!({ "myReactions": ["👍"] }));
+ let messages = store.get_messages("default-thread").expect("get messages");
+ assert_eq!(messages[0].extra_metadata, json!({ "myReactions": ["👍"] }));
+}
+
+#[test]
+fn purge_removes_threads_and_messages() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "default-thread".to_string(),
+ title: "Conversation".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .expect("ensure thread");
+ store
+ .append_message(
+ "default-thread",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "hello".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .expect("append message");
+
+ let stats = store.purge_threads().expect("purge");
+ assert_eq!(stats.thread_count, 1);
+ assert_eq!(stats.message_count, 1);
+ assert!(store.list_threads().expect("list threads").is_empty());
+}
+
+#[test]
+fn ensure_thread_is_idempotent() {
+ let (_temp, store) = make_store();
+ let req = CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "Thread".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ };
+ store.ensure_thread(req.clone()).unwrap();
+ store.ensure_thread(req).unwrap();
+ let threads = store.list_threads().unwrap();
+ assert_eq!(threads.len(), 1);
+}
+
+#[test]
+fn delete_thread_removes_thread_and_messages() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "Thread".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "t1",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "msg".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+ store.delete_thread("t1", "2026-04-10T12:02:00Z").unwrap();
+ let threads = store.list_threads().unwrap();
+ assert!(threads.is_empty());
+}
+
+#[test]
+fn delete_nonexistent_thread_is_ok() {
+ let (_temp, store) = make_store();
+ // Should not error
+ store
+ .delete_thread("nonexistent", "2026-04-10T12:00:00Z")
+ .unwrap();
+}
+
+#[test]
+fn get_messages_empty_thread() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "Empty".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ let messages = store.get_messages("t1").unwrap();
+ assert!(messages.is_empty());
+}
+
+#[test]
+fn get_messages_nonexistent_thread() {
+ let (_temp, store) = make_store();
+ let messages = store.get_messages("nonexistent").unwrap();
+ assert!(messages.is_empty());
+}
+
+#[test]
+fn multiple_threads_and_messages() {
+ let (_temp, store) = make_store();
+ for i in 0..3 {
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: format!("t{i}"),
+ title: format!("Thread {i}"),
+ created_at: format!("2026-04-10T12:0{i}:00Z"),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ &format!("t{i}"),
+ ConversationMessage {
+ id: format!("m{i}"),
+ content: format!("msg {i}"),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: format!("2026-04-10T12:0{i}:30Z"),
+ },
+ )
+ .unwrap();
+ }
+ let threads = store.list_threads().unwrap();
+ assert_eq!(threads.len(), 3);
+}
+
+#[test]
+fn purge_on_empty_store() {
+ let (_temp, store) = make_store();
+ let stats = store.purge_threads().unwrap();
+ assert_eq!(stats.thread_count, 0);
+ assert_eq!(stats.message_count, 0);
+}
+
+#[test]
+fn update_message_nonexistent_returns_error() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "Thread".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ let result = store.update_message(
+ "t1",
+ "nonexistent",
+ ConversationMessagePatch {
+ extra_metadata: Some(json!({})),
+ },
+ );
+ assert!(result.is_err());
+}
+
+#[test]
+fn update_thread_title_persists_latest_title() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "Chat Apr 10 12:00 PM".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+
+ let updated = store
+ .update_thread_title("t1", "Invoice follow-up", "2026-04-10T12:03:00Z")
+ .unwrap();
+
+ assert_eq!(updated.title, "Invoice follow-up");
+ let threads = store.list_threads().unwrap();
+ assert_eq!(threads[0].title, "Invoice follow-up");
+ assert_eq!(threads[0].created_at, "2026-04-10T12:00:00Z");
+}
+
+#[test]
+fn store_handles_labels_and_inference() {
+ let (_temp, store) = make_store();
+
+ // 1. Explicit labels on ensure
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "Thread 1".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: Some(vec!["custom".to_string()]),
+ personality_id: None,
+ })
+ .unwrap();
+
+ // 2. Inferred labels for morning briefing
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "proactive:morning_briefing".to_string(),
+ title: "Morning Briefing".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+
+ // 3. Inferred labels for other proactive
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "proactive:system".to_string(),
+ title: "System Notification".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+
+ // 4. Default inferred labels (general)
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "user-thread".to_string(),
+ title: "User Chat".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+
+ // 5. Legacy explicit labels normalize into their canonical buckets.
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "legacy-work-thread".to_string(),
+ title: "Legacy Work Chat".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: Some(vec![
+ "work".to_string(),
+ "urgent".to_string(),
+ "work".to_string(),
+ ]),
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "legacy-subconscious-thread".to_string(),
+ title: "Legacy Subconscious Chat".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: Some(vec![
+ "from_reflection".to_string(),
+ "subconscious_tick".to_string(),
+ ]),
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "legacy-task-thread".to_string(),
+ title: "Legacy Task Chat".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: Some(vec!["agent-task".to_string(), "worker".to_string()]),
+ personality_id: None,
+ })
+ .unwrap();
+
+ let threads = store.list_threads().unwrap();
+ {
+ let t1 = threads.iter().find(|t| t.id == "t1").unwrap();
+ assert_eq!(t1.labels, vec!["custom"]);
+ }
+ {
+ let mb = threads
+ .iter()
+ .find(|t| t.id == "proactive:morning_briefing")
+ .unwrap();
+ assert_eq!(mb.labels, vec!["briefing"]);
+ }
+ {
+ let sys = threads.iter().find(|t| t.id == "proactive:system").unwrap();
+ assert_eq!(sys.labels, vec!["notification"]);
+ }
+ {
+ let user = threads.iter().find(|t| t.id == "user-thread").unwrap();
+ assert_eq!(user.labels, vec!["general"]);
+ }
+ {
+ let legacy = threads
+ .iter()
+ .find(|t| t.id == "legacy-work-thread")
+ .unwrap();
+ assert_eq!(legacy.labels, vec!["general", "urgent"]);
+ }
+ {
+ let legacy = threads
+ .iter()
+ .find(|t| t.id == "legacy-subconscious-thread")
+ .unwrap();
+ assert_eq!(legacy.labels, vec!["subconscious"]);
+ }
+ {
+ let legacy = threads
+ .iter()
+ .find(|t| t.id == "legacy-task-thread")
+ .unwrap();
+ assert_eq!(legacy.labels, vec!["tasks"]);
+ }
+
+ // 6. Update labels
+ store
+ .update_thread_labels("t1", vec!["updated".to_string()], "2026-04-10T12:05:00Z")
+ .unwrap();
+ let threads = store.list_threads().unwrap();
+ {
+ let t1 = threads.iter().find(|t| t.id == "t1").unwrap();
+ assert_eq!(t1.labels, vec!["updated"]);
+ }
+
+ // 7. Title update preserves labels
+ store
+ .update_thread_title("t1", "New Title", "2026-04-10T12:06:00Z")
+ .unwrap();
+ let threads = store.list_threads().unwrap();
+ {
+ let t1 = threads.iter().find(|t| t.id == "t1").unwrap();
+ assert_eq!(t1.labels, vec!["updated"]);
+ assert_eq!(t1.title, "New Title");
+ }
+}
+
+#[path = "store_tests_more.rs"]
+mod more;
diff --git a/src/openhuman/memory/conversations/store/store_tests_late.rs b/src/openhuman/memory/conversations/store/store_tests_late.rs
new file mode 100644
index 0000000000..4927ae2dac
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/store_tests_late.rs
@@ -0,0 +1,478 @@
+use super::*;
+
+#[test]
+fn search_cross_thread_messages_finds_japanese_bigram_match() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "thread-jp".to_string(),
+ title: "JP".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "thread-jp",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "明日東京に行きます".to_string(), // "Tomorrow I'm going to Tokyo"
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+
+ let hits = store
+ .search_cross_thread_messages("東京", 10, None)
+ .expect("cross-thread search");
+ assert_eq!(hits.len(), 1, "CJK bigram lookup should find 東京");
+ assert_eq!(hits[0].message_id, "m1");
+}
+
+#[test]
+fn search_cross_thread_messages_rebuilds_index_from_jsonl_after_reopen() {
+ // First store handle writes messages, second handle (simulating
+ // process restart on the same workspace dir) must lazy-rebuild the
+ // index from JSONL and still answer search queries.
+ let temp = TempDir::new().expect("tempdir");
+ let workspace = temp.path().to_path_buf();
+ {
+ let store = ConversationStore::new(workspace.clone());
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "thread-x".to_string(),
+ title: "X".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "thread-x",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "persisted across reopen — checksum kitten".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+ }
+ // The cache key is per-workspace path; this TempDir was never seen
+ // before, so a fresh store handle will trigger a lazy rebuild.
+ let reopened = ConversationStore::new(workspace);
+ let hits = reopened
+ .search_cross_thread_messages("kitten", 10, None)
+ .expect("cross-thread search");
+ assert_eq!(hits.len(), 1, "reopened store must rebuild index from disk");
+}
+
+#[test]
+fn update_thread_labels_missing_thread_returns_error() {
+ let (_temp, store) = make_store();
+ let err = store
+ .update_thread_labels("missing", vec!["work".into()], "2026-04-10T12:05:00Z")
+ .unwrap_err();
+ assert!(err.contains("thread missing not found"));
+}
+
+#[test]
+fn cold_search_does_not_serialize_on_outer_lock() {
+ // Issue #2849: verify that a cold-cache search releases the store
+ // lock before the JSONL rebuild, so concurrent writes aren't blocked.
+ let (_temp, store) = make_store();
+
+ // Seed a thread with a message so the search has something to find.
+ store
+ .ensure_thread(CreateConversationThread {
+ id: "t1".to_string(),
+ title: "test thread".to_string(),
+ created_at: "2026-01-01T00:00:00Z".to_string(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "t1",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "hello world".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-01-01T00:00:00Z".to_string(),
+ },
+ )
+ .unwrap();
+
+ // Evict any warm cache so the next search triggers a cold rebuild.
+ {
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ cache.remove(&store.root_dir());
+ }
+
+ // Spawn a thread that tries to append a message while a cold search
+ // is (conceptually) running. In the old code this would deadlock or
+ // serialize behind the full rebuild; in the fixed code the store lock
+ // is released after the thread-list snapshot and the append succeeds
+ // concurrently.
+ let store2 = store.clone();
+ let writer = std::thread::spawn(move || {
+ store2
+ .append_message(
+ "t1",
+ ConversationMessage {
+ id: "m2".to_string(),
+ content: "concurrent write".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "assistant".to_string(),
+ created_at: "2026-01-01T00:00:01Z".to_string(),
+ },
+ )
+ .unwrap();
+ });
+
+ // Run the cold search — should not deadlock.
+ let results = store
+ .search_cross_thread_messages("hello", 10, None)
+ .unwrap();
+ assert!(!results.is_empty(), "search should find seeded message");
+
+ // The concurrent write must also succeed.
+ writer.join().expect("concurrent write must not deadlock");
+}
+
+#[test]
+fn read_jsonl_skips_invalid_lines_but_keeps_valid_ones() {
+ let tmp = TempDir::new().unwrap();
+ let path = tmp.path().join("messages.jsonl");
+ std::fs::write(
+ &path,
+ concat!(
+ "{\"id\":\"m1\",\"content\":\"ok\",\"type\":\"text\",\"extraMetadata\":{},\"sender\":\"user\",\"createdAt\":\"2026-04-10T12:00:00Z\"}\n",
+ "{not valid json}\n",
+ "{\"id\":\"m2\",\"content\":\"ok2\",\"type\":\"text\",\"extraMetadata\":{},\"sender\":\"agent\",\"createdAt\":\"2026-04-10T12:01:00Z\"}\n"
+ ),
+ )
+ .unwrap();
+
+ let messages: Vec<ConversationMessage> = read_jsonl(&path).expect("read jsonl");
+ assert_eq!(messages.len(), 2);
+ assert_eq!(messages[0].id, "m1");
+ assert_eq!(messages[1].id, "m2");
+}
+
+// ── concurrency: search cold rebuild must not block concurrent append ────────
+
+/// Regression test for issue #2849.
+///
+/// Before the fix, `search_cross_thread_messages` held `CONVERSATION_STORE_LOCK`
+/// for the entire cold index rebuild, stalling every concurrent
+/// `append_message` call for as long as the rebuild took. The fix
+/// moves the rebuild outside the outer lock (`prime_index_if_cold`), so
+/// an append in flight during a cold rebuild acquires the outer lock
+/// independently and completes promptly.
+///
+/// The test seeds a fresh workspace (cold cache), races a search against
+/// an append using a barrier, and asserts the append finishes within a
+/// generous timeout that would be violated if the two operations were
+/// serialised through the outer lock.
+#[test]
+fn search_cold_rebuild_does_not_block_concurrent_append() {
+ use std::sync::{mpsc, Arc, Barrier};
+ use std::thread;
+ use std::time::Duration;
+
+ let ts = "2026-04-10T12:00:00Z".to_string();
+
+ // Fresh TempDir → path never seen by the process-level cache → cold.
+ // Note: append_message only updates an *existing* cache entry; it never
+ // inserts one, so the cache stays cold until the first search call.
+ let temp = TempDir::new().unwrap();
+ let store = ConversationStore::new(temp.path().to_path_buf());
+
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "Rebuild thread".to_string(),
+ created_at: ts.clone(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+
+ // Seed enough messages to give the rebuild real work.
+ for i in 0..200_usize {
+ store
+ .append_message(
+ "t1",
+ ConversationMessage {
+ id: format!("seed-{i}"),
+ content: format!("seed message {i} for cold rebuild test"),
+ message_type: "text".to_string(),
+ extra_metadata: serde_json::json!({}),
+ sender: "user".to_string(),
+ created_at: ts.clone(),
+ },
+ )
+ .unwrap();
+ }
+
+ let store_search = store.clone();
+ let store_append = store.clone();
+
+ // Both threads start at the same time.
+ let barrier = Arc::new(Barrier::new(2));
+ let b_search = Arc::clone(&barrier);
+ let b_append = Arc::clone(&barrier);
+
+ let search_handle = thread::spawn(move || {
+ b_search.wait();
+ store_search.search_cross_thread_messages("seed message", 5, None)
+ });
+
+ let (tx, rx) = mpsc::channel();
+ thread::spawn(move || {
+ b_append.wait();
+ let result = store_append.append_message(
+ "t1",
+ ConversationMessage {
+ id: "concurrent-append".to_string(),
+ content: "written during cold rebuild".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: serde_json::json!({}),
+ sender: "user".to_string(),
+ created_at: ts,
+ },
+ );
+ let _ = tx.send(result);
+ });
+
+ // append_message must complete even if the rebuild is in progress. On the
+ // old code this blocked for the full rebuild duration; on fixed code the
+ // two operations proceed concurrently. The 30 s budget tolerates a slow CI
+ // runner — a genuine deadlock never completes, so a regression still fails.
+ let append_result = rx
+ .recv_timeout(Duration::from_secs(30))
+ .expect("append_message did not complete within 30 s — likely blocked by cold rebuild");
+ assert!(
+ append_result.is_ok(),
+ "append failed: {:?}",
+ append_result.err()
+ );
+
+ let search_result = search_handle.join().expect("search thread panicked");
+ assert!(
+ search_result.is_ok(),
+ "search failed: {:?}",
+ search_result.err()
+ );
+}
+
+// ── legacy workspace (pre-Stats backfill path) ───────────────────────────────
+
+/// Regression test for issue #2849 (backfill path).
+///
+/// A workspace where `threads.jsonl` contains only `Upsert` entries with no
+/// `MessageAppended` / `Stats` history is a "pre-Stats" workspace — common for
+/// data written before the Stats log was introduced. When
+/// `list_threads_unlocked` encounters such threads it calls
+/// `measure_messages_unlocked` per thread and appends a `Stats` entry to
+/// `threads.jsonl`, all while holding `CONVERSATION_STORE_LOCK`.
+///
+/// `prime_index_if_cold` must NOT call `list_threads_unlocked`. It uses
+/// `thread_index_unlocked` (header-only, no per-thread I/O) to snapshot
+/// thread IDs under the lock, then reads per-thread JSONL content outside
+/// the lock. This test verifies that a cold search on such a workspace
+/// still finds the correct messages, and that the former blocking code path
+/// is no longer reachable from `prime_index_if_cold`.
+#[test]
+fn prime_index_cold_build_works_on_legacy_workspace_without_stats() {
+ let temp = TempDir::new().unwrap();
+ let store = ConversationStore::new(temp.path().to_path_buf());
+ let ts = "2023-06-01T00:00:00Z".to_string();
+
+ // Bootstrap a legacy workspace by writing directly to the JSONL files —
+ // bypassing ensure_thread / append_message so no MessageAppended or Stats
+ // entries end up in threads.jsonl. This is exactly the shape produced by
+ // versions of the code predating the Stats log.
+ let root = store.root_dir();
+ std::fs::create_dir_all(root.join(THREAD_MESSAGES_DIR)).unwrap();
+
+ // Write an Upsert-only threads.jsonl (no MessageAppended / Stats entries).
+ append_jsonl(
+ &root.join(THREADS_FILENAME),
+ &ThreadLogEntry::Upsert {
+ thread_id: "legacy-t1".to_string(),
+ title: "Legacy Thread".to_string(),
+ created_at: ts.clone(),
+ updated_at: ts.clone(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ },
+ )
+ .unwrap();
+
+ // Write messages directly to the per-thread JSONL file, bypassing
+ // append_message so message_count stays None in the index.
+ let msg_path = store.thread_messages_path("legacy-t1");
+ for i in 0..3_usize {
+ append_jsonl(
+ &msg_path,
+ &ConversationMessage {
+ id: format!("lm{i}"),
+ content: format!("legacy kitten message {i}"),
+ message_type: "text".to_string(),
+ extra_metadata: serde_json::json!({}),
+ sender: "user".to_string(),
+ created_at: ts.clone(),
+ },
+ )
+ .unwrap();
+ }
+
+ // Cold build on a pre-Stats workspace must index all messages without
+ // triggering measure_messages_unlocked under CONVERSATION_STORE_LOCK.
+ let hits = store
+ .search_cross_thread_messages("kitten", 10, None)
+ .expect("search on legacy workspace");
+ assert_eq!(
+ hits.len(),
+ 3,
+ "all three legacy messages must be found via cold build"
+ );
+ assert!(
+ hits.iter().any(|h| h.message_id == "lm0"),
+ "lm0 must be in results"
+ );
+}
+
+/// Extends the concurrent-append test to the legacy (no-Stats) workspace shape.
+///
+/// Before the fix, `prime_index_if_cold` called `list_threads_unlocked` under
+/// the outer lock; for pre-Stats workspaces this triggered a slow
+/// `measure_messages_unlocked` + `Stats` append per thread — stalling any
+/// concurrent `append_message`. After the fix, `thread_index_unlocked` is
+/// used instead (header-only) so the append proceeds concurrently.
+#[test]
+fn legacy_workspace_cold_rebuild_does_not_block_concurrent_append() {
+ use std::sync::{mpsc, Arc, Barrier};
+ use std::thread;
+ use std::time::Duration;
+
+ let temp = TempDir::new().unwrap();
+ let store = ConversationStore::new(temp.path().to_path_buf());
+ let ts = "2023-06-01T00:00:00Z".to_string();
+
+ // Build a pre-Stats workspace with many threads to make the rebuild
+ // measurable (each thread has a per-thread JSONL file but no Stats entry).
+ let root = store.root_dir();
+ std::fs::create_dir_all(root.join(THREAD_MESSAGES_DIR)).unwrap();
+
+ for t in 0..20_usize {
+ let tid = format!("legacy-t{t}");
+ append_jsonl(
+ &root.join(THREADS_FILENAME),
+ &ThreadLogEntry::Upsert {
+ thread_id: tid.clone(),
+ title: format!("Legacy {t}"),
+ created_at: ts.clone(),
+ updated_at: ts.clone(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ },
+ )
+ .unwrap();
+ let msg_path = store.thread_messages_path(&tid);
+ for m in 0..50_usize {
+ append_jsonl(
+ &msg_path,
+ &ConversationMessage {
+ id: format!("lm-{t}-{m}"),
+ content: format!("legacy content thread {t} message {m}"),
+ message_type: "text".to_string(),
+ extra_metadata: serde_json::json!({}),
+ sender: "user".to_string(),
+ created_at: ts.clone(),
+ },
+ )
+ .unwrap();
+ }
+ }
+
+ // Also need a thread that append_message can target — create it properly
+ // so it exists in threads.jsonl (still Upsert-only, no Stats).
+ append_jsonl(
+ &root.join(THREADS_FILENAME),
+ &ThreadLogEntry::Upsert {
+ thread_id: "append-target".to_string(),
+ title: "Append Target".to_string(),
+ created_at: ts.clone(),
+ updated_at: ts.clone(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ },
+ )
+ .unwrap();
+
+ let store_search = store.clone();
+ let store_append = store.clone();
+
+ let barrier = Arc::new(Barrier::new(2));
+ let b_search = Arc::clone(&barrier);
+ let b_append = Arc::clone(&barrier);
+
+ let search_handle = thread::spawn(move || {
+ b_search.wait();
+ store_search.search_cross_thread_messages("legacy content", 5, None)
+ });
+
+ let (tx, rx) = mpsc::channel();
+ thread::spawn(move || {
+ b_append.wait();
+ let result = store_append.append_message(
+ "append-target",
+ ConversationMessage {
+ id: "concurrent-legacy-append".to_string(),
+ content: "written during legacy cold rebuild".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: serde_json::json!({}),
+ sender: "user".to_string(),
+ created_at: ts,
+ },
+ );
+ let _ = tx.send(result);
+ });
+
+ let append_result = rx
+ .recv_timeout(Duration::from_secs(30))
+ .expect("append_message blocked — legacy workspace cold rebuild held STORE_LOCK too long");
+ assert!(
+ append_result.is_ok(),
+ "append failed: {:?}",
+ append_result.err()
+ );
+
+ let search_result = search_handle.join().expect("search thread panicked");
+ assert!(
+ search_result.is_ok(),
+ "search failed: {:?}",
+ search_result.err()
+ );
+}
diff --git a/src/openhuman/memory/conversations/store/store_tests_more.rs b/src/openhuman/memory/conversations/store/store_tests_more.rs
new file mode 100644
index 0000000000..dd19b0796c
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/store_tests_more.rs
@@ -0,0 +1,429 @@
+use super::*;
+
+#[test]
+fn conversation_store_new() {
+ let tmp = TempDir::new().unwrap();
+ let store = ConversationStore::new(tmp.path().to_path_buf());
+ let threads = store.list_threads().unwrap();
+ assert!(threads.is_empty());
+}
+
+#[test]
+fn conversation_purge_stats_default() {
+ let stats = ConversationPurgeStats::default();
+ assert_eq!(stats.thread_count, 0);
+ assert_eq!(stats.message_count, 0);
+}
+
+#[test]
+fn list_threads_reconciles_stats_with_authoritative_message_files() {
+ let (temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t1".to_string(),
+ title: "T1".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ for i in 0..3 {
+ store
+ .append_message(
+ "t1",
+ ConversationMessage {
+ id: format!("m{i}"),
+ content: format!("hi {i}"),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: format!("2026-04-10T12:0{}:00Z", i + 1),
+ },
+ )
+ .unwrap();
+ }
+ // Warm-up: list_threads folds the MessageAppended entries.
+ let _ = store.list_threads().unwrap();
+
+ // Removing the transcript after a stats snapshot does not force routine
+ // list calls to rescan every message file. Cached navigation metadata
+ // remains available; explicit recovery can rebuild it when needed.
+ let messages_dir = temp
+ .path()
+ .join("memory")
+ .join("conversations")
+ .join("threads");
+ let entries: Vec<_> = std::fs::read_dir(&messages_dir)
+ .unwrap()
+ .filter_map(Result::ok)
+ .collect();
+ for entry in entries {
+ std::fs::remove_file(entry.path()).unwrap();
+ }
+
+ let threads = store.list_threads().unwrap();
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].message_count, 3);
+ assert_eq!(threads[0].last_message_at, "2026-04-10T12:03:00Z");
+}
+
+#[test]
+fn backfill_writes_stats_snapshot_for_legacy_threads() {
+ // Simulate legacy data: write only an Upsert entry (no MessageAppended)
+ // plus a per-thread messages file. The first list_threads must backfill.
+ let (temp, store) = make_store();
+ let conversations_dir = temp.path().join("memory").join("conversations");
+ std::fs::create_dir_all(conversations_dir.join("threads")).unwrap();
+
+ let threads_log = conversations_dir.join("threads.jsonl");
+ let upsert = serde_json::json!({
+ "op": "upsert",
+ "thread_id": "legacy-1",
+ "title": "Legacy",
+ "created_at": "2026-04-10T08:00:00Z",
+ "updated_at": "2026-04-10T08:00:00Z",
+ });
+ std::fs::write(&threads_log, format!("{}\n", upsert)).unwrap();
+
+ // Write 2 messages directly to the per-thread file (no MessageAppended
+ // entries — this is what pre-upgrade data looks like).
+ let messages_file = conversations_dir
+ .join("threads")
+ .join(format!("{}.jsonl", hex_encode("legacy-1".as_bytes())));
+ let m1 = serde_json::json!({
+ "id": "m1", "content": "a", "type": "text",
+ "extraMetadata": {}, "sender": "user",
+ "createdAt": "2026-04-10T09:00:00Z",
+ });
+ let m2 = serde_json::json!({
+ "id": "m2", "content": "b", "type": "text",
+ "extraMetadata": {}, "sender": "user",
+ "createdAt": "2026-04-10T09:05:00Z",
+ });
+ std::fs::write(&messages_file, format!("{m1}\n{m2}\n")).unwrap();
+
+ let threads = store.list_threads().unwrap();
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].message_count, 2);
+ assert_eq!(threads[0].last_message_at, "2026-04-10T09:05:00Z");
+
+ // The backfill should have appended a Stats entry — check the log
+ // contents now contain "op":"stats" for legacy-1.
+ let log = std::fs::read_to_string(&threads_log).unwrap();
+ assert!(
+ log.contains("\"op\":\"stats\"") && log.contains("legacy-1"),
+ "expected backfilled Stats entry in threads.jsonl, got:\n{log}",
+ );
+
+ // Once a Stats snapshot exists, routine reads remain header-only even if
+ // the transcript later becomes unavailable.
+ std::fs::remove_file(&messages_file).unwrap();
+ let threads2 = store.list_threads().unwrap();
+ assert_eq!(threads2[0].message_count, 2);
+ assert_eq!(threads2[0].last_message_at, "2026-04-10T09:05:00Z");
+}
+
+#[test]
+fn list_threads_repairs_message_append_without_matching_stat_event() {
+ let (temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "crash-window".to_string(),
+ title: "Crash window".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "crash-window",
+ ConversationMessage {
+ id: "m1".into(),
+ content: "first".into(),
+ message_type: "text".into(),
+ extra_metadata: json!({}),
+ sender: "user".into(),
+ created_at: "2026-04-10T12:01:00Z".into(),
+ },
+ )
+ .unwrap();
+
+ let path = temp
+ .path()
+ .join("memory/conversations/threads")
+ .join(format!("{}.jsonl", hex_encode("crash-window".as_bytes())));
+ let second = ConversationMessage {
+ id: "m2".into(),
+ content: "persisted before crash".into(),
+ message_type: "text".into(),
+ extra_metadata: json!({}),
+ sender: "assistant".into(),
+ created_at: "2026-04-10T12:02:00Z".into(),
+ };
+ use std::io::Write;
+ writeln!(
+ std::fs::OpenOptions::new().append(true).open(path).unwrap(),
+ "{}",
+ serde_json::to_string(&second).unwrap()
+ )
+ .unwrap();
+
+ let thread = store.list_threads().unwrap().remove(0);
+ assert_eq!(thread.message_count, 2);
+ assert_eq!(thread.last_message_at, "2026-04-10T12:02:00Z");
+}
+
+#[test]
+fn legacy_log_without_stats_still_parses() {
+ // Old on-disk format (only Upsert + Delete variants) must still load
+ // without errors after the enum gained MessageAppended + Stats.
+ let (temp, store) = make_store();
+ let conversations_dir = temp.path().join("memory").join("conversations");
+ std::fs::create_dir_all(conversations_dir.join("threads")).unwrap();
+ let threads_log = conversations_dir.join("threads.jsonl");
+ let upsert = serde_json::json!({
+ "op": "upsert",
+ "thread_id": "old",
+ "title": "Old",
+ "created_at": "2026-04-10T08:00:00Z",
+ "updated_at": "2026-04-10T08:00:00Z",
+ });
+ std::fs::write(&threads_log, format!("{}\n", upsert)).unwrap();
+
+ let threads = store.list_threads().unwrap();
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].id, "old");
+ assert_eq!(threads[0].message_count, 0);
+ // No messages → last_message_at falls back to created_at.
+ assert_eq!(threads[0].last_message_at, "2026-04-10T08:00:00Z");
+}
+
+#[test]
+fn delete_thread_clears_stats_from_index() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "doomed".to_string(),
+ title: "Doomed".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "doomed",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "x".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+ assert_eq!(store.list_threads().unwrap().len(), 1);
+
+ store
+ .delete_thread("doomed", "2026-04-10T12:02:00Z")
+ .unwrap();
+ assert!(store.list_threads().unwrap().is_empty());
+}
+
+#[test]
+fn search_cross_thread_messages_finds_hits_outside_excluded_thread() {
+ let (_temp, store) = make_store();
+
+ // Chat A — durable fact lives here.
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "thread-a".to_string(),
+ title: "Chat A".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "thread-a",
+ ConversationMessage {
+ id: "m-a-1".to_string(),
+ content: "Remember: my project is called Phoenix and uses Go and PostgreSQL."
+ .to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+
+ // Chat B — active chat, asking dependent question. Should be excluded
+ // so its own text doesn't echo back into [Cross-chat context].
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "thread-b".to_string(),
+ title: "Chat B".to_string(),
+ created_at: "2026-04-10T13:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "thread-b",
+ ConversationMessage {
+ id: "m-b-1".to_string(),
+ content: "What database does my project use?".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T13:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+
+ let hits = store
+ .search_cross_thread_messages("What database does my project use", 10, Some("thread-b"))
+ .expect("cross-thread search");
+
+ assert_eq!(hits.len(), 1, "exactly one cross-thread hit");
+ let hit = &hits[0];
+ assert_eq!(hit.thread_id, "thread-a");
+ assert!(hit.content.contains("PostgreSQL"));
+ assert!(hit.score > 0.0);
+}
+
+#[test]
+fn search_cross_thread_messages_excludes_active_thread() {
+ let (_temp, store) = make_store();
+
+ // Single thread — the only matching message lives in the thread we're
+ // about to exclude. Expect zero hits (don't echo same-chat history).
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "thread-only".to_string(),
+ title: "Only".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "thread-only",
+ ConversationMessage {
+ id: "m-1".to_string(),
+ content: "PostgreSQL deployment running on staging".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+
+ let hits = store
+ .search_cross_thread_messages("PostgreSQL deployment staging", 10, Some("thread-only"))
+ .expect("cross-thread search");
+ assert!(
+ hits.is_empty(),
+ "active thread must not echo into cross-chat"
+ );
+
+ // Sanity: without exclude, the hit is returned.
+ let hits_no_exclude = store
+ .search_cross_thread_messages("PostgreSQL deployment staging", 10, None)
+ .expect("cross-thread search");
+ assert_eq!(hits_no_exclude.len(), 1);
+}
+
+#[test]
+fn search_cross_thread_messages_skips_short_terms_and_empty_queries() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t".to_string(),
+ title: "T".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "t",
+ ConversationMessage {
+ id: "m".to_string(),
+ content: "Postgres".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+
+ // All terms < 3 chars → empty
+ assert!(store
+ .search_cross_thread_messages("a is on", 10, None)
+ .unwrap()
+ .is_empty());
+ // Empty query → empty
+ assert!(store
+ .search_cross_thread_messages("", 10, None)
+ .unwrap()
+ .is_empty());
+}
+
+#[test]
+fn search_cross_thread_messages_finds_polish_substring_without_diacritics() {
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "thread-pl".to_string(),
+ title: "PL".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .unwrap();
+ store
+ .append_message(
+ "thread-pl",
+ ConversationMessage {
+ id: "m1".to_string(),
+ content: "Lecę w piątek do Łodzi a potem Krakowa".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .unwrap();
+
+ // Query without diacritics should still find content with them.
+ let hits = store
+ .search_cross_thread_messages("Lodzi", 10, None)
+ .expect("cross-thread search");
+ assert_eq!(hits.len(), 1, "ł-fold should match Łodzi via lodzi");
+
+ let hits = store
+ .search_cross_thread_messages("krakow", 10, None)
+ .expect("cross-thread search");
+ assert_eq!(hits.len(), 1, "diacritic strip should match Krakowa");
+}
+
+#[path = "store_tests_late.rs"]
+mod late;
diff --git a/src/openhuman/memory/conversations/store/tokenize.rs b/src/openhuman/memory/conversations/store/tokenize.rs
new file mode 100644
index 0000000000..b9282a34a1
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/tokenize.rs
@@ -0,0 +1,261 @@
+//! Multilingual normalization + character n-gram generation for the
+//! cross-thread search inverted index.
+//!
+//! ## Why character n-grams (not word tokens)?
+//!
+//! The cross-thread search must find substrings *inside* words — querying
+//! `cat` should return messages containing `concatenate` or `Kotlin`. A
+//! whitespace/word-boundary tokenizer fundamentally cannot do that, and
+//! it also breaks down for CJK scripts that have no whitespace at all.
+//! Character n-grams sidestep both problems.
+//!
+//! ## Why a hybrid trigram + CJK-bigram scheme?
+//!
+//! Trigrams strike a good balance between recall and dictionary size for
+//! alphabetic scripts (~26³ ≈ 17k Latin trigrams). For CJK scripts the
+//! alphabet is tens of thousands of characters, so character trigrams
+//! explode the dictionary while character bigrams stay tractable. We
+//! therefore generate:
+//!
+//! - **bigrams** for contiguous runs of CJK characters (Han / Hiragana /
+//! Katakana / Hangul),
+//! - **trigrams** for everything else.
+//!
+//! Tokens from both schemes coexist in the same posting map. As long as
+//! query-time tokenization runs the *same* code path, lookups stay
+//! consistent.
+//!
+//! ## Normalization pipeline
+//!
+//! OpenHuman implemented `normalize()` on top of the `unicode-normalization`
+//! crate (NFKD → strip combining marks → lowercase → NFKC). That crate is not
+//! a dependency of this crate, so this port reproduces the *observable*
+//! behaviour with std-only primitives plus small per-character tables:
+//!
+//! 1. **Lowercase** — Unicode-aware case folding (`char::to_lowercase`) for
+//! cross-alphabet case insensitivity.
+//! 2. **Strip combining marks** — drops standalone combining diacritics across
+//! Latin, Arabic (harakat), and Hebrew (niqqud) ranges so a query without
+//! marks matches content with them.
+//! 3. **Strip precomposed Latin diacritics** — a per-letter table maps
+//! precomposed accented Latin letters (Latin-1 Supplement + Latin
+//! Extended-A) back to their base letter (Polish ó→o, ż→z; Spanish ñ→n).
+//! 4. **Non-decomposing fold** — small per-letter table for decorated letters
+//! that have no canonical base (Polish ł, German ß, Norwegian ø, Icelandic
+//! þ/ð, Latin æ/œ, Turkish ı, Croatian đ, Maltese ħ, Sami ŋ).
+//! 5. **Half-width → full-width katakana** — unifies the half-width and
+//! full-width kana forms so byte equality lines up at lookup time.
+//!
+//! The result is idempotent: re-running `normalize` on its own output is a
+//! no-op (no precomposed letters, combining marks, or half-width forms remain).
+
+/// Normalize a piece of text for indexing or querying. Idempotent: running
+/// the output through `normalize` again yields the same string.
+pub fn normalize(text: &str) -> String {
+ // Lowercase first so the per-letter tables below only need lowercase
+ // entries. `char::to_lowercase` may expand a single char into several.
+ let lowered: String = text.chars().flat_map(char::to_lowercase).collect();
+ let mut out = String::with_capacity(lowered.len());
+ for c in lowered.chars() {
+ if is_combining_mark(c) {
+ // Drop diacritics that sit on their own code point (Arabic
+ // harakat, Hebrew niqqud, Latin combining marks, …).
+ continue;
+ }
+ if let Some(folded) = fold_non_decomposing(c) {
+ out.push_str(folded);
+ } else if let Some(base) = strip_latin_diacritic(c) {
+ out.push(base);
+ } else if let Some(full) = halfwidth_to_fullwidth(c) {
+ out.push(full);
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
+/// Per-letter folds for "decorated" letters that have no canonical
+/// decomposition (so stripping combining marks alone leaves them unchanged).
+/// Polish ł/Ł is the motivating case — a Polish user typing `lacka`
+/// reasonably expects to find `łącka`. Lowercase-only entries (run after
+/// `to_lowercase`). Returns `&str` because some fold to multiple letters
+/// (ß→ss, æ→ae).
+fn fold_non_decomposing(c: char) -> Option<&'static str> {
+ Some(match c {
+ 'ł' => "l",
+ 'ø' => "o",
+ 'ß' => "ss",
+ 'æ' => "ae",
+ 'œ' => "oe",
+ 'þ' => "th",
+ 'ð' => "d",
+ 'đ' => "d",
+ 'ħ' => "h",
+ 'ı' => "i", // Turkish dotless i
+ 'ŋ' => "n",
+ _ => return None,
+ })
+}
+
+/// Map a precomposed accented Latin letter to its base letter. Lowercase-only
+/// (run after `to_lowercase`). Covers Latin-1 Supplement and Latin Extended-A.
+fn strip_latin_diacritic(c: char) -> Option<char> {
+ Some(match c {
+ // Latin-1 Supplement
+ 'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' => 'a',
+ 'ç' => 'c',
+ 'è' | 'é' | 'ê' | 'ë' => 'e',
+ 'ì' | 'í' | 'î' | 'ï' => 'i',
+ 'ñ' => 'n',
+ 'ò' | 'ó' | 'ô' | 'õ' | 'ö' => 'o',
+ 'ù' | 'ú' | 'û' | 'ü' => 'u',
+ 'ý' | 'ÿ' => 'y',
+ // Latin Extended-A
+ 'ā' | 'ă' | 'ą' => 'a',
+ 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
+ 'ď' => 'd',
+ 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
+ 'ĝ' | 'ğ' | 'ġ' | 'ģ' => 'g',
+ 'ĥ' => 'h',
+ 'ĩ' | 'ī' | 'ĭ' | 'į' => 'i',
+ 'ĵ' => 'j',
+ 'ķ' => 'k',
+ 'ĺ' | 'ļ' | 'ľ' | 'ŀ' => 'l',
+ 'ń' | 'ņ' | 'ň' => 'n',
+ 'ō' | 'ŏ' | 'ő' => 'o',
+ 'ŕ' | 'ŗ' | 'ř' => 'r',
+ 'ś' | 'ŝ' | 'ş' | 'š' => 's',
+ 'ţ' | 'ť' | 'ŧ' => 't',
+ 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
+ 'ŵ' => 'w',
+ 'ŷ' => 'y',
+ 'ź' | 'ż' | 'ž' => 'z',
+ _ => return None,
+ })
+}
+
+/// Returns true for standalone combining marks that should be dropped during
+/// normalization (diacritics that sit on their own code point). Covers the
+/// Latin combining block, Arabic harakat, and Hebrew niqqud.
+fn is_combining_mark(c: char) -> bool {
+ matches!(
+ c as u32,
+ 0x0300..=0x036F // Combining Diacritical Marks (Latin etc.)
+ | 0x0483..=0x0489 // Combining Cyrillic
+ | 0x0591..=0x05BD // Hebrew points
+ | 0x05BF
+ | 0x05C1 | 0x05C2
+ | 0x05C4 | 0x05C5
+ | 0x05C7
+ | 0x0610..=0x061A // Arabic signs
+ | 0x064B..=0x065F // Arabic harakat / tashkil
+ | 0x0670 // Arabic superscript alef
+ | 0x06D6..=0x06DC // Arabic small high marks
+ | 0x06DF..=0x06E4
+ | 0x06E7 | 0x06E8
+ | 0x06EA..=0x06ED
+ | 0xFE20..=0xFE2F // Combining Half Marks
+ )
+}
+
+/// Map a half-width katakana code point to its full-width equivalent so the
+/// two encodings hash identically. Returns `None` for anything outside the
+/// half-width katakana letter block.
+fn halfwidth_to_fullwidth(c: char) -> Option<char> {
+ // Full-width katakana targets for U+FF66..=U+FF9D, in order.
+ const HW_KATAKANA: [u32; 56] = [
+ 0x30F2, 0x30A1, 0x30A3, 0x30A5, 0x30A7, 0x30A9, 0x30E3, 0x30E5, 0x30E7, 0x30C3, 0x30FC,
+ 0x30A2, 0x30A4, 0x30A6, 0x30A8, 0x30AA, 0x30AB, 0x30AD, 0x30AF, 0x30B1, 0x30B3, 0x30B5,
+ 0x30B7, 0x30B9, 0x30BB, 0x30BD, 0x30BF, 0x30C1, 0x30C4, 0x30C6, 0x30C8, 0x30CA, 0x30CB,
+ 0x30CC, 0x30CD, 0x30CE, 0x30CF, 0x30D2, 0x30D5, 0x30D8, 0x30DB, 0x30DE, 0x30DF, 0x30E0,
+ 0x30E1, 0x30E2, 0x30E4, 0x30E6, 0x30E8, 0x30E9, 0x30EA, 0x30EB, 0x30EC, 0x30ED, 0x30EF,
+ 0x30F3,
+ ];
+ let u = c as u32;
+ if (0xFF66..=0xFF9D).contains(&u) {
+ return char::from_u32(HW_KATAKANA[(u - 0xFF66) as usize]);
+ }
+ None
+}
+
+/// Returns true for code points that should be tokenized as CJK bigrams.
+///
+/// Covers Han ideographs (CJK Unified + Ext A + Compatibility), Japanese
+/// kana (Hiragana, Katakana), and Hangul (Jamo + precomposed syllables).
+/// CJK punctuation and symbols (U+3000..=U+303F) are intentionally
+/// excluded — they should be treated as token delimiters, not content.
+pub fn is_cjk(c: char) -> bool {
+ matches!(
+ c as u32,
+ 0x3040..=0x309F // Hiragana
+ | 0x30A0..=0x30FF // Katakana
+ | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A
+ | 0x4E00..=0x9FFF // CJK Unified Ideographs
+ | 0xF900..=0xFAFF // CJK Compatibility Ideographs
+ | 0x1100..=0x11FF // Hangul Jamo
+ | 0xAC00..=0xD7AF // Hangul Syllables
+ )
+}
+
+/// Tokenize already-normalized text into character n-grams as borrowed
+/// slices into `normalized`.
+///
+/// Returning `&str` (instead of owned `String`s) keeps the hot search
+/// path allocation-free: query-time ngram extraction only needs to look
+/// up posting-list keys, never to insert. On the insert side, the index
+/// allocates a fresh key only when an ngram is brand-new to the corpus —
+/// see `InvertedIndex::insert`.
+///
+/// - CJK runs (≥2 chars) → bigrams.
+/// - Non-CJK runs (≥3 chars) → trigrams.
+/// - Runs shorter than the relevant n are dropped (they cannot be
+/// substring-matched against any document containing them anyway, so
+/// the Phase 2 verification will catch them via the linear fallback in
+/// `InvertedIndex::search`).
+///
+/// Word boundaries inside a run do NOT split the n-gram window — we
+/// deliberately want substring matches that span punctuation.
+pub fn ngrams(normalized: &str) -> Vec<&str> {
+ let mut out = Vec::new();
+ // Capture (byte_offset, is_cjk) per char. Byte offsets let us slice
+ // `normalized` directly to return `&str` views; the cjk flag drives
+ // the script-class run partitioning below.
+ let chars: Vec<(usize, bool)> = normalized
+ .char_indices()
+ .map(|(b, c)| (b, is_cjk(c)))
+ .collect();
+ if chars.is_empty() {
+ return out;
+ }
+ let end_byte = normalized.len();
+
+ // Walk contiguous runs of "same script class" (CJK vs non-CJK) and
+ // emit the appropriate n-gram size for each run.
+ let mut i = 0;
+ while i < chars.len() {
+ let cjk = chars[i].1;
+ let mut j = i + 1;
+ while j < chars.len() && chars[j].1 == cjk {
+ j += 1;
+ }
+ let n = if cjk { 2 } else { 3 };
+ if j - i >= n {
+ for k in i..=j - n {
+ let start = chars[k].0;
+ let end = if k + n < chars.len() {
+ chars[k + n].0
+ } else {
+ end_byte
+ };
+ out.push(&normalized[start..end]);
+ }
+ }
+ i = j;
+ }
+ out
+}
+
+#[cfg(test)]
+#[path = "tokenize_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/conversations/store/tokenize_tests.rs b/src/openhuman/memory/conversations/store/tokenize_tests.rs
new file mode 100644
index 0000000000..67e617600a
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/tokenize_tests.rs
@@ -0,0 +1,108 @@
+//! Normalization + n-gram tokenization tests.
+
+use super::*;
+
+#[test]
+fn normalize_lowercases_ascii() {
+ assert_eq!(normalize("Hello World"), "hello world");
+}
+
+#[test]
+fn normalize_strips_polish_diacritics() {
+ // Polish: Kraków, żółć, łąka, plus a Spanish parity case.
+ // ł/Ł are *not* canonically decomposable (no combining ogonek
+ // form) so we fold them manually via `fold_non_decomposing`.
+ assert_eq!(normalize("Kraków"), "krakow");
+ assert_eq!(normalize("żółć"), "zolc");
+ assert_eq!(normalize("łąka"), "laka");
+ assert_eq!(normalize("Mañana"), "manana");
+}
+
+#[test]
+fn normalize_folds_non_decomposing_letters() {
+ // Letters that have no canonical base but a user typing without
+ // the diacritic would still expect to find.
+ assert_eq!(normalize("Łódź"), "lodz");
+ assert_eq!(normalize("Straße"), "strasse");
+ assert_eq!(normalize("Bjørn"), "bjorn");
+ assert_eq!(normalize("Þórr"), "thorr");
+}
+
+#[test]
+fn normalize_strips_arabic_harakat() {
+ // Arabic: word "kataba" (he wrote) with harakat marks vs without
+ let with_marks = "كَتَبَ";
+ let without_marks = "كتب";
+ assert_eq!(normalize(with_marks), normalize(without_marks));
+}
+
+#[test]
+fn normalize_unifies_cjk_halfwidth_fullwidth() {
+ // Half-width katakana maps to full-width.
+ let halfwidth = "カタカナ"; // half-width
+ let fullwidth = "カタカナ"; // full-width
+ assert_eq!(normalize(halfwidth), normalize(fullwidth));
+}
+
+#[test]
+fn normalize_is_idempotent() {
+ let s = "Café — 東京 — żółć";
+ let once = normalize(s);
+ let twice = normalize(&once);
+ assert_eq!(once, twice);
+}
+
+#[test]
+fn ngrams_emits_trigrams_for_latin() {
+ let g = ngrams("kitten");
+ assert_eq!(g, vec!["kit", "itt", "tte", "ten"]);
+}
+
+#[test]
+fn ngrams_emits_bigrams_for_cjk() {
+ // 日本語 → 日本, 本語
+ let g = ngrams("日本語");
+ assert_eq!(g, vec!["日本", "本語"]);
+}
+
+#[test]
+fn ngrams_mixed_script_splits_at_boundary() {
+ // "東京tokyo" → CJK run [東京] gives bigram "東京",
+ // Latin run [tokyo] gives trigrams tok, oky, kyo.
+ let g = ngrams("東京tokyo");
+ assert_eq!(g, vec!["東京", "tok", "oky", "kyo"]);
+}
+
+#[test]
+fn ngrams_drops_runs_too_short() {
+ // "ab東" → Latin run [ab] is only 2 chars → dropped; CJK run [東]
+ // is only 1 char → dropped. Empty result.
+ let g = ngrams("ab東");
+ assert!(g.is_empty(), "got {:?}", g);
+}
+
+#[test]
+fn ngrams_substring_inside_word_is_indexable() {
+ // After normalize, "Concatenate" → "concatenate" → trigrams include
+ // "cat". This is the canonical substring-inside-word scenario that
+ // motivates the character-n-gram scheme over word tokenization.
+ let normalized = normalize("Concatenate");
+ let g = ngrams(&normalized);
+ assert!(g.contains(&"cat"), "trigrams: {:?}", g);
+}
+
+#[test]
+fn ngrams_empty_input_returns_empty() {
+ assert!(ngrams("").is_empty());
+}
+
+#[test]
+fn is_cjk_classifies_common_scripts() {
+ assert!(is_cjk('東'));
+ assert!(is_cjk('あ')); // hiragana
+ assert!(is_cjk('カ')); // katakana
+ assert!(is_cjk('한')); // hangul syllable
+ assert!(!is_cjk('a'));
+ assert!(!is_cjk('ą'));
+ assert!(!is_cjk(',')); // CJK punctuation — intentionally NOT cjk
+}
diff --git a/src/openhuman/memory/conversations/store/types.rs b/src/openhuman/memory/conversations/store/types.rs
new file mode 100644
index 0000000000..e81ec16e68
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/types.rs
@@ -0,0 +1,120 @@
+//! Wire/storage types for the workspace-backed conversation store: threads,
+//! messages, create requests, and partial-update patches.
+//!
+//! These mirror one-to-one the JSONL records persisted under
+//! `<workspace>/memory/conversations/`. The `camelCase` serde renames and the
+//! `type`/`extraMetadata` wire keys are part of the OpenHuman on-disk contract
+//! and must be preserved byte-for-byte so existing transcripts keep loading.
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// A persisted conversation thread, mirroring one entry in `threads.jsonl`.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConversationThread {
+ /// Stable thread identifier; the JSONL key callers reference everywhere.
+ pub id: String,
+ /// Human-readable thread title.
+ pub title: String,
+ /// Optional host chat id (e.g. a messaging platform chat); omitted from the
+ /// wire record when `None`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub chat_id: Option<i64>,
+ /// Whether the thread is currently active (not archived/closed).
+ pub is_active: bool,
+ /// Cached count of messages in the thread's log.
+ pub message_count: usize,
+ /// ISO-8601 timestamp of the most recent message.
+ pub last_message_at: String,
+ /// ISO-8601 timestamp of thread creation.
+ pub created_at: String,
+ /// Parent thread id when this thread was branched from another; omitted from
+ /// the wire record when `None`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub parent_thread_id: Option<String>,
+ /// Free-form labels/tags; defaults to empty when absent on disk.
+ #[serde(default)]
+ pub labels: Vec<String>,
+ /// Optional personality id bound to the thread; omitted from the wire record
+ /// when `None`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub personality_id: Option<String>,
+}
+
+/// A single message appended to a thread's JSONL log.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConversationMessage {
+ /// Stable message identifier, unique within the thread's log.
+ pub id: String,
+ /// Message body text.
+ pub content: String,
+ /// Message kind; serialized under the wire key `type` (e.g. `"text"`).
+ #[serde(rename = "type")]
+ pub message_type: String,
+ /// Arbitrary per-message metadata; serialized under the wire key
+ /// `extraMetadata`. Defaults to JSON null when absent.
+ #[serde(default)]
+ pub extra_metadata: Value,
+ /// Sender identifier/role for the message.
+ pub sender: String,
+ /// ISO-8601 timestamp of when the message was created.
+ pub created_at: String,
+}
+
+/// Input payload to create-or-update a thread via
+/// [`ConversationStore::ensure_thread`](super::store::ConversationStore::ensure_thread).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateConversationThread {
+ /// Desired thread id; reused as-is if the thread already exists.
+ pub id: String,
+ /// Initial thread title.
+ pub title: String,
+ /// ISO-8601 creation timestamp to record.
+ pub created_at: String,
+ /// Optional parent thread id when branching from an existing thread.
+ #[serde(default)]
+ pub parent_thread_id: Option<String>,
+ /// Optional initial labels; `None` leaves the thread's labels unset.
+ #[serde(default)]
+ pub labels: Option<Vec<String>>,
+ /// Optional personality id to bind to the thread.
+ #[serde(default)]
+ pub personality_id: Option<String>,
+}
+
+/// Partial update to apply to a stored message (e.g. rewriting `extraMetadata`).
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct ConversationMessagePatch {
+ /// Replacement `extraMetadata` payload; `None` leaves existing metadata
+ /// untouched.
+ #[serde(default)]
+ pub extra_metadata: Option<Value>,
+}
+
+/// A single match returned by
+/// [`ConversationStore::search_cross_thread_messages`](super::store::ConversationStore::search_cross_thread_messages).
+/// Carries the source `thread_id` so the caller can render provenance into the
+/// `[Cross-chat context]` block (issue #1505).
+#[derive(Debug, Clone, PartialEq)]
+pub struct CrossThreadHit {
+ /// Source thread the match came from; drives provenance rendering.
+ pub thread_id: String,
+ /// Id of the matched message within that thread.
+ pub message_id: String,
+ /// Sender role of the matched message.
+ pub role: String,
+ /// Matched message content.
+ pub content: String,
+ /// ISO-8601 timestamp of the matched message.
+ pub created_at: String,
+ /// Relevance score for the match; higher is more relevant.
+ pub score: f64,
+}
+
+#[cfg(test)]
+#[path = "types_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/conversations/store/types_tests.rs b/src/openhuman/memory/conversations/store/types_tests.rs
new file mode 100644
index 0000000000..50fee0305a
--- /dev/null
+++ b/src/openhuman/memory/conversations/store/types_tests.rs
@@ -0,0 +1,65 @@
+//! Serde-contract tests for the conversation wire types.
+
+use super::*;
+use serde_json::json;
+
+#[test]
+fn conversation_thread_serde_uses_camel_case_and_defaults_labels() {
+ let raw = json!({
+ "id": "thread-1",
+ "title": "Memory",
+ "chatId": 42,
+ "isActive": true,
+ "messageCount": 3,
+ "lastMessageAt": "2026-05-24T08:00:00Z",
+ "createdAt": "2026-05-24T07:00:00Z",
+ "parentThreadId": "parent-1"
+ });
+
+ let thread: ConversationThread = serde_json::from_value(raw).unwrap();
+ assert_eq!(thread.chat_id, Some(42));
+ assert_eq!(thread.parent_thread_id.as_deref(), Some("parent-1"));
+ assert!(thread.labels.is_empty(), "labels should default to []");
+
+ let encoded = serde_json::to_value(&thread).unwrap();
+ assert_eq!(encoded["chatId"], json!(42));
+ assert_eq!(encoded["parentThreadId"], json!("parent-1"));
+ assert!(encoded.get("chat_id").is_none());
+ assert!(encoded.get("parent_thread_id").is_none());
+}
+
+#[test]
+fn conversation_message_patch_defaults_to_no_changes() {
+ let patch: ConversationMessagePatch = serde_json::from_value(json!({})).unwrap();
+ assert!(patch.extra_metadata.is_none());
+
+ let patch_with_metadata: ConversationMessagePatch =
+ serde_json::from_value(json!({"extraMetadata": {"source": "mock"}})).unwrap();
+ assert_eq!(
+ patch_with_metadata.extra_metadata,
+ Some(json!({"source": "mock"}))
+ );
+}
+
+#[test]
+fn create_thread_optional_fields_roundtrip() {
+ let create = CreateConversationThread {
+ id: "thread-2".into(),
+ title: "Thread".into(),
+ created_at: "2026-05-24T08:00:00Z".into(),
+ parent_thread_id: None,
+ labels: Some(vec!["important".into(), "memory".into()]),
+ personality_id: None,
+ };
+
+ let encoded = serde_json::to_value(&create).unwrap();
+ assert_eq!(encoded["labels"], json!(["important", "memory"]));
+ assert_eq!(encoded["parentThreadId"], Value::Null);
+
+ let decoded: CreateConversationThread = serde_json::from_value(encoded).unwrap();
+ assert_eq!(
+ decoded.labels,
+ Some(vec!["important".to_string(), "memory".to_string()])
+ );
+ assert!(decoded.parent_thread_id.is_none());
+}
diff --git a/src/openhuman/memory/goals/doc.rs b/src/openhuman/memory/goals/doc.rs
new file mode 100644
index 0000000000..1682b41176
--- /dev/null
+++ b/src/openhuman/memory/goals/doc.rs
@@ -0,0 +1,169 @@
+//! The validating mutation surface for [`GoalsDoc`] — add, edit, delete.
+//!
+//! # Why this is the host's and not the driver's (#5560)
+//!
+//! [`MemoryGoals`](crate::openhuman::memory::api::provider::MemoryGoals) has
+//! exactly two members: read the whole document and replace the whole document.
+//! That is deliberate, and its own contract docs say why —
+//!
+//! > Whole-document replacement rather than per-item add/edit/delete because
+//! > the validating mutation surface (PII and secret predicates) is **host**
+//! > policy: the host parses, validates, mutates, and hands back the result.
+//! > Exposing per-item mutation here would put that policy behind a trait a
+//! > third-party driver implements, where it could be skipped.
+//!
+//! So the trio below came home from `tinycortex::memory::goals::store`'s
+//! `GoalsDocMutations` trait, and the predicates they call came with them —
+//! except that they did not have to travel, because
+//! [`safety`](crate::openhuman::memory::safety) is where they started.
+//! TinyCortex's `memory::store::safety` says so in its own first line ("Ported
+//! from OpenHuman's `memory_store::safety`"), and the four functions
+//! [`validate_goal_text`] needs — `has_likely_email`, `has_likely_pii`,
+//! `has_likely_secret`, `sanitize_text` — are the originals, in this crate,
+//! already. Nothing here is a second implementation of anything.
+//!
+//! ## Validation still runs twice, exactly as it did before
+//!
+//! The engine's `goals::store::save` re-validates every item before it writes,
+//! and that has not changed: it is reached through
+//! `MemoryGoals::set_goals`. So a document that gets past this module is
+//! checked again at the one choke point that touches the file, and a driver
+//! handed a bad document by any other route still refuses it. What this module
+//! restores is the *first* check — the one that used to live in
+//! `GoalsDocMutations` and produce the specific message a caller acts on
+//! ("goal text must be a single line") rather than `save`'s catch-all
+//! ("goal '<id>' text must be a non-empty, single-line, secret/PII-free
+//! string").
+//!
+//! ## The mutation lock came home too, and it has to
+//!
+//! Every mutation is a read-modify-write over a whole document: `goals()`,
+//! mutate here, `set_goals()`. The engine serialised that sequence behind a
+//! process-wide `parking_lot::Mutex` (`goals_mutation_lock`) precisely because
+//! two interleaved sequences lose one of the two writes outright — the second
+//! `set_goals` replaces the document the first one wrote. Splitting the
+//! sequence across two driver calls does not make that hazard smaller; it makes
+//! the window wider. [`mutation_lock`] is the same lock on this side of the
+//! boundary, and `ops` holds it across both calls.
+//!
+//! It is a `tokio::sync::Mutex` rather than a `parking_lot` one because the
+//! guarded region now contains two `await` points. A `std`/`parking_lot` guard
+//! held across an await is not `Send`, and blocking the executor thread for the
+//! duration of two bus round-trips is the alternative nobody wants.
+
+use tokio::sync::Mutex;
+
+use crate::openhuman::memory::api::error::MemoryError;
+use crate::openhuman::memory::api::goals::{GoalItem, GoalsDoc};
+use crate::openhuman::memory::safety::{
+ has_likely_email, has_likely_pii, has_likely_secret, sanitize_text,
+};
+
+/// Serialises `goals()` → mutate → `set_goals()` sequences across all host
+/// callers. See the module docs for why the sequence needs one.
+pub(super) fn mutation_lock() -> &'static Mutex<()> {
+ static LOCK: std::sync::OnceLock<Mutex<()>> = std::sync::OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+}
+
+/// Detect likely PII in goal text (email addresses, generic PII patterns, or
+/// content the sanitizer would otherwise redact).
+///
+/// The three-way test is the engine's `has_goal_pii`, unchanged: the boundary
+/// predicate [`has_likely_pii`] is deliberately *strict* (it ignores
+/// bare-numeric shapes to avoid rejecting scanner-built identifiers), so the
+/// `sanitize_text` arm is what catches the rest — a goal is free prose, not an
+/// identifier, and the strict set alone would let a phone number through.
+fn has_goal_pii(text: &str) -> bool {
+ has_likely_email(text) || has_likely_pii(text) || sanitize_text(text).report.pii_redactions > 0
+}
+
+/// Validate that `text` is a non-empty, single-line, secret- and PII-free goal
+/// body, returning the trimmed text.
+///
+/// A newline-bearing goal would inject extra `- [..]` list lines on reload,
+/// corrupting the stored shape — so it is rejected outright rather than
+/// escaped.
+///
+/// # Errors
+///
+/// [`MemoryError::Invalid`] with the same three messages the engine's
+/// `validate_goal_text` produced; they reach the agent as tool-result text and
+/// are what it acts on to retry.
+fn validate_goal_text(text: &str) -> Result<&str, MemoryError> {
+ let text = text.trim();
+ if text.is_empty() {
+ return Err(MemoryError::Invalid(
+ "goal text must not be empty".to_string(),
+ ));
+ }
+ if text.contains('\n') || text.contains('\r') {
+ return Err(MemoryError::Invalid(
+ "goal text must be a single line".to_string(),
+ ));
+ }
+ if has_likely_secret(text) || has_goal_pii(text) {
+ return Err(MemoryError::Invalid(
+ "goal text must not contain secrets or PII".to_string(),
+ ));
+ }
+ Ok(text)
+}
+
+/// Append a new goal to `doc`, returning the assigned id.
+///
+/// In-memory only — pair with `MemoryGoals::set_goals`. The id comes from
+/// [`GoalsDoc::next_id`], which is the contract's own allocator, so the
+/// `g<N>` sequence is unchanged.
+///
+/// # Errors
+///
+/// As [`validate_goal_text`].
+pub(super) fn add_item(doc: &mut GoalsDoc, text: &str) -> Result<String, MemoryError> {
+ let text = validate_goal_text(text)?;
+ let id = doc.next_id();
+ doc.items.push(GoalItem::new(&id, text));
+ Ok(id)
+}
+
+/// Replace the text of the goal with `id`.
+///
+/// # Errors
+///
+/// [`MemoryError::NotFound`] for an unknown id, otherwise as
+/// [`validate_goal_text`].
+pub(super) fn edit_item(doc: &mut GoalsDoc, id: &str, text: &str) -> Result<(), MemoryError> {
+ let text = validate_goal_text(text)?;
+ let item = doc
+ .items
+ .iter_mut()
+ .find(|i| i.id == id)
+ .ok_or_else(|| MemoryError::NotFound(format!("no goal with id '{id}'")))?;
+ item.text = text.to_string();
+ Ok(())
+}
+
+/// Delete the goal with `id`.
+///
+/// `position` + `remove` rather than `retain`, which would drop every item
+/// sharing `id`. A well-formed document never has duplicate ids, but
+/// [`GoalsDoc::parse`] accepts a hand-edited or corrupt file that does — this
+/// matches [`edit_item`]'s "first occurrence" semantics so such a document
+/// loses at most one goal per delete rather than all of them.
+///
+/// # Errors
+///
+/// [`MemoryError::NotFound`] for an unknown id.
+pub(super) fn delete_item(doc: &mut GoalsDoc, id: &str) -> Result<(), MemoryError> {
+ let index = doc
+ .items
+ .iter()
+ .position(|item| item.id == id)
+ .ok_or_else(|| MemoryError::NotFound(format!("no goal with id '{id}'")))?;
+ doc.items.remove(index);
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "doc_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/goals/doc_tests.rs b/src/openhuman/memory/goals/doc_tests.rs
new file mode 100644
index 0000000000..ec3975a475
--- /dev/null
+++ b/src/openhuman/memory/goals/doc_tests.rs
@@ -0,0 +1,121 @@
+//! Unit tests for the host-owned validating mutation surface.
+//!
+//! Ported from the engine's `memory/goals/mutations_tests.rs` — the same cases
+//! against the same predicates, rewritten from method syntax (`doc.add(..)`) to
+//! the free functions this module exposes. They are kept here rather than
+//! trusted to the engine's copy because the predicates the guards call are now
+//! reached from this crate, and a divergence would otherwise only surface as a
+//! goal with an email address in it.
+
+use super::*;
+
+#[test]
+fn parse_round_trips_render() {
+ let mut doc = GoalsDoc::default();
+ add_item(&mut doc, "ship the desktop app").unwrap();
+ add_item(&mut doc, "keep the rust core authoritative").unwrap();
+ let rendered = doc.render();
+ let reparsed = GoalsDoc::parse(&rendered);
+ assert_eq!(doc, reparsed);
+}
+
+#[test]
+fn add_assigns_unique_ids() {
+ let mut doc = GoalsDoc::default();
+ let a = add_item(&mut doc, "a").unwrap();
+ let b = add_item(&mut doc, "b").unwrap();
+ assert_ne!(a, b);
+ assert_eq!(doc.items.len(), 2);
+}
+
+#[test]
+fn add_rejects_empty_text() {
+ let mut doc = GoalsDoc::default();
+ let err = add_item(&mut doc, " ").unwrap_err();
+ assert!(
+ err.to_string().contains("goal text must not be empty"),
+ "the empty-text message reaches the agent verbatim: {err}"
+ );
+}
+
+#[test]
+fn add_and_edit_reject_multiline_text() {
+ let mut doc = GoalsDoc::default();
+ // A newline-bearing goal would inject extra "- [..]" list lines on reload,
+ // corrupting the stored shape — reject it outright.
+ assert!(add_item(&mut doc, "line one\n- [x] injected").is_err());
+ let id = add_item(&mut doc, "legit goal").unwrap();
+ assert!(edit_item(&mut doc, &id, "still\rinjected").is_err());
+}
+
+#[test]
+fn add_and_edit_reject_secret_or_pii_text() {
+ let mut doc = GoalsDoc::default();
+ assert!(add_item(&mut doc, "follow up with [email protected] about launch").is_err());
+ assert!(add_item(&mut doc, "rotate api_key=sk-abcdefghijklmnopqrstuvwxyz123456").is_err());
+
+ let id = add_item(&mut doc, "ship the memory engine").unwrap();
+ assert!(edit_item(&mut doc, &id, "call +14155551212 tomorrow").is_err());
+ assert_eq!(
+ doc.items[0].text, "ship the memory engine",
+ "a rejected edit must leave the item untouched"
+ );
+}
+
+#[test]
+fn edit_updates_known_id_and_rejects_unknown() {
+ let mut doc = GoalsDoc::default();
+ let id = add_item(&mut doc, "old").unwrap();
+ edit_item(&mut doc, &id, "new").unwrap();
+ assert_eq!(doc.items[0].text, "new");
+ assert!(edit_item(&mut doc, "nope", "x").is_err());
+}
+
+#[test]
+fn delete_removes_known_id_and_rejects_unknown() {
+ let mut doc = GoalsDoc::default();
+ let id = add_item(&mut doc, "x").unwrap();
+ delete_item(&mut doc, &id).unwrap();
+ assert!(doc.is_empty());
+ assert!(delete_item(&mut doc, "nope").is_err());
+}
+
+#[test]
+fn delete_removes_only_the_first_occurrence_of_a_duplicate_id() {
+ // A well-formed document never has duplicate ids, but `GoalsDoc::parse`
+ // accepts a hand-edited or corrupt file that does. `delete` must not
+ // bulk-remove every item sharing the id.
+ let mut doc = GoalsDoc {
+ items: vec![GoalItem::new("g1", "first"), GoalItem::new("g1", "second")],
+ };
+ delete_item(&mut doc, "g1").unwrap();
+ assert_eq!(doc.items.len(), 1);
+ assert_eq!(doc.items[0].text, "second");
+}
+
+#[test]
+fn next_id_avoids_collision_with_custom_ids() {
+ let mut doc = GoalsDoc {
+ items: vec![GoalItem::new("g1", "a"), GoalItem::new("g2", "b")],
+ };
+ let id = add_item(&mut doc, "c").unwrap();
+ assert_eq!(id, "g3");
+}
+
+/// The one property the whole module exists for: the guards the host now runs
+/// are the same guards the engine ran, so a text the engine's `save` would
+/// refuse never reaches it.
+#[test]
+fn host_guards_agree_with_the_engine_choke_point() {
+ for rejected in [
+ "email [email protected] the plan",
+ "store token ghp_abcdefghijklmnopqrstuvwxyz0123456789",
+ ] {
+ let mut doc = GoalsDoc::default();
+ assert!(
+ add_item(&mut doc, rejected).is_err(),
+ "host validation must reject {rejected:?} before `set_goals` sees it"
+ );
+ assert!(doc.is_empty(), "a rejected add must not mutate the document");
+ }
+}
diff --git a/src/openhuman/memory/goals/enrich.rs b/src/openhuman/memory/goals/enrich.rs
index 77956c8ab9..f0b4b01b39 100644
--- a/src/openhuman/memory/goals/enrich.rs
+++ b/src/openhuman/memory/goals/enrich.rs
@@ -19,7 +19,8 @@ use crate::openhuman::agent::harness::definition::AgentDefinitionRegistry;
use crate::openhuman::agent::turn_origin::{with_origin, AgentTurnOrigin, TrustedAutomationSource};
use crate::openhuman::agent::Agent;
use crate::openhuman::config::Config;
-use tinycortex::memory::goals::store;
+use crate::openhuman::memory::api::goals::GoalsDoc;
+use crate::openhuman::memory::api::provider::MemoryProvider;
/// Registry id of the bundled goals enrichment agent definition.
pub const GOALS_AGENT_ID: &str = "goals_agent";
@@ -56,17 +57,50 @@ fn build_prompt(context_input: &str, first_run: bool) -> String {
)
}
+/// The current goals document, through the bound driver's goals family.
+///
+/// Resolved here rather than passed in because of [`spawn_enrich_goals`]: that
+/// entry point detaches a `'static` task, which cannot hold a borrowed
+/// `&dyn MemoryGoals` across the spawn. `active_memory_guard` works inside a
+/// spawned task — `CoreContext::current` falls back to the process default
+/// context, which a detached task still sees.
+///
+/// # Errors
+///
+/// When no workspace can be named, or when the driver's read fails. A driver
+/// that does not serve the family is reported rather than degraded to an empty
+/// document: this answer decides `first_run`, and a false "the list is empty"
+/// tells the agent to bootstrap a list that already exists.
+async fn read_goals() -> Result<GoalsDoc, String> {
+ let guard = crate::openhuman::memory::ops::guard::active_memory_guard()
+ .await
+ .map_err(|e| format!("goals load failed: {e}"))?;
+ let goals = guard
+ .as_goals()
+ .ok_or_else(|| "goals load failed: memory driver does not support goals".to_string())?;
+ goals
+ .goals()
+ .await
+ .map_err(|e| format!("goals load failed: {e}"))
+}
+
/// Run the goals enrichment agent against `context_input` (typically a
/// session recap/summary, or an on-demand nudge). Returns the agent's final
/// text. Best-effort: the caller decides whether to ignore errors.
+///
+/// `workspace_dir` names the agent-definition registry's root, not the goals
+/// document — the list itself is reached through the driver (see
+/// [`read_goals`]).
pub async fn enrich_goals(
config: &Config,
workspace_dir: &Path,
context_input: &str,
) -> Result<String, String> {
// Surface real storage failures instead of masking them as an empty
- // first-run doc — `load` already maps a missing file to an empty doc.
- let doc = store::load(workspace_dir).map_err(|e| format!("goals load failed: {e}"))?;
+ // first-run doc. The distinction still holds through the family: a driver
+ // with no goals yet answers an empty `GoalsDoc` rather than `NotFound`, so
+ // an `Err` here is a real backend failure and never "the file is missing".
+ let doc = read_goals().await?;
let first_run = doc.is_empty();
log::info!(
"[memory_goals] enrich start (first_run={first_run}, existing_items={})",
diff --git a/src/openhuman/memory/goals/mod.rs b/src/openhuman/memory/goals/mod.rs
index 5cab3fcbec..b29dd22a28 100644
--- a/src/openhuman/memory/goals/mod.rs
+++ b/src/openhuman/memory/goals/mod.rs
@@ -1,11 +1,29 @@
//! The agent's long-term goals.
//!
-//! Unlike its sibling domains this one did **not** split across the memory
-//! extraction: its store lives in `tinycortex::memory::goals`, and everything
-//! above that — the RPC surface, the reflection agent, the agent tools — names
-//! host types. `tinymemory-core` briefly carried an empty `goals` module as a
-//! result; it was removed rather than left as a husk that re-exported nothing.
+//! # The split this domain landed on (#5560)
+//!
+//! It used to have none: the store was `tinycortex::memory::goals`, reached
+//! in-process, and everything above it — the RPC surface, the reflection agent,
+//! the agent tools — named host types around that one call. With the engine
+//! behind the loaded module, the contract splits the domain in the one place it
+//! can be split without moving policy across a trait boundary:
+//!
+//! - **Driver** ([`MemoryGoals`](crate::openhuman::memory::api::provider::MemoryGoals),
+//! two members): read the document, replace the document. With it go
+//! persistence, the symlink-escape check, and the item-count and byte-size
+//! caps — all facts about a store, which is the thing a driver owns.
+//! - **Host** ([`doc`]): parse, validate, mutate. `set_goals`' own contract
+//! docs say why the mutation surface may not be a driver's: the secret and
+//! PII predicates it runs are safety policy, and a per-item mutation member
+//! would put that policy behind a trait a third-party driver implements,
+//! where it could be skipped.
+//!
+//! [`ops`] is where those two halves meet — it holds the read-modify-write and
+//! the lock that serialises it. Everything else here is unchanged: [`enrich`]
+//! still runs the real `goals_agent`, and [`schemas`] still publishes the same
+//! `memory_goals.*` wire shape.
+pub mod doc;
pub mod enrich;
pub mod ops;
pub mod schemas;
diff --git a/src/openhuman/memory/goals/ops.rs b/src/openhuman/memory/goals/ops.rs
index 70222e8952..0645897523 100644
--- a/src/openhuman/memory/goals/ops.rs
+++ b/src/openhuman/memory/goals/ops.rs
@@ -1,15 +1,64 @@
-//! Business logic for the goals domain — thin handlers over [`super::store`]
-//! plus the on-demand reflection entry point. Every function returns an
-//! [`RpcOutcome`] so the RPC layer (and CLI) get a uniform shape with logs.
-
-use std::path::Path;
+//! Business logic for the goals domain — thin handlers over the driver's
+//! goals family, plus the on-demand reflection entry point. Every function
+//! returns an [`RpcOutcome`] so the RPC layer (and CLI) get a uniform shape
+//! with logs.
+//!
+//! # These take the driver's goals family, not a workspace path (#5560)
+//!
+//! They used to take `&Path` and call `tinycortex::memory::goals::store`,
+//! reaching `MEMORY_GOALS.md` in-process. The engine lives behind the loaded
+//! module now, so each handler takes `&dyn MemoryGoals` — the guarded family
+//! off the bound driver — and the file is opened on the far side.
+//!
+//! **Same file, and that is checkable rather than hopeful.** The module's
+//! `MemoryGoals::goals` is literally
+//! `tinycortex::memory::goals::store::load(&self.config.workspace_dir)`, and
+//! `set_goals` the matching `save` — the same two functions these handlers
+//! called, over the same path. It is the same path even for a profile with
+//! dedicated memory: `OpenStore` re-roots the *store* (the SQLite tree), while
+//! the provider it serves is built from the unchanged `EngineRuntimeConfig`,
+//! so `workspace_dir` is the workspace root on every object the module serves.
+//! Goals were workspace-wide before this change and are workspace-wide after
+//! it.
+//!
+//! ## What moved to this side, and what deliberately did not
+//!
+//! The contract splits the work at "who owns the safety policy":
+//!
+//! - **Host**: parse, validate, mutate. [`super::doc`] holds the trio and the
+//! secret/PII predicates they call, because `set_goals`' own contract says
+//! per-item mutation must not sit behind a trait a third-party driver
+//! implements, where it could be skipped.
+//! - **Driver**: persistence, the symlink-escape check, and the item-count and
+//! byte-size caps. A cap is the driver's judgement about its own store, and
+//! restating it here would be a second ceiling to keep in step.
+//!
+//! Because the caps are the driver's, a mutation cannot know its own result:
+//! `set_goals` answers with unit, and the document on disk may have had its
+//! oldest items trimmed away. So every mutation reads back with `goals()`
+//! afterwards, which is exactly the trimmed document the engine's `add` used to
+//! return by mutating its argument in place. One extra call, and the same
+//! answer — where re-deriving the trim locally would be the same answer only
+//! until the driver retuned a cap.
+//!
+//! ## The mutation lock is held across both calls
+//!
+//! `goals()` → mutate → `set_goals()` is a read-modify-write over a *whole
+//! document*, so two interleaved sequences do not merge — the later
+//! `set_goals` replaces the document the earlier one wrote, and a goal
+//! disappears. The engine serialised this behind a process-wide mutex;
+//! [`super::doc::mutation_lock`] is the same lock on this side of the module
+//! boundary, and it is acquired here rather than in `doc` because this is where
+//! the sequence lives.
use serde::Serialize;
use crate::openhuman::config::Config;
+use crate::openhuman::memory::api::goals::GoalsDoc;
+use crate::openhuman::memory::api::provider::MemoryGoals;
use crate::rpc::RpcOutcome;
-use tinycortex::memory::goals::store;
-use tinycortex_api::goals::GoalsDoc;
+
+use super::doc;
/// Result of an add operation: the new id plus the full updated list.
#[derive(Debug, Serialize)]
@@ -29,17 +78,38 @@ pub struct ReflectResult {
pub goals: GoalsDoc,
}
+/// Read the goals document through the family.
+///
+/// A driver with no goals yet answers an empty [`GoalsDoc`] rather than
+/// `NotFound` — "no goals" is a valid state — so this is the whole of `load`'s
+/// behaviour, including its missing-file case.
+async fn read(goals: &dyn MemoryGoals, op: &str) -> Result<GoalsDoc, String> {
+ goals.goals().await.map_err(|e| format!("{op}: {e}"))
+}
+
/// List the current goals.
-pub async fn list(workspace_dir: &Path) -> Result<RpcOutcome<GoalsDoc>, String> {
+pub async fn list(goals: &dyn MemoryGoals) -> Result<RpcOutcome<GoalsDoc>, String> {
log::debug!("[memory_goals] rpc=list");
- let doc = store::load(workspace_dir).map_err(|e| e.to_string())?;
+ let doc = read(goals, "list").await?;
Ok(RpcOutcome::new(doc, vec![]))
}
/// Add a goal and return the new id + updated list.
-pub async fn add(workspace_dir: &Path, text: &str) -> Result<RpcOutcome<AddResult>, String> {
+///
+/// The id survives cap trimming by construction: the caps drop the *oldest*
+/// items and the new goal is the newest, so the read-back always contains it
+/// unless that one goal alone exceeds the whole-file byte cap — which is the
+/// same edge the engine's `add` had.
+pub async fn add(goals: &dyn MemoryGoals, text: &str) -> Result<RpcOutcome<AddResult>, String> {
log::debug!("[memory_goals] rpc=add");
- let (id, goals) = store::add(workspace_dir, text).map_err(|e| e.to_string())?;
+ let _guard = doc::mutation_lock().lock().await;
+ let mut document = read(goals, "add").await?;
+ let id = doc::add_item(&mut document, text).map_err(|e| e.to_string())?;
+ goals
+ .set_goals(document)
+ .await
+ .map_err(|e| format!("add: {e}"))?;
+ let goals = read(goals, "add").await?;
Ok(RpcOutcome::single_log(
AddResult {
id: id.clone(),
@@ -51,28 +121,49 @@ pub async fn add(workspace_dir: &Path, text: &str) -> Result<RpcOutcome<AddResul
/// Edit a goal's text and return the updated list.
pub async fn edit(
- workspace_dir: &Path,
+ goals: &dyn MemoryGoals,
id: &str,
text: &str,
) -> Result<RpcOutcome<GoalsDoc>, String> {
log::debug!("[memory_goals] rpc=edit id={id}");
- let goals = store::edit(workspace_dir, id, text).map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(goals, format!("edited goal {id}")))
+ let _guard = doc::mutation_lock().lock().await;
+ let mut document = read(goals, "edit").await?;
+ doc::edit_item(&mut document, id, text).map_err(|e| e.to_string())?;
+ goals
+ .set_goals(document)
+ .await
+ .map_err(|e| format!("edit: {e}"))?;
+ let updated = read(goals, "edit").await?;
+ Ok(RpcOutcome::single_log(updated, format!("edited goal {id}")))
}
/// Delete a goal and return the updated list.
-pub async fn delete(workspace_dir: &Path, id: &str) -> Result<RpcOutcome<GoalsDoc>, String> {
+pub async fn delete(goals: &dyn MemoryGoals, id: &str) -> Result<RpcOutcome<GoalsDoc>, String> {
log::debug!("[memory_goals] rpc=delete id={id}");
- let goals = store::delete(workspace_dir, id).map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(goals, format!("deleted goal {id}")))
+ let _guard = doc::mutation_lock().lock().await;
+ let mut document = read(goals, "delete").await?;
+ doc::delete_item(&mut document, id).map_err(|e| e.to_string())?;
+ goals
+ .set_goals(document)
+ .await
+ .map_err(|e| format!("delete: {e}"))?;
+ let updated = read(goals, "delete").await?;
+ Ok(RpcOutcome::single_log(updated, format!("deleted goal {id}")))
}
/// On-demand enrichment: run the turn-based goals agent now, then return the
/// resulting list. Unlike the automatic summarization trigger (which fires
/// best-effort in the background), this awaits the agent so the caller sees
/// the updated list in the response.
+///
+/// Takes both a [`Config`] and the family: the config is what builds the agent
+/// and names the workspace its definition registry loads from, while the family
+/// is what reads the list back afterwards. The agent itself mutates the list
+/// through the `goals_*` tools, which resolve their own family — this handler
+/// never writes.
pub async fn reflect_now(
config: &Config,
+ goals: &dyn MemoryGoals,
context: Option<String>,
) -> Result<RpcOutcome<ReflectResult>, String> {
log::info!("[memory_goals] rpc=reflect — running goals agent on demand");
@@ -89,7 +180,11 @@ pub async fn reflect_now(
Ok(s) => s,
Err(e) => {
log::warn!("[memory_goals] reflect failed: {e}");
- let goals = store::load(&workspace_dir).unwrap_or_default();
+ // `unwrap_or_default` for the same reason it was there before: the
+ // caller is already being told the run failed, and a second failure
+ // reading the list back should not replace that report with a
+ // different one.
+ let goals = goals.goals().await.unwrap_or_default();
return Ok(RpcOutcome::single_log(
ReflectResult {
ran: false,
@@ -101,7 +196,7 @@ pub async fn reflect_now(
}
};
- let goals = store::load(&workspace_dir).unwrap_or_default();
+ let goals = goals.goals().await.unwrap_or_default();
Ok(RpcOutcome::single_log(
ReflectResult {
ran: true,
diff --git a/src/openhuman/memory/goals/ops_tests.rs b/src/openhuman/memory/goals/ops_tests.rs
index ea86ace781..4b2c39fc7b 100644
--- a/src/openhuman/memory/goals/ops_tests.rs
+++ b/src/openhuman/memory/goals/ops_tests.rs
@@ -1,30 +1,144 @@
+//! Handler tests for the goals domain.
+//!
+//! These used to run against a `tempfile::tempdir()` and the engine's
+//! filesystem store. The handlers take the driver's family now, so the fixture
+//! is a fake that implements exactly the two members `MemoryGoals` has —
+//! which is also what makes the read-back contract visible: the fake stores
+//! whatever it is given, so anything the handlers assert about the document
+//! afterwards is something they read back rather than something they assumed.
+
+use std::sync::Mutex;
+
+use async_trait::async_trait;
+
use super::*;
+use crate::openhuman::memory::api::error::MemoryError;
+
+/// A `MemoryGoals` that keeps the document in memory.
+///
+/// Deliberately **not** cap-enforcing: the caps are the driver's and the
+/// handlers must not depend on them, so a fixture that trimmed would hide a
+/// handler that had quietly taken on that job.
+#[derive(Default)]
+struct FakeGoals {
+ document: Mutex<GoalsDoc>,
+ /// Every `set_goals` the handler made, so a test can assert the write count
+ /// rather than only the end state.
+ writes: Mutex<usize>,
+}
+
+#[async_trait]
+impl MemoryGoals for FakeGoals {
+ async fn goals(&self) -> Result<GoalsDoc, MemoryError> {
+ Ok(self.document.lock().expect("goals fixture lock").clone())
+ }
+
+ async fn set_goals(&self, goals: GoalsDoc) -> Result<(), MemoryError> {
+ *self.document.lock().expect("goals fixture lock") = goals;
+ *self.writes.lock().expect("goals fixture lock") += 1;
+ Ok(())
+ }
+}
+
+/// A `MemoryGoals` whose writes always fail, for the refusal paths.
+struct FailingGoals;
+
+#[async_trait]
+impl MemoryGoals for FailingGoals {
+ async fn goals(&self) -> Result<GoalsDoc, MemoryError> {
+ Ok(GoalsDoc::default())
+ }
+
+ async fn set_goals(&self, _goals: GoalsDoc) -> Result<(), MemoryError> {
+ Err(MemoryError::Invalid("driver refused".to_string()))
+ }
+}
#[tokio::test]
async fn list_add_edit_delete_flow() {
- let tmp = tempfile::tempdir().unwrap();
- let dir = tmp.path();
+ let goals = FakeGoals::default();
// Starts empty.
- let listed = list(dir).await.unwrap();
+ let listed = list(&goals).await.unwrap();
assert!(listed.value.is_empty());
// Add returns an id and the updated list.
- let added = add(dir, "ship the desktop app").await.unwrap();
+ let added = add(&goals, "ship the desktop app").await.unwrap();
let id = added.value.id.clone();
assert_eq!(added.value.goals.items.len(), 1);
// Edit by id.
- let edited = edit(dir, &id, "ship the app to all platforms")
+ let edited = edit(&goals, &id, "ship the app to all platforms")
.await
.unwrap();
assert_eq!(edited.value.items[0].text, "ship the app to all platforms");
// Delete by id leaves the list empty.
- let deleted = delete(dir, &id).await.unwrap();
+ let deleted = delete(&goals, &id).await.unwrap();
assert!(deleted.value.is_empty());
// Unknown id is an error.
- assert!(edit(dir, "nope", "x").await.is_err());
- assert!(delete(dir, "nope").await.is_err());
+ assert!(edit(&goals, "nope", "x").await.is_err());
+ assert!(delete(&goals, "nope").await.is_err());
+}
+
+/// The result a mutation reports is the document the *driver* holds, not the
+/// one the handler assembled — which is the whole reason for the read-back.
+#[tokio::test]
+async fn a_mutation_reports_the_document_the_driver_kept() {
+ let goals = FakeGoals::default();
+ add(&goals, "first").await.unwrap();
+ let second = add(&goals, "second").await.unwrap();
+
+ assert_eq!(second.value.goals.items.len(), 2);
+ let stored = goals.goals().await.unwrap();
+ assert_eq!(
+ second.value.goals, stored,
+ "the reported list is read back, not reconstructed"
+ );
+}
+
+/// Validation runs before the write, so a refused goal costs no `set_goals`
+/// and cannot leave a partially-applied document behind.
+#[tokio::test]
+async fn invalid_text_is_refused_before_the_driver_is_asked() {
+ let goals = FakeGoals::default();
+
+ for bad in [
+ " ",
+ "line one\n- [x] injected",
+ "follow up with [email protected]",
+ ] {
+ assert!(add(&goals, bad).await.is_err(), "expected {bad:?} refused");
+ }
+
+ assert_eq!(
+ *goals.writes.lock().unwrap(),
+ 0,
+ "a refused mutation must never reach set_goals"
+ );
+ assert!(goals.goals().await.unwrap().is_empty());
+}
+
+/// The refusal message is the specific one the agent acts on, not the driver's
+/// catch-all.
+#[tokio::test]
+async fn refusal_names_the_specific_rule_that_was_broken() {
+ let goals = FakeGoals::default();
+ let err = add(&goals, " ").await.unwrap_err();
+ assert!(
+ err.contains("goal text must not be empty"),
+ "unexpected message: {err}"
+ );
+}
+
+/// A driver that refuses the write is reported as a failure — never as a
+/// success over the unchanged list.
+#[tokio::test]
+async fn a_driver_refusal_surfaces_rather_than_reading_back_a_stale_list() {
+ let err = add(&FailingGoals, "ship the desktop app")
+ .await
+ .unwrap_err();
+ assert!(err.starts_with("add: "), "unexpected message: {err}");
+ assert!(err.contains("driver refused"), "unexpected message: {err}");
}
diff --git a/src/openhuman/memory/goals/schemas.rs b/src/openhuman/memory/goals/schemas.rs
index 65ff2c974f..9042c0dde8 100644
--- a/src/openhuman/memory/goals/schemas.rs
+++ b/src/openhuman/memory/goals/schemas.rs
@@ -1,9 +1,16 @@
//! Controller schemas + JSON-RPC handlers for the `memory_goals` namespace.
//!
//! Methods are exposed as `openhuman.memory_goals_<function>`:
-//! `list`, `add`, `edit`, `delete`, `reflect`. Handlers load the active
-//! config (for `workspace_dir`), delegate to [`super::ops`], and serialise
-//! the [`RpcOutcome`] into the CLI-compatible JSON shape.
+//! `list`, `add`, `edit`, `delete`, `reflect`. Handlers resolve the guarded
+//! goals family for the dispatch, delegate to [`super::ops`], and serialise the
+//! [`RpcOutcome`] into the CLI-compatible JSON shape.
+//!
+//! The wire shape is a published compatibility surface and does not change
+//! here: `memory_goals.*` still answers with the same `GoalsDoc` /
+//! `{ id, goals }` / `{ ran, summary, goals }` bodies. What changed is where
+//! the document comes from — the bound driver rather than a path this handler
+//! passed down. `reflect` still loads the config, because the agent it runs is
+//! built from one.
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
@@ -12,6 +19,8 @@ use super::ops;
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use crate::openhuman::config::rpc as config_rpc;
+use crate::openhuman::memory::api::provider::MemoryProvider;
+use crate::openhuman::memory::ops::guard::active_memory_guard;
use crate::rpc::RpcOutcome;
/// All `memory_goals` controller schemas (advertised to CLI + RPC consumers).
@@ -149,42 +158,63 @@ fn schemas(function: &str) -> ControllerSchema {
// ── Handlers ─────────────────────────────────────────────────────────────
+/// The guarded driver for this dispatch, checked to serve the goals family.
+///
+/// Returned as the guard rather than as `&dyn MemoryGoals` because the family
+/// accessor borrows from it — a helper handing back the borrow directly would
+/// not outlive the call. Same shape, and the same reason, as
+/// `people::schemas::current_people_guard`.
+async fn current_goals_guard(
+) -> Result<std::sync::Arc<crate::openhuman::memory::guard::MemoryGuard>, String> {
+ let guard = active_memory_guard().await?;
+ if guard.as_goals().is_none() {
+ return Err("memory driver does not support the goals family".to_string());
+ }
+ Ok(guard)
+}
+
fn handle_list(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- to_json(ops::list(&config.workspace_dir).await?)
+ let guard = current_goals_guard().await?;
+ let goals = guard.as_goals().expect("checked in current_goals_guard");
+ to_json(ops::list(goals).await?)
})
}
fn handle_add(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let guard = current_goals_guard().await?;
+ let goals = guard.as_goals().expect("checked in current_goals_guard");
let req = parse_value::<AddParams>(Value::Object(params))?;
- to_json(ops::add(&config.workspace_dir, &req.text).await?)
+ to_json(ops::add(goals, &req.text).await?)
})
}
fn handle_edit(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let guard = current_goals_guard().await?;
+ let goals = guard.as_goals().expect("checked in current_goals_guard");
let req = parse_value::<EditParams>(Value::Object(params))?;
- to_json(ops::edit(&config.workspace_dir, &req.id, &req.text).await?)
+ to_json(ops::edit(goals, &req.id, &req.text).await?)
})
}
fn handle_delete(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let guard = current_goals_guard().await?;
+ let goals = guard.as_goals().expect("checked in current_goals_guard");
let req = parse_value::<DeleteParams>(Value::Object(params))?;
- to_json(ops::delete(&config.workspace_dir, &req.id).await?)
+ to_json(ops::delete(goals, &req.id).await?)
})
}
fn handle_reflect(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
+ let guard = current_goals_guard().await?;
+ let goals = guard.as_goals().expect("checked in current_goals_guard");
let req = parse_value::<ReflectParams>(Value::Object(params))?;
- to_json(ops::reflect_now(&config, req.context).await?)
+ to_json(ops::reflect_now(&config, goals, req.context).await?)
})
}
diff --git a/src/openhuman/memory/host_impls.rs b/src/openhuman/memory/host_impls.rs
index c8fe61fc82..a5bdfc5bca 100644
--- a/src/openhuman/memory/host_impls.rs
+++ b/src/openhuman/memory/host_impls.rs
@@ -25,6 +25,48 @@
//! should be live. Seams that must be live (`ConfigLoader`) take a `&Config`
//! argument and re-read instead.
//!
+//! # They are not dead code, and the check is not the driver class (#5560)
+//!
+//! `memory::binding` refuses `DriverClass::Embedded` outright — "embedded
+//! memory drivers are no longer supported; use the 'tinymemory' module driver"
+//! — and `modules::memory_host` serves this same set of seven over the bus for
+//! the module. Both facts together read like an argument that the in-process
+//! installs below are only reached from tests, and #5560 acted on exactly that
+//! reading once and had to be reverted. **The driver class is the wrong thing
+//! to check.** It governs what answers a `MemoryProvider` call; it says nothing
+//! about the free-function engine surface this crate still reaches through the
+//! `memory::tree` re-export facade, which bypasses the binding entirely — the
+//! "second unpoliced door" `memory::direct_engine_refs` is a ratchet over.
+//!
+//! Two production paths through that door land on a seam today, both on
+//! [`ChatHost`]:
+//!
+//! - `agent::harness::archivist::recap` calls `memory::tree::summarise::
+//! summarise` on every recap fold — the `#[cfg(not(test))]` arm, so no test
+//! override is involved — and that is `tinymemory_core::tree::summarise`,
+//! which builds its provider through `chat::build_chat_provider` →
+//! `chat_host::{provider_for_role, create_chat_model_with_model_id}`;
+//! - `memory::tools::doctor` and the `memory_tree_doctor` RPC call
+//! `memory::tree::health::async_run_doctor`, whose `doctor.rs` asks
+//! `chat_host::summarizer_available(config)` for the report's summariser row.
+//!
+//! The seams fail **loudly** when unwired rather than degrading, so removing
+//! the installs would not silently misbehave — it would break every recap and
+//! every doctor run with "no ChatHost installed". That is the failure #5560
+//! shipped once, as "no EmbeddingHost installed" on the chat hot path.
+//!
+//! [`reset_in_process_chunk_store`] is live for a different reason and survives
+//! independently: `memory::sources::status` reaches the engine's chunk store
+//! over raw SQLite, and `openhuman.memory_sources_status_list` — polled every
+//! five seconds by the sources UI — is what keeps that connection cached here.
+//!
+//! **So the question to re-ask is not "is the driver embedded" but "does any
+//! production caller still reach an engine free function".** `grep -rn
+//! 'tinymemory_core::' src --include='*.rs'` outside comments, plus the
+//! `memory::{tree, sources}` re-export shims, is the whole inventory; when that
+//! is empty this file's installs are dead and go with the manifest entry, in
+//! the same change.
+//!
//! # Composio no longer has a seam here
//!
//! `tinymemory_core::composio_host` was deleted in tinymemory v1.13.4 along
diff --git a/src/openhuman/memory/mod.rs b/src/openhuman/memory/mod.rs
index d0bff190a5..6380952a20 100644
--- a/src/openhuman/memory/mod.rs
+++ b/src/openhuman/memory/mod.rs
@@ -156,22 +156,27 @@ pub use tinycortex::memory::ingest::{
ExtractedEntity, ExtractedRelation, ExtractionMode, MemoryIngestionConfig,
MemoryIngestionRequest, MemoryIngestionResult, DEFAULT_MEMORY_EXTRACTION_MODEL,
};
-// The remaining four are genuinely `tinymemory-core`'s own: the in-process
-// ingest queue (`ingestion::queue`) and its status snapshot
-// (`ingestion::state`). They have no contract equivalent — the ingest queue is
-// named in `direct_engine_refs_tests`' upstream-gap list as one of the four
-// things with no bus representation at all — so this is what still pins the
-// engine crate here, and it is now visible as such rather than hidden in a
-// list of eleven.
+// The other four — `IngestionJob`, `IngestionQueue`, `IngestionState` and
+// `IngestionStatusSnapshot` — are genuinely `tinymemory-core`'s own: the
+// in-process ingest queue and its status snapshot, which `direct_engine_refs`
+// lists among the handful of things with no bus representation at all. They
+// used to be re-exported here beside the seven above, and that line is gone
+// (#5560).
//
-// `IngestionState` is the one with a live consumer
-// (`tests/raw_coverage/memory_raw_coverage_e2e.rs`). The other three are kept
-// because they are one module's worth of a single domain and splitting a queue
-// from its own job type would leave a re-export that documents nothing; when
-// the queue moves behind the bus they go together.
-pub use tinymemory_core::ingestion::{
- IngestionJob, IngestionQueue, IngestionState, IngestionStatusSnapshot,
-};
+// It was gone for want of a caller, not because the gap closed. Three of the
+// four had **no consumer anywhere** — not in `src/`, not in `tests/`, not in
+// the shell — and the fourth, `IngestionState`, had exactly one:
+// `tests/raw_coverage/memory_raw_coverage_e2e.rs`, an integration test, which
+// now names `tinymemory_core::ingestion` itself. That costs it nothing: the
+// engine crate stays a **dev-dependency**, which every `tests/` target links,
+// so the only thing this line was still buying was a *production* compile-time
+// link to the engine on behalf of nobody. Same reasoning, and the same
+// conclusion, as the `MemoryClient` / `UnifiedMemory` aliases dropped below.
+//
+// A production caller that genuinely needs the in-process queue should not get
+// it back through this facade — the queue belongs behind the bus, and reaching
+// it by re-export is the second unpoliced door `memory::binding` exists to
+// close.
// The host's own JSON-RPC request/response shapes. They lived in
// `tinymemory_core::rpc_models` and were re-exported here by a glob; nothing
// in `tinymemory` ever named one, so the engine crate was carrying this host's
diff --git a/src/openhuman/memory/ops/sync.rs b/src/openhuman/memory/ops/sync.rs
index de1e62f750..a8097b7710 100644
--- a/src/openhuman/memory/ops/sync.rs
+++ b/src/openhuman/memory/ops/sync.rs
@@ -3,21 +3,22 @@
//! Sync RPCs publish `DomainEvent::MemorySyncRequested` on the global event
//! bus — they are fire-and-forget hooks for future ingestion subscribers.
//!
-//! # One engine call is left here, and it is an openhuman#5560 blocker
+//! # The engine call that was here is gone (openhuman#5560)
//!
-//! - **`spawn_manual_sync` → `tinycortex::run_composio_connection`.** The
-//! engine's own `run_composio_connection_with_caps` opens with
-//! `global::client_if_ready().ok_or(… "memory client is not ready")`, so with
-//! the in-process engine gone every target fails and this handler emits
-//! `MemorySyncStage::Failed` per connection. Loud, at least, but wrong. There
-//! is no contract member to move to: the whole pipeline is `tinycortex`-shaped
-//! (a `SyncPipeline` over provider-specific fetchers), and the loaded module
-//! does not run it either — `tinymemory` v1.5.0's module carries a section
-//! headed "The periodic sync loops are deliberately NOT started here" with
-//! three named reasons. Manual sync and the periodic loop share this call, so
-//! they move together or not at all, and the ordering that imposes lives next
-//! to the loop it protects in
-//! [`memory::sync::composio`](crate::openhuman::memory::sync::composio).
+//! This section used to name one blocker: `spawn_manual_sync` reached
+//! `tinycortex::run_composio_connection`, whose
+//! `run_composio_connection_with_caps` opens with
+//! `global::client_if_ready().ok_or(… "memory client is not ready")` — so with
+//! the in-process engine gone, every target failed and the handler emitted
+//! `MemorySyncStage::Failed` per connection. Loud, but wrong.
+//!
+//! [`spawn_manual_sync`] runs the pass through
+//! [`integrations::composio::ops::run_sync_pass`](crate::openhuman::integrations::composio::ops::run_sync_pass)
+//! now — the tinyconnectors module for the fetch, the bound driver's
+//! `MemorySourceSink` for the write. The one thing this handler still does for
+//! itself is resolve the binding *before* the spawn, so a driver that accepts
+//! no source items is an error the caller sees rather than a status line a
+//! detached task emits into a channel nobody is reading yet.
//!
//! # `memory_ingestion_status` was the quiet one, and it is fixed
//!
diff --git a/src/openhuman/memory/people/mod.rs b/src/openhuman/memory/people/mod.rs
index 49435928c3..7e9afb353e 100644
--- a/src/openhuman/memory/people/mod.rs
+++ b/src/openhuman/memory/people/mod.rs
@@ -1,36 +1,34 @@
-//! Host layer over the engine's people domain.
+//! Host layer over the people domain: its JSON-RPC surface, and nothing else.
//!
-//! The domain itself lives in the engine crate; what stays here is its
-//! JSON-RPC surface — handlers and controller schemas name OpenHuman's
-//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
-//! The glob re-export keeps every historical `memory::people::…` path resolving.
+//! Handlers and controller schemas name OpenHuman's `RpcOutcome` and
+//! `ControllerSchema`, which the driver cannot see; the ranking, scoring and
+//! address-book work happens driver-side, behind
+//! [`MemoryPeople`](crate::openhuman::memory::api::provider::MemoryPeople).
//!
-//! # Why this names `tinycortex` rather than `tinymemory_core` (#5560)
+//! # The re-export is gone, because it had no readers left (#5560)
//!
-//! It used to read `pub use tinymemory_core::people::*;`, and that path was
-//! itself a re-export: `tinymemory_core::people` is
-//! `pub use crate::engine::backend::people::{address_book, migrations,
-//! resolver, scorer, store, types};`, and `engine::backend::people` is
-//! `pub use tinycortex::memory::people`. Both spellings therefore resolve to
-//! the **same six items**; naming the engine crate directly changes no item,
-//! only which crate alias holds them in the build.
+//! This module opened with `pub use tinycortex::memory::people::*;` — six
+//! engine modules (`address_book`, `migrations`, `resolver`, `scorer`, `store`,
+//! `types`) poured into `memory::people::*` so every historical path kept
+//! resolving. That was worth keeping while something walked those paths.
//!
-//! That matters because `tinymemory-core` is what #5560 is removing from the
-//! production dependency graph, while `tinycortex` stays — it is a direct
-//! dependency of this crate (`Cargo.toml`), it is where the memory engine
-//! actually lives, and ~40 files here already name `tinycortex::memory::…`.
-//! Same precedent as the `Memory` / `MemoryCategory` type re-exports in
-//! `memory/mod.rs`, which were repointed at the contract for the same reason.
+//! Nothing does. [`rpc`] took the family instead of a `PeopleStore` when it
+//! migrated, and it was the only production caller — a `grep` for the six names
+//! across `src/` now finds prose in `binding`'s module docs (an analogy to
+//! `people::store`'s workspace-keyed cache shape) and the `#[cfg(test)]`
+//! contacts gate below. A glob re-export with no consumer is not a
+//! compatibility surface; it is a dependency edge that keeps the engine crate
+//! named in production for the benefit of no call site.
//!
-//! **The `contacts` gate has to follow.** `address_book`'s macOS reader is
-//! `#[cfg(all(target_os = "macos", feature = "contacts"))]` *inside tinycortex*,
-//! and this crate reaches it today through `contacts = ["tinymemory-core/contacts"]`
-//! → `tinymemory-core`'s `contacts = ["tinycortex/contacts"]`. When the
-//! `tinymemory-core` normal dependency is dropped, that forward has to become
-//! `contacts = ["tinycortex/contacts"]` directly, or the gate test below stops
-//! testing anything.
-
-pub use tinycortex::memory::people::*;
+//! **The `contacts` gate outlives it, and deliberately.** `address_book`'s
+//! macOS reader is `#[cfg(all(target_os = "macos", feature = "contacts"))]`
+//! *inside the engine*, and this crate's `contacts` feature has to forward
+//! there or the reader is compiled out while `refresh_address_book` reports
+//! success having seeded nothing — the exact bug the gate was written for. So
+//! `mod_contacts_gate_tests_tests.rs` still names the engine crate, from
+//! `#[cfg(test)]`, and asserts the forward end to end. A test reference does
+//! not link the crate into the shipped binary; that is the whole distinction
+//! this change is drawn along.
pub mod rpc;
pub mod schemas;
diff --git a/src/openhuman/memory/people/mod_contacts_gate_tests_tests.rs b/src/openhuman/memory/people/mod_contacts_gate_tests_tests.rs
index a3add45bc1..1f5d15b197 100644
--- a/src/openhuman/memory/people/mod_contacts_gate_tests_tests.rs
+++ b/src/openhuman/memory/people/mod_contacts_gate_tests_tests.rs
@@ -16,10 +16,18 @@
///
/// Deliberately not a `cfg!(feature = ...)` self-assertion: that would pass
/// while the forward is broken, which is the entire bug.
+///
+/// Names the engine crate directly rather than through `super::*`, which was
+/// the glob re-export until #5560 deleted it as unused. This is the one
+/// remaining reader, it is `#[cfg(test)]`, and a test reference does not link
+/// the crate into the shipped binary — so the gate keeps testing the forward
+/// without the production edge it used to travel over.
#[test]
#[cfg(all(target_os = "macos", feature = "contacts"))]
fn contacts_feature_reaches_the_engine_reader() {
- use super::address_book::{AddressBookError, ContactsSource, SystemContactsSource};
+ use tinycortex::memory::people::address_book::{
+ AddressBookError, ContactsSource, SystemContactsSource,
+ };
// The stub arm returns Ok(vec![]) and can never report a permission
// failure. Reaching a `PermissionDenied` — or real contacts — proves the
@@ -36,7 +44,7 @@ fn contacts_feature_reaches_the_engine_reader() {
#[test]
#[cfg(not(target_os = "macos"))]
fn contacts_gate_is_a_no_op_off_macos() {
- use super::address_book::{ContactsSource, SystemContactsSource};
+ use tinycortex::memory::people::address_book::{ContactsSource, SystemContactsSource};
assert_eq!(
SystemContactsSource
diff --git a/src/openhuman/memory/query/ingest_document.rs b/src/openhuman/memory/query/ingest_document.rs
index 9b88094da4..4294211d89 100644
--- a/src/openhuman/memory/query/ingest_document.rs
+++ b/src/openhuman/memory/query/ingest_document.rs
@@ -2,11 +2,51 @@ use crate::openhuman::config::rpc as config_rpc;
use crate::openhuman::memory::tree::tree::rpc;
use crate::openhuman::tools::traits::{Tool, ToolResult};
use async_trait::async_trait;
-use chrono::Utc;
+use chrono::{DateTime, Utc};
+use serde::Serialize;
use serde_json::json;
-use tinycortex::memory::ingest::canonicalize::document::DocumentInput;
use tinymemory_api::chunks::SourceKind;
+/// The `document` ingest payload, as the driver's canonicaliser reads it.
+///
+/// # Why this is declared here rather than imported (#5560)
+///
+/// It was `tinycortex::memory::ingest::canonicalize::document::DocumentInput`,
+/// and the import was the last thing keeping the engine crate named in this
+/// file. The contract has no equivalent and should not: `IngestRequest::payload`
+/// is deliberately a `serde_json::Value`, because the shape a payload takes is
+/// owned by the *source kind*, and the set of source kinds grows without a
+/// contract change. A per-kind payload type in the contract would be the
+/// opposite of that.
+///
+/// So what crosses here is JSON, and what this struct is for is naming the
+/// field set that JSON must have. Serialize-only, for the same reason: the
+/// engine's type carries a `deserialize_with` that accepts epoch-millis,
+/// RFC 3339, or an absent timestamp, and none of that leniency is this
+/// producer's business — it always emits one shape. Reproducing the read side
+/// would be a second parser with no reader.
+///
+/// Field for field with the engine's declaration, in the same order, with no
+/// serde attributes on either side beyond the defaults, so the emitted object
+/// is byte-identical. `execute_success_path_roundtrips_document_chunk` is what
+/// checks that end to end: it ingests through this payload and reads the
+/// resulting chunk back, so a renamed or dropped field fails as a missing
+/// chunk rather than as a silent no-op.
+#[derive(Serialize)]
+struct DocumentInput {
+ /// Provider name (e.g. `notion`, `drive`, `meeting_notes`).
+ provider: String,
+ /// Document title.
+ title: String,
+ /// Document body (markdown preferred; plain text also accepted).
+ body: String,
+ /// When the document was last modified at the source. Emitted as RFC 3339,
+ /// which is one of the three forms the canonicaliser accepts.
+ modified_at: DateTime<Utc>,
+ /// Optional pointer back to source (URL, file path, Notion page id).
+ source_ref: Option<String>,
+}
+
pub struct MemoryTreeIngestDocumentTool;
#[async_trait]
diff --git a/src/openhuman/memory/read_rpc/admin.rs b/src/openhuman/memory/read_rpc/admin.rs
index b994f24569..12191c3d42 100644
--- a/src/openhuman/memory/read_rpc/admin.rs
+++ b/src/openhuman/memory/read_rpc/admin.rs
@@ -3,8 +3,18 @@ use anyhow::{Context, Result};
use crate::openhuman::config::Config;
use crate::openhuman::memory::api::provider::ForgetSelector;
use crate::rpc::RpcOutcome;
-use tinycortex::memory::sync::state::STATE_NAMESPACE as KV_NAMESPACE;
+// The KV namespace the Composio sync pipelines keep their per-connection
+// cursor state under, named at the **contract** (#5560).
+//
+// It used to be `tinycortex::memory::sync::state::STATE_NAMESPACE`. The
+// contract publishes the same string under `composio::KV_NAMESPACE`, and its
+// own docs mark it a compatibility surface for exactly the reason this handler
+// cares about: the value is on disk, so a wipe that spelled it differently
+// would leave every cursor behind while reporting a clean sweep. Taking the
+// constant rather than copying the literal is what keeps that impossible —
+// and it is the same constant the driver writing those rows reads.
use tinymemory_api::chunks::SourceKind;
+use tinymemory_api::composio::KV_NAMESPACE;
use super::types::{
DeleteSourceResponse, FlushNowResponse, FlushSourceTreeResponse, ResetTreeResponse,
diff --git a/src/openhuman/memory/sources/mod.rs b/src/openhuman/memory/sources/mod.rs
index adee7e1217..3392ae5b82 100644
--- a/src/openhuman/memory/sources/mod.rs
+++ b/src/openhuman/memory/sources/mod.rs
@@ -16,33 +16,49 @@
//! 2. **Two of the seven readers had no upstream twin.** `composio` and
//! `twitter` were implemented in the engine crate but named nothing
//! engine-shaped, so they came home unchanged. See [`readers`].
-//! 3. **`sync`, `status` and `reconcile` are wired into pieces that have not
-//! moved.** This one still stands, and is why those three are still reached
-//! from the engine by name below rather than through a glob.
+//! 3. **`sync` and `status` are wired into pieces that have not moved.** This
+//! one still stands, and is why those two are still reached from the engine
+//! by name below rather than through a glob. `reconcile` was on this line as
+//! well and has since come home — see below.
//!
//! ## What is still the engine's, and why each one
//!
//! - [`sync`] reaches `engine::run_source_pipeline`, `engine::{needs_rebuild,
//! rebuild_tree_from_raw}`, `queue::store::retry_all_failed`,
//! `sync::composio` and `sync::audit` — the ingest pipeline, the re-embed
-//! queue and the Composio sync half.
+//! queue and the Composio sync half. Only `derive_scopes` is reached from
+//! production today (`rpc::reconcile_rpc`); `sync_source` itself has no
+//! caller left in `src/`, because the sync the product runs goes over the bus
+//! through `MemorySourceSync`. The module is kept whole rather than narrowed
+//! to the one live function: a re-export that hides which half is dead would
+//! make the next audit harder, not easier.
//! - [`status`] reaches `store::chunks::store::with_connection`, the raw SQLite
-//! chunk door. **`MemoryChunks::source_totals` is not a substitute**, and
-//! this is worth stating because it looks like one: `SourceTotal` carries
-//! `chunk_count` and `most_recent_ms` but no `chunks_pending`, and pending —
-//! "has no embedding, was not dropped, was not skipped for re-embed" — is the
-//! whole point of a sync-status row. `source_totals` also omits a source with
-//! zero chunks entirely, where `status_list` returns a row per *configured*
-//! source. Migrating onto it would compile and quietly report a healthy
-//! store. The ask upstream is a pending count.
-//! - [`reconcile`] is Composio source reconciliation, so it moves with
-//! `sync::composio`.
+//! chunk door, and is live in production behind
+//! `memory_sources.status_list`. **`MemoryChunks::source_totals` is not a
+//! substitute**, and this is worth stating because it looks like one:
+//! `SourceTotal` carries `chunk_count` and `most_recent_ms` but no
+//! `chunks_pending`, and pending — "has no embedding, was not dropped, was
+//! not skipped for re-embed" — is the whole point of a sync-status row.
+//! `source_totals` also omits a source with zero chunks entirely, where
+//! `status_list` returns a row per *configured* source. Migrating onto it
+//! would compile and quietly report a healthy store. The ask upstream is a
+//! pending count.
//!
-//! Porting those as they stand would move the ingest pipeline and the raw
+//! Porting those two as they stand would move the ingest pipeline and the raw
//! chunk door *into* the host rather than behind the bus, which is the opposite
//! of what #5560 is for: a second unpoliced door spelled differently is still a
//! second unpoliced door.
//!
+//! ## What came home, and why it was different
+//!
+//! [`reconcile`] was on the blocked list and no longer is. Both of its halves
+//! read the `[[memory_sources]]` table in **this host's own config file** and
+//! nothing below it: the scan came home when tinymemory v1.13.4 deleted the
+//! in-process Composio pipeline it used to call, and
+//! `apply_composio_source_caps_migration` followed in #5560. That is the line
+//! between the two lists — a config rewrite is host work that happened to live
+//! upstream, where an ingest pipeline and a SQLite cursor are not.
+//!
//! `MemorySourceSink` is not the answer for the registry either — it is
//! `accept_source_items` + `forget_source` + `forget_matching`, an *ingest*
//! door with no listing or CRUD member for a configured connector, and it is
@@ -74,13 +90,15 @@ pub use types::{ContentType, MemorySourceEntry, SourceContent, SourceItem, Sourc
// honest inventory of what is left. See the module docs for what blocks each.
pub use tinymemory_core::sources::{status, sync};
-// `reconcile` used to be entirely the engine's too. tinymemory v1.13.4
-// deleted `ensure_composio_sources` along with the rest of the in-process
-// Composio pipeline it scanned (`sync::composio::scan_active_sync_targets`),
-// so this host now carries its own — built on
+// `reconcile` used to be entirely the engine's. tinymemory v1.13.4 deleted
+// `ensure_composio_sources` along with the rest of the in-process Composio
+// pipeline it scanned (`sync::composio::scan_active_sync_targets`), so this
+// host carries its own — built on
// `memory::sync::composio::scan_active_sync_targets`, the tinyconnectors
-// replacement — while `apply_composio_source_caps_migration` (which never
-// touched the deleted pipeline) stays the engine's.
+// replacement. `apply_composio_source_caps_migration` followed it home in
+// #5560: it never touched the deleted pipeline, only this host's config file,
+// and reaching it through the engine bought a compile-time link to the engine
+// for a `config.toml` rewrite.
pub mod reconcile;
// The controller aggregators this domain's RPC surface defines. Aliased
diff --git a/src/openhuman/memory/sources/reconcile.rs b/src/openhuman/memory/sources/reconcile.rs
index 1f3119b315..d74312ff50 100644
--- a/src/openhuman/memory/sources/reconcile.rs
+++ b/src/openhuman/memory/sources/reconcile.rs
@@ -12,14 +12,35 @@
//! host's own replacement built on the `tinyconnectors` module, instead of
//! the deleted engine function of the same name.
//!
-//! `apply_composio_source_caps_migration` itself is untouched and still comes
-//! from the engine (`tinymemory_core::sources::reconcile`) — it never read
-//! the deleted pipeline, only the registry.
+//! [`apply_composio_source_caps_migration`] came home in the same spirit, one
+//! step later (#5560). It was the last line in this domain naming
+//! `tinymemory_core`, and it named it for a **config migration over this
+//! host's own `config.toml`**: load the config, read `[[memory_sources]]`,
+//! fill in per-toolkit caps, bump the version guard, save. Nothing in it is
+//! engine-shaped — no store, no SQLite, no TinyCortex — and the two helpers it
+//! leans on (`memory_sync_defaults_for_toolkit`, `apply_kind_defaults`) are
+//! `tinymemory-sources`', already a direct dependency and already re-exported
+//! by [`registry`]. Same route, and the same argument, as the registry itself
+//! took when it moved into `sources::registry`.
+//!
+//! The port is function for function, with one simplification that is not a
+//! behaviour change: the engine reached the registry through
+//! `MemoryHostConfig::{memory_sources_json, set_memory_sources_json}`, a serde
+//! round-trip that exists only because `MemorySourceEntry` is foreign to the
+//! dependency-light contract crate. Here the entries are a field on the host's
+//! own `Config`, so they are edited in place. The version guard, the
+//! skip-when-current early return, the write-lock ordering and the
+//! save-even-when-nothing-migrated behaviour are all carried over unchanged.
use std::collections::HashSet;
use crate::openhuman::config::rpc as config_rpc;
use crate::openhuman::memory::sources::registry;
+use crate::openhuman::memory::sources::types::{MemorySourceEntry, SourceKind};
+
+/// Current version of the caps migration. Bump when the migration logic
+/// changes, so installs that ran an earlier revision re-run it exactly once.
+const CURRENT_CAPS_MIGRATION_VERSION: u32 = 1;
/// Reconcile active Composio connections into the memory sources registry and
/// return the live active-connection set scanned this call.
@@ -84,12 +105,12 @@ pub async fn ensure_composio_sources() -> Option<HashSet<String>> {
);
}
- // Run the one-time caps migration after the reconcile loop so any
- // sources upserted just above are also considered. Still the engine's —
- // it only ever read the registry, never the deleted pipeline.
- if let Err(e) =
- tinymemory_core::sources::reconcile::apply_composio_source_caps_migration().await
- {
+ // Run the one-time caps migration after the reconcile loop so any sources
+ // upserted just above are also considered. Ordering, not decoration: a
+ // connection that only appeared in this pass would otherwise wait a whole
+ // extra reconcile for its caps, and sync at the provider's ceiling in the
+ // meantime.
+ if let Err(e) = apply_composio_source_caps_migration().await {
tracing::warn!(
error = %e,
"[memory_sources:reconcile] caps migration failed (non-fatal, will retry next time)"
@@ -145,6 +166,102 @@ fn short_id(id: &str) -> &str {
&id[start..]
}
+/// Apply conservative default caps in place to every cap-less source.
+///
+/// For a Composio source with no `max_items` / `sync_depth_days`, writes the
+/// per-toolkit defaults **and enables it** (a no-op when already enabled) — an
+/// already-enabled, cap-less source would otherwise sync at the provider's
+/// large internal ceiling instead of the cheap default, which is the cost this
+/// migration exists to avoid. For other kinds it fills any unset kind-specific
+/// caps through [`registry::apply_kind_defaults`]. Caps the user has
+/// customised (any non-`None` value) are never overwritten.
+///
+/// Returns the number of Composio entries that received defaults. Pure (no
+/// I/O) so it can be unit-tested directly.
+fn apply_caps_defaults_to_entries(sources: &mut [MemorySourceEntry]) -> u32 {
+ let mut applied = 0u32;
+ for source in sources.iter_mut() {
+ match source.kind {
+ SourceKind::Composio => {
+ // Applies to enabled AND disabled cap-less sources; skips
+ // entries the user has already customised (any non-None cap).
+ if source.max_items.is_none() && source.sync_depth_days.is_none() {
+ let toolkit = source.toolkit.as_deref().unwrap_or("");
+ let (max_items, sync_depth_days) =
+ registry::memory_sync_defaults_for_toolkit(toolkit);
+ tracing::debug!(
+ id = %source.id,
+ toolkit = %toolkit,
+ was_enabled = source.enabled,
+ max_items = ?max_items,
+ sync_depth_days = ?sync_depth_days,
+ "[memory_sources:reconcile] caps migration: applying conservative defaults"
+ );
+ source.enabled = true;
+ source.max_items = max_items;
+ source.sync_depth_days = sync_depth_days;
+ applied += 1;
+ }
+ }
+ // Non-composio kinds get their kind defaults through the same
+ // helper the CRUD path uses, so one table of conservative values
+ // serves both.
+ _ => registry::apply_kind_defaults(source),
+ }
+ }
+ applied
+}
+
+/// Retroactive migration: give any cap-less Composio source — enabled or
+/// disabled — conservative per-toolkit caps so its first sync stays cheap.
+///
+/// Version-gated by `Config::composio_source_caps_migration_version`: it runs
+/// once per [`CURRENT_CAPS_MIGRATION_VERSION`] bump, so an install that already
+/// ran an earlier revision re-runs the current one exactly once. Entries the
+/// user has customised are left untouched.
+///
+/// Takes the registry write guard for the whole load-modify-save, because the
+/// migration rewrites the entire `[[memory_sources]]` table: without it a
+/// concurrent upsert would be read, mutated and written back over, with no
+/// error anywhere.
+///
+/// # Errors
+///
+/// Stringified, when the config cannot be loaded or saved.
+pub async fn apply_composio_source_caps_migration() -> Result<(), String> {
+ let _guard = registry::memory_sources_write_guard().await;
+ let mut config = config_rpc::load_config_with_timeout().await?;
+
+ if config.composio_source_caps_migration_version >= CURRENT_CAPS_MIGRATION_VERSION {
+ tracing::debug!(
+ version = config.composio_source_caps_migration_version,
+ "[memory_sources:reconcile] caps migration already at current version; skipping"
+ );
+ return Ok(());
+ }
+
+ tracing::info!(
+ from_version = config.composio_source_caps_migration_version,
+ to_version = CURRENT_CAPS_MIGRATION_VERSION,
+ "[memory_sources:reconcile] applying composio source caps migration"
+ );
+
+ let migrated_count = apply_caps_defaults_to_entries(&mut config.memory_sources);
+
+ config.composio_source_caps_migration_version = CURRENT_CAPS_MIGRATION_VERSION;
+ config
+ .save()
+ .await
+ .map_err(|e| format!("caps migration: failed to save config: {e:#}"))?;
+
+ tracing::info!(
+ migrated = migrated_count,
+ "[memory_sources:reconcile] caps migration complete"
+ );
+
+ Ok(())
+}
+
#[cfg(test)]
#[path = "reconcile_tests.rs"]
mod tests;
diff --git a/src/openhuman/memory/sources/reconcile_tests.rs b/src/openhuman/memory/sources/reconcile_tests.rs
index e9d8cd3018..cc5e408de0 100644
--- a/src/openhuman/memory/sources/reconcile_tests.rs
+++ b/src/openhuman/memory/sources/reconcile_tests.rs
@@ -49,3 +49,129 @@ fn short_id_utf8_safe() {
let out = short_id(s);
assert_eq!(out.chars().count(), 8);
}
+
+// ── Caps migration ──────────────────────────────────────────────────────────
+//
+// The transform came home with `apply_composio_source_caps_migration` (#5560),
+// so its predicate is this crate's to pin. These exercise
+// `apply_caps_defaults_to_entries` — the real production function, not a
+// re-statement of it — because the migration's whole risk is in which entries
+// it decides to touch: an over-eager pass overwrites a cap the user chose, and
+// a shy one leaves an enabled, cap-less connector syncing at the provider's
+// internal ceiling.
+
+fn composio_entry(
+ id: &str,
+ toolkit: &str,
+ enabled: bool,
+ max_items: Option<u32>,
+ sync_depth_days: Option<u32>,
+) -> MemorySourceEntry {
+ MemorySourceEntry {
+ id: id.to_string(),
+ kind: SourceKind::Composio,
+ label: toolkit.to_string(),
+ enabled,
+ toolkit: Some(toolkit.to_string()),
+ connection_id: Some(format!("conn_{id}")),
+ path: None,
+ glob: None,
+ url: None,
+ branch: None,
+ paths: Vec::new(),
+ max_commits: None,
+ max_issues: None,
+ max_prs: None,
+ query: None,
+ since_days: None,
+ max_items,
+ selector: None,
+ max_tokens_per_sync: None,
+ max_cost_per_sync_usd: None,
+ sync_depth_days,
+ }
+}
+
+#[test]
+fn migration_flips_disabled_capless_entry_to_enabled_with_caps() {
+ let mut sources = vec![composio_entry("s1", "gmail", false, None, None)];
+ let count = apply_caps_defaults_to_entries(&mut sources);
+ assert_eq!(count, 1);
+ assert!(sources[0].enabled);
+ assert_eq!(sources[0].max_items, Some(100));
+ assert_eq!(sources[0].sync_depth_days, Some(30));
+}
+
+#[test]
+fn migration_applies_defaults_to_enabled_capless_entry() {
+ // An already-enabled but cap-less source must also receive defaults —
+ // otherwise its first sync runs at the provider's large internal ceiling.
+ let mut sources = vec![composio_entry("s2", "slack", true, None, None)];
+ let count = apply_caps_defaults_to_entries(&mut sources);
+ assert_eq!(count, 1);
+ assert!(sources[0].enabled);
+ assert_eq!(sources[0].max_items, Some(50));
+ assert_eq!(sources[0].sync_depth_days, Some(14));
+}
+
+#[test]
+fn migration_leaves_user_customised_caps_untouched() {
+ // The user set max_items explicitly, so the migration must not override it
+ // — and must not flip `enabled` on its way past either.
+ let mut sources = vec![composio_entry("s3", "notion", false, Some(5), None)];
+ let count = apply_caps_defaults_to_entries(&mut sources);
+ assert_eq!(count, 0, "entry with user-set caps must not be migrated");
+ assert!(!sources[0].enabled, "enabled must not be flipped");
+ assert_eq!(sources[0].max_items, Some(5), "user cap must be preserved");
+}
+
+#[test]
+fn migration_is_noop_on_empty_list() {
+ let mut sources: Vec<MemorySourceEntry> = vec![];
+ assert_eq!(apply_caps_defaults_to_entries(&mut sources), 0);
+}
+
+#[test]
+fn migration_applies_correct_defaults_per_toolkit() {
+ let toolkits = [
+ ("gmail", Some(100u32), Some(30u32)),
+ ("slack", Some(50), Some(14)),
+ ("notion", Some(30), Some(30)),
+ ("linear", Some(50), Some(30)),
+ ("clickup", Some(50), Some(30)),
+ ("github", Some(50), Some(30)),
+ ("unknown", Some(30), Some(14)),
+ ];
+ for (toolkit, exp_items, exp_days) in &toolkits {
+ let mut sources = vec![composio_entry("sid", toolkit, false, None, None)];
+ apply_caps_defaults_to_entries(&mut sources);
+ assert_eq!(
+ sources[0].max_items, *exp_items,
+ "max_items mismatch for toolkit={toolkit}"
+ );
+ assert_eq!(
+ sources[0].sync_depth_days, *exp_days,
+ "sync_depth_days mismatch for toolkit={toolkit}"
+ );
+ }
+}
+
+/// The non-Composio arm goes through `apply_kind_defaults`, which fills the
+/// kind's own caps and — unlike the Composio arm — never enables anything and
+/// never counts towards the returned tally.
+#[test]
+fn migration_fills_kind_defaults_without_counting_them() {
+ let mut repo = composio_entry("s4", "github", false, None, None);
+ repo.kind = SourceKind::GithubRepo;
+ repo.toolkit = None;
+ repo.connection_id = None;
+ repo.url = Some("https://github.com/tinyhumansai/openhuman".to_string());
+
+ let mut sources = vec![repo];
+ let count = apply_caps_defaults_to_entries(&mut sources);
+
+ assert_eq!(count, 0, "only composio entries count as migrated");
+ assert!(!sources[0].enabled, "kind defaults must not enable a source");
+ assert_eq!(sources[0].max_prs, Some(10));
+ assert!(sources[0].max_issues.is_some());
+}
diff --git a/src/openhuman/memory/sync/mod.rs b/src/openhuman/memory/sync/mod.rs
index 436ca403ae..17460a13a7 100644
--- a/src/openhuman/memory/sync/mod.rs
+++ b/src/openhuman/memory/sync/mod.rs
@@ -12,10 +12,8 @@
//! other two names it carried (`composio`, `sync_status`) are declared below
//! and an explicit item shadows a glob import. A repo-wide search for those
//! four under this path found **no consumer**: not in `src/`, not in `tests/`,
-//! not in the desktop shell's separate Cargo world. Every real caller reaches
-//! the engine's sync pipelines by naming `tinycortex::memory::sync::…` (see
-//! `integrations::composio::ops::memory_cleanup`) or goes through
-//! `memory::sync::composio`, which is its own module.
+//! not in the desktop shell's separate Cargo world. Every real caller goes
+//! through `memory::sync::composio`, which is its own module.
//!
//! So this line was a compile-time edge to `tinymemory-core` bought for nobody,
//! and dropping it is not a carve-out or a substitution — nothing resolved
@@ -23,9 +21,13 @@
//! bearing (`composio`, `composio::providers`, `composio::providers::slack`)
//! keep theirs and say what pins them.
//!
-//! Note that `sync_status` made the opposite move earlier and for a different
-//! reason: its glob carried two real names, and they were repointed at
-//! `tinycortex`, which defines them. See that module's own docs.
+//! [`sync_status`] took a different route, twice. Its glob carried two names
+//! that *were* real, so they could not simply be dropped; they were repointed
+//! at the engine crate that defined them, and then — once its `rpc` started
+//! reading the driver's `MemorySourceSync::sync_statuses` instead of the
+//! engine's SQLite query — declared in that module outright, as the wire types
+//! they had always been on this side of the call. See its own docs for why the
+//! contract's `SourceSyncStatus` is deliberately not aliased in their place.
pub mod composio;
pub mod sync_status;
diff --git a/src/openhuman/memory/sync/sync_status/mod.rs b/src/openhuman/memory/sync/sync_status/mod.rs
index 6ad6bacebf..26e811a56a 100644
--- a/src/openhuman/memory/sync/sync_status/mod.rs
+++ b/src/openhuman/memory/sync/sync_status/mod.rs
@@ -1,48 +1,112 @@
-//! Host layer over the engine's sync-status vocabulary.
+//! The `memory_sync.status_list` domain: its wire types and its JSON-RPC
+//! surface.
//!
-//! The domain itself lives in the engine; what stays here is its JSON-RPC
-//! surface — handlers and controller schemas name OpenHuman's `RpcOutcome` and
-//! `ControllerSchema`, which the engine crate cannot see. The re-export below
-//! keeps every historical `memory::sync::sync_status::…` path resolving.
+//! # The producer left; the wire shape stayed (#5560)
//!
-//! # Why this names `tinycortex` rather than `tinymemory_core` (#5560)
+//! These three types had two homes before this change and neither of them is
+//! reachable now. The path was `pub use tinymemory_core::sync::sync_status::*;`
+//! and then, when `tinymemory-core` left the production graph,
+//! `pub use tinycortex::memory::sync::{FreshnessLabel, MemorySyncStatus}` —
+//! naming the crate that *defined* them, because the engine's SQLite-backed
+//! `list_sync_statuses` was what produced them.
//!
-//! It used to read `pub use tinymemory_core::sync::sync_status::*;`, and that
-//! glob had exactly two `pub` items — `FreshnessLabel` and `MemorySyncStatus`.
-//! **Neither was the one this domain actually returns.** `rpc::status_list_rpc`
-//! builds its reply from `tinycortex::memory::sync::{StatusListResponse,
-//! MemorySyncStatus}`, produced by `tinycortex`'s SQLite-backed
-//! `list_sync_statuses`; `tinymemory-core`'s pair is a second declaration of
-//! the same two shapes with no producer behind it. Its own module doc says so:
-//! "today the only *producer* is the engine's SQLite-backed
-//! `list_sync_statuses`, which OpenHuman still calls directly … the serde shape
-//! matches the engine's copy field for field."
+//! [`rpc`] no longer calls `list_sync_statuses`. It asks the bound driver's
+//! `MemorySourceSync::sync_statuses`, which answers in the contract's own
+//! [`SourceSyncStatus`](tinymemory_api::provider::sync::SourceSyncStatus) — so
+//! the *producer* is contract-shaped and the engine's declaration has no
+//! remaining reader.
//!
-//! So this is not a substitute — it is the **same two items**, named through
-//! the crate that defines them instead of through a twin. Verified rather than
-//! assumed: both `FreshnessLabel`s are `#[serde(rename_all = "snake_case")]`
-//! over `Active`/`Recent`/`Idle` with the identical `from_age_ms` thresholds
-//! (30s → `Active`, 5min → `Recent`, else `Idle`), and both `MemorySyncStatus`
-//! carry the same seven fields in the same order.
+//! What could not follow it across is the **published response shape**.
+//! `memory_sync.status_list` has always answered `{ statuses: [...] }` with a
+//! `freshness` string beside six counters, and the contract's type is not that
+//! shape: it is the same seven fields under a different type name
+//! (`SyncFreshness`, not `FreshnessLabel`), which is a different Rust type even
+//! where it is the same JSON. Aliasing the contract type here would work today
+//! and would silently republish whatever the contract renamed tomorrow, on a
+//! surface a frontend reads.
//!
-//! That matters because `tinymemory-core` is what #5560 removes from the
-//! production dependency graph, while `tinycortex` stays — it is a direct
-//! dependency of this crate (`Cargo.toml`), it is where the engine actually
-//! lives, and `rpc.rs` in this very directory already names
-//! `tinycortex::memory::sync`. Same precedent as `memory::people`, which
-//! repointed for the same reason.
+//! So the three came home as what they always were on this side of the call:
+//! **the wire types, and only the wire types**. [`rpc::into_wire`] is the one
+//! place the contract's shape becomes this one, and it is a field-for-field
+//! destructure, so a contract field that is added, removed or renamed is a
+//! compile error there rather than a changed response.
//!
-//! **Named, not globbed, and that is deliberate.** `tinycortex::memory::sync`
-//! re-exports ~50 items — every sync pipeline, `SyncState`, `SyncDispatcher`,
-//! the audit log — and pouring those into `memory::sync::sync_status::*` would
-//! widen this path far past the two names the old glob carried. Two names in,
-//! two names out.
+//! Carried verbatim from the engine's declaration — same field order, same
+//! `#[serde(rename_all = "snake_case")]`, same derives — because the JSON is
+//! the compatibility surface and `response_keeps_top_level_statuses_array`
+//! pins the envelope.
-pub use tinycortex::memory::sync::{FreshnessLabel, MemorySyncStatus};
+use serde::{Deserialize, Serialize};
pub mod rpc;
pub mod schemas;
+/// How recently a provider last wrote a chunk.
+///
+/// The wire strings are `active` / `recent` / `idle`; the frontend switches on
+/// them, so the `rename_all` is load-bearing rather than cosmetic.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FreshnessLabel {
+ /// Wrote something within the last 30 seconds.
+ Active,
+ /// Wrote something within the last 5 minutes.
+ Recent,
+ /// Wrote nothing recently, or has never written anything.
+ Idle,
+}
+
+impl FreshnessLabel {
+ /// Classify an age in milliseconds against the two thresholds this label
+ /// has always used: 30s → [`Self::Active`], 5min → [`Self::Recent`],
+ /// otherwise [`Self::Idle`]. A provider that has never written a chunk is
+ /// [`Self::Idle`] rather than an error.
+ ///
+ /// Kept beside the type although [`rpc::into_wire`] maps the driver's
+ /// answer rather than deriving one: the driver classifies with these
+ /// thresholds, so having them written down on this side is what makes the
+ /// mapping checkable — and a host that ever has to classify a timestamp
+ /// itself must not invent a third set.
+ pub fn from_age_ms(last_chunk_at_ms: Option<i64>, now_ms: i64) -> Self {
+ match last_chunk_at_ms {
+ None => Self::Idle,
+ Some(timestamp) => match now_ms.saturating_sub(timestamp) {
+ age if age <= 30_000 => Self::Active,
+ age if age <= 5 * 60_000 => Self::Recent,
+ _ => Self::Idle,
+ },
+ }
+ }
+}
+
+/// One row of `memory_sync.status_list`: what one provider has in the tree.
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub struct MemorySyncStatus {
+ /// Provider slug, derived from the source id's prefix or its source kind.
+ pub provider: String,
+ /// Chunks this provider has that are resolved (embedded, dropped, or
+ /// explicitly skipped).
+ pub chunks_synced: u64,
+ /// Chunks still awaiting resolution within the current wave.
+ pub chunks_pending: u64,
+ /// Total chunks in the current wave.
+ pub batch_total: u64,
+ /// Chunks of the current wave already processed.
+ pub batch_processed: u64,
+ /// Epoch milliseconds of the newest chunk, when there is one.
+ pub last_chunk_at_ms: Option<i64>,
+ /// [`FreshnessLabel::from_age_ms`] over [`Self::last_chunk_at_ms`].
+ pub freshness: FreshnessLabel,
+}
+
+/// The response envelope. A top-level `statuses` array, and nothing else —
+/// `rpc::tests::response_keeps_top_level_statuses_array` pins exactly that.
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub struct StatusListResponse {
+ /// One row per provider that has chunks in the memory tree.
+ pub statuses: Vec<MemorySyncStatus>,
+}
+
// The controller aggregators this domain's RPC surface defines. Aliased
// exactly as the pre-extraction module exported them.
pub use schemas::{
diff --git a/src/openhuman/memory/sync/sync_status/rpc.rs b/src/openhuman/memory/sync/sync_status/rpc.rs
index 5eb8ee2b39..6c6f5aa2f8 100644
--- a/src/openhuman/memory/sync/sync_status/rpc.rs
+++ b/src/openhuman/memory/sync/sync_status/rpc.rs
@@ -3,9 +3,10 @@
use crate::openhuman::config::Config;
use crate::rpc::RpcOutcome;
-use tinycortex::memory::sync::{FreshnessLabel, MemorySyncStatus, StatusListResponse};
use tinymemory_api::provider::sync::{SourceSyncStatus, SyncFreshness};
+use super::{FreshnessLabel, MemorySyncStatus, StatusListResponse};
+
/// Carry one status across as the wire type this RPC has always answered.
///
/// Field-for-field, and that is checkable rather than hopeful: the contract's
@@ -16,7 +17,12 @@ use tinymemory_api::provider::sync::{SourceSyncStatus, SyncFreshness};
/// `rename_all = "snake_case"`. The response body is therefore byte-identical
/// to what the engine call produced — `response_keeps_top_level_statuses_array`
/// still holds.
-fn into_wire(status: SourceSyncStatus) -> MemorySyncStatus {
+///
+/// The destructure is deliberate and is the reason this function is not a
+/// `From` impl over `..`: it is the one seam between the contract's shape and
+/// the published one, so a field added, removed or renamed upstream has to fail
+/// here rather than quietly change what `memory_sync.status_list` answers.
+pub(super) fn into_wire(status: SourceSyncStatus) -> MemorySyncStatus {
let SourceSyncStatus {
provider,
chunks_synced,
diff --git a/src/openhuman/memory/sync/sync_status/schemas.rs b/src/openhuman/memory/sync/sync_status/schemas.rs
index c86d0ec808..b98be5fe58 100644
--- a/src/openhuman/memory/sync/sync_status/schemas.rs
+++ b/src/openhuman/memory/sync/sync_status/schemas.rs
@@ -2,8 +2,13 @@
//!
//! Wired into `src/core/all.rs` via the `all_memory_sync_status_*`
//! re-exports in `super::mod`. Single method now — see `rpc.rs` for the
-//! simplified design (#1136 rewrite). The wire types are engine-owned
-//! (`tinycortex::memory::sync`).
+//! simplified design (#1136 rewrite).
+//!
+//! The `MemorySyncStatus` this schema names as its output type is
+//! [`super::MemorySyncStatus`] — the host's own wire type. It was the engine's
+//! until #5560; the row now comes from the driver's `sync_statuses` and is
+//! carried across by `rpc::into_wire`, so the schema and the type it advertises
+//! live in the same module.
use serde_json::{Map, Value};
diff --git a/src/openhuman/memory/tool_memory/capture.rs b/src/openhuman/memory/tool_memory/capture.rs
index c71afba387..51dff5d545 100644
--- a/src/openhuman/memory/tool_memory/capture.rs
+++ b/src/openhuman/memory/tool_memory/capture.rs
@@ -26,17 +26,15 @@
//! `tool_effectiveness`.
//!
//! [`ToolTrackerHook`]: crate::openhuman::agent::learning::ToolTrackerHook
-//! [`ToolMemoryStore`]: super::store::ToolMemoryStore
use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
-use super::{tool_memory_store, ToolMemoryStore};
+use super::{tool_memory_store, ToolMemoryPriority, ToolMemorySource, ToolMemoryStore};
use crate::openhuman::agent::hooks::{PostTurnHook, ToolCallRecord, TurnContext};
use crate::openhuman::memory::Memory;
-use tinycortex::memory::tool_memory::{ToolMemoryPriority, ToolMemorySource};
/// Maximum length (chars) of the captured rule body — keeps malformed or
/// runaway input from bloating the namespace.
diff --git a/src/openhuman/memory/tool_memory/mod.rs b/src/openhuman/memory/tool_memory/mod.rs
index 07b529c2a7..4371abe7a0 100644
--- a/src/openhuman/memory/tool_memory/mod.rs
+++ b/src/openhuman/memory/tool_memory/mod.rs
@@ -5,29 +5,37 @@
//! system prompt section — both of which name harness traits (`PostTurnHook`,
//! `PromptContext`) that the engine crate cannot see.
//!
-//! # Why this names `tinycortex` rather than `tinymemory_core` (#5560)
+//! # Where the four names in this module came from (#5560)
//!
//! This module used to be `pub use tinymemory_core::tool_memory::*;`, and that
-//! glob resolved to three different places:
+//! glob resolved to four different places:
//!
-//! | Name | Where it really lives |
-//! | --- | --- |
-//! | `ToolMemoryStore`, `TOOL_MEMORY_PROMPT_CAP` | `tinycortex::memory::tool_memory::store` |
-//! | `tool_memory_namespace`, `ToolMemoryPriority`, `ToolMemoryRule`, `ToolMemorySource` | `tinycortex::memory::tool_memory::types` |
-//! | `tool_memory_store` | a ten-line constructor in `tinymemory-core` |
-//! | `test_helpers` | `tinymemory-core`, behind `cfg(any(test, feature = "test-support"))` |
+//! | Name | Where it used to live | Where it is now |
+//! | --- | --- | --- |
+//! | `ToolMemoryStore`, `TOOL_MEMORY_PROMPT_CAP` | `tinycortex::memory::tool_memory::store` | [`store`], in this directory |
+//! | `tool_memory_namespace`, `ToolMemoryPriority`, `ToolMemoryRule`, `ToolMemorySource` | `tinycortex::memory::tool_memory::types` | `tinymemory_api::tool_memory` — the contract |
+//! | `tool_memory_store` | a ten-line constructor in `tinymemory-core` | [`tool_memory_store`] below |
+//! | `test_helpers` | `tinymemory-core`, behind `cfg(any(test, feature = "test-support"))` | unchanged, and test-only |
//!
-//! The first two rows are named at `tinycortex` directly now. They are the
-//! **same items** either way — `tinymemory_core::tool_memory` re-exported them
-//! out of `crate::engine::backend::tool_memory`, which is itself
-//! `pub use tinycortex::memory::tool_memory` — so this changes no type, only
-//! which crate alias holds it in the build. `tinycortex` stays a direct
-//! dependency of this crate; `tinymemory-core` is the one #5560 removes.
+//! The **second** row is a pure repoint and changes no type. The engine's
+//! `memory::tool_memory::types` is `tinycortex_api::tool_memory`, and
+//! `tinycortex-api` is itself now nothing but `pub use tinymemory_api::{…}` —
+//! so the contract path and the engine path name the *same items*, and the
+//! engine's own `MemoryToolMemory` implementation serialises those very types.
+//! Naming the contract removes an alias, not an indirection.
//!
-//! The third row came home: [`tool_memory_store`] below is the same one-line
-//! `ToolMemoryStore::new` wrapper, and it was only in the engine crate because
-//! that crate used to be this host's memory layer. Nothing in `tinymemory`
-//! named it.
+//! The **first** row came home rather than being repointed, because there was
+//! nothing to repoint it at: the contract has the vocabulary a rule is made of
+//! but not the store that files one. [`store`] says at length why it is a
+//! host-side convention over `Arc<dyn Memory>` rather than a call onto
+//! `MemoryToolMemory` — the short version is that both of its callers are
+//! handed a *subtree-scoped* memory object, and the family reached through the
+//! ambient guard is the shared tree.
+//!
+//! The **third** row came home earlier for the same reason:
+//! [`tool_memory_store`] below is the same one-line `ToolMemoryStore::new`
+//! wrapper, and it was only in the engine crate because that crate used to be
+//! this host's memory layer. Nothing in `tinymemory` named it.
//!
//! The fourth row is **test-only** and stays on the engine crate deliberately:
//! `MockMemory` is a test fixture reached from four inline `#[cfg(test)]`
@@ -46,13 +54,18 @@ use std::sync::Arc;
// `memory::Memory` — same item, one less alias to follow.
use tinymemory_api::traits::Memory;
-pub use tinycortex::memory::tool_memory::{
- store::{ToolMemoryStore, TOOL_MEMORY_PROMPT_CAP},
- types::{tool_memory_namespace, ToolMemoryPriority, ToolMemoryRule, ToolMemorySource},
+// The rule vocabulary, named at the contract. Re-exported rather than merely
+// available so every historical `memory::tool_memory::ToolMemoryRule` path
+// keeps resolving — and resolving to the item that actually crosses the bus.
+pub use tinymemory_api::tool_memory::{
+ tool_memory_namespace, ToolMemoryPriority, ToolMemoryRule, ToolMemorySource,
};
+pub use store::{ToolMemoryStore, TOOL_MEMORY_PROMPT_CAP};
+
pub mod capture;
pub mod prompt;
+pub mod store;
/// Build the rule store over OpenHuman's shared memory object.
///
diff --git a/src/openhuman/memory/tool_memory/prompt.rs b/src/openhuman/memory/tool_memory/prompt.rs
index 0de2585948..228eded0b4 100644
--- a/src/openhuman/memory/tool_memory/prompt.rs
+++ b/src/openhuman/memory/tool_memory/prompt.rs
@@ -1,5 +1,5 @@
//! Prompt section that injects tool-scoped memory rules into the system
-//! prompt — thin host shim over `tinycortex::memory::tool_memory::render` (W7).
+//! prompt (W7).
//!
//! ## Why a prompt section
//!
@@ -10,15 +10,20 @@
//! want to be **compression-resistant** therefore has to live in the system
//! prompt — exactly where Critical and High priority [`ToolMemoryRule`]s belong.
//!
-//! ## What this shim owns
+//! ## What this module owns
//!
-//! The rendering (`render_tool_memory_rules`) and the section type
-//! ([`ToolMemoryRulesSection`], a byte-stable at-construction snapshot) are the
-//! crate's and are re-exported here. Host-retained: the [`PromptSection`] impl
-//! that plugs the crate section into the host system-prompt builder — a host
-//! trait we can implement for the crate type under the orphan rule.
+//! All of it, and the doc above this line used to say otherwise. The rendering
+//! ([`render_tool_memory_rules`]) and the section type
+//! ([`ToolMemoryRulesSection`], a byte-stable at-construction snapshot) were
+//! described as "the crate's, re-exported here" back when they were
+//! `tinycortex::memory::tool_memory::render`; they have been defined below for
+//! some time. What was always host-retained is the [`PromptSection`] impl that
+//! plugs the section into the host system-prompt builder.
//!
-//! [`ToolMemoryRule`]: super::types::ToolMemoryRule
+//! The one contract dependency is the rule vocabulary itself
+//! ([`ToolMemoryRule`], [`ToolMemoryPriority`]), named at
+//! [`memory::api::tool_memory`](crate::openhuman::memory::api::tool_memory)
+//! because these are the types the module serialises across the bus.
use anyhow::Result;
diff --git a/src/openhuman/memory/tool_memory/store.rs b/src/openhuman/memory/tool_memory/store.rs
new file mode 100644
index 0000000000..6fe96818e8
--- /dev/null
+++ b/src/openhuman/memory/tool_memory/store.rs
@@ -0,0 +1,323 @@
+//! [`ToolMemoryStore`] — the rule store, over the contract's storage trait.
+//!
+//! # Why this came home (#5560)
+//!
+//! It was `tinycortex::memory::tool_memory::store::ToolMemoryStore`, and the
+//! host reached it through a `pub use`. What it actually *is* is a naming
+//! convention plus a sort order applied over an
+//! [`Arc<dyn Memory>`](crate::openhuman::memory::Memory) the host already
+//! holds — and every load-bearing piece of that convention is in the contract,
+//! not in the engine:
+//!
+//! | Piece | Where it lives |
+//! | --- | --- |
+//! | namespace (`tool-<name>`) | [`tool_memory_namespace`] |
+//! | key (`rule/<id>`) | [`ToolMemoryRule::storage_key`] |
+//! | id allocation | [`ToolMemoryRule::generate_id`] |
+//! | the record itself | [`ToolMemoryRule`]'s serde |
+//! | "which rules go in the prompt" | [`ToolMemoryPriority::is_eager`] |
+//!
+//! So both ends of the wire already agree on the bytes by construction. The
+//! module's own `MemoryToolMemory` implementation writes the same namespace,
+//! the same key, and the same JSON — it reaches the *engine's* copy of this
+//! file — and neither copy can drift on the parts that decide where a rule
+//! lands, because both read them from the contract.
+//!
+//! ## Why not the `MemoryToolMemory` family instead
+//!
+//! Because of *which store* the two callers must reach. Both
+//! [`capture::ToolMemoryCaptureHook`](super::capture::ToolMemoryCaptureHook)
+//! and the session builder's prompt prefetch are handed a **subtree-scoped**
+//! `Arc<dyn Memory>` — `DriverMemory::for_subtree(config, memory_subdir)`,
+//! resolved per session so a profile with `dedicatedMemory` writes its rules
+//! into `memory-<id>` and not into the shared tree. `active_memory_guard()`
+//! resolves the *ambient* binding, which is the shared tree; routing either
+//! caller onto it would silently merge every dedicated profile's tool rules
+//! into one namespace, which is the isolation `dedicatedMemory` exists to
+//! provide.
+//!
+//! The family reached through the session's own subtree binding
+//! (`binding::for_subtree(..).provider().as_tool_memory()`) would be correct on
+//! that axis, and is the right destination once the hook constructors take a
+//! subtree rather than a memory object. It is not this change: both
+//! constructors are called from the session builder with the `Arc<dyn Memory>`
+//! it already built, and swapping the argument is a harness change rather than
+//! a compile-target one. Note also that the *guarded* family is not a drop-in
+//! here even then — it applies `enforce_write`, so a `readonly` autonomy tier
+//! would start refusing post-turn capture, which is best-effort telemetry and
+//! has never been tier-gated.
+//!
+//! What this file therefore is: the same convention, over the same object, with
+//! nothing from the engine crate in it.
+//!
+//! ## The surface is narrowed to what the host actually calls
+//!
+//! The engine's store also carries `delete_rule` and `list_rules_json`. Neither
+//! is reached from here any more — the `memory_tools_*` RPC and agent tools go
+//! through `MemoryToolMemory` on the guard
+//! (`memory/ops/tool_memory.rs`, `memory/tools/tool_memory/`) — so they are not
+//! reimplemented. A method with no caller is a second definition waiting to
+//! disagree with the first.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use tokio::sync::Mutex;
+
+use crate::openhuman::memory::api::tool_memory::{
+ tool_memory_namespace, ToolMemoryPriority, ToolMemoryRule,
+};
+use crate::openhuman::memory::{Memory, MemoryCategory};
+
+/// How many eager rules the prompt block may carry.
+///
+/// A cap on the **High**-priority remainder only: every `Critical` rule is
+/// retained, so the returned set can exceed this when a tool has more than
+/// thirty critical rules. That asymmetry is the point — a critical rule is a
+/// safety constraint, and dropping one to fit a budget is the failure this
+/// surface exists to prevent.
+pub const TOOL_MEMORY_PROMPT_CAP: usize = 30;
+
+/// Namespace prefix every tool-scoped rule namespace carries.
+///
+/// Only used to *recognise* one in [`ToolMemoryStore::list_tool_names`];
+/// namespaces are always **built** with [`tool_memory_namespace`], never with
+/// this constant, so the trim-and-lowercase rule stays in one place.
+const TOOL_NAMESPACE_PREFIX: &str = "tool-";
+
+/// The tool name a user edict is filed under when no tool ran in the turn.
+///
+/// Excluded from prompt prefetch: such a rule is not permanently associated
+/// with any real tool, so injecting it into an arbitrary session's prompt would
+/// pin guidance against a tool the user never mentioned.
+const UNSCOPED_TOOL: &str = "__unscoped__";
+
+/// Serialises the read-modify-write inside [`ToolMemoryStore::put_rule`].
+///
+/// The engine's store held a process-wide lock here for the same reason: the
+/// `created_at`-preserving upsert is a `get` followed by a `store`, and two
+/// interleaved upserts of the same rule id can otherwise resurrect the older
+/// `created_at`. Process-wide rather than per-store because a `ToolMemoryStore`
+/// is cheap to clone and several live handles routinely front one backend.
+fn rule_mutation_lock() -> &'static Mutex<()> {
+ static LOCK: std::sync::OnceLock<Mutex<()>> = std::sync::OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+}
+
+/// High-level store for tool-scoped memory rules.
+///
+/// All methods operate on a single shared [`Arc<dyn Memory>`] backend. Cheap to
+/// clone — the backend is reference-counted.
+#[derive(Clone)]
+pub struct ToolMemoryStore {
+ memory: Arc<dyn Memory>,
+}
+
+impl ToolMemoryStore {
+ /// Build a new store over the given memory backend.
+ pub fn new(memory: Arc<dyn Memory>) -> Self {
+ Self { memory }
+ }
+
+ /// Upsert a rule and return the stored copy, with `updated_at` refreshed.
+ ///
+ /// A rule with the same `(tool_name, id)` keeps its original `created_at`.
+ /// `tool_name` is sourced from the rule itself rather than from a separate
+ /// argument, so the namespace it is stored under and the name it displays
+ /// as cannot skew; it is trimmed and lower-cased before the write, which is
+ /// the same normalisation [`tool_memory_namespace`] applies, so a read-back
+ /// with the caller's raw name hits the same namespace. Legacy mixed-case
+ /// rows are left alone until something rewrites them.
+ ///
+ /// # Errors
+ ///
+ /// A blank `tool_name` or rule body, a serialisation failure, or any
+ /// backend failure. Reported as `String` rather than as a typed error
+ /// because that is what both callers log — neither branches on the cause.
+ pub async fn put_rule(&self, mut rule: ToolMemoryRule) -> Result<ToolMemoryRule, String> {
+ if rule.tool_name.trim().is_empty() {
+ return Err("tool_name is required".to_string());
+ }
+ if rule.rule.trim().is_empty() {
+ return Err("rule body is required".to_string());
+ }
+ if rule.id.trim().is_empty() {
+ rule.id = ToolMemoryRule::generate_id();
+ }
+ rule.tool_name = rule.tool_name.trim().to_lowercase();
+
+ let _guard = rule_mutation_lock().lock().await;
+
+ let namespace = tool_memory_namespace(&rule.tool_name);
+ let key = ToolMemoryRule::storage_key(&rule.id);
+
+ if let Some(existing) = self.fetch_rule(&namespace, &key).await? {
+ rule.created_at = existing.created_at;
+ }
+ rule.updated_at = chrono::Utc::now().to_rfc3339();
+
+ let content = serde_json::to_string(&rule).map_err(|e| e.to_string())?;
+ self.memory
+ .store(
+ &namespace,
+ &key,
+ &content,
+ MemoryCategory::Custom("tool_memory".into()),
+ None,
+ )
+ .await
+ .map_err(|e| format!("store tool rule: {e:#}"))?;
+ Ok(rule)
+ }
+
+ /// Build a rule from caller-supplied fields and persist it.
+ ///
+ /// The id is minted by [`ToolMemoryRule::new`], so this is always an
+ /// insert — the `created_at` preservation in [`Self::put_rule`] is
+ /// unreachable from here.
+ ///
+ /// # Errors
+ ///
+ /// As [`Self::put_rule`].
+ pub async fn record(
+ &self,
+ tool_name: &str,
+ rule_body: &str,
+ priority: ToolMemoryPriority,
+ source: crate::openhuman::memory::api::tool_memory::ToolMemorySource,
+ tags: Vec<String>,
+ ) -> Result<ToolMemoryRule, String> {
+ let mut rule = ToolMemoryRule::new(tool_name, rule_body, priority, source);
+ rule.tags = tags;
+ self.put_rule(rule).await
+ }
+
+ /// Every rule for one tool, highest priority first and freshest first
+ /// within a priority.
+ ///
+ /// A row that will not deserialise is skipped rather than failing the list:
+ /// one corrupt entry must not hide every other rule for that tool from the
+ /// prompt, and there is nothing a caller could do with the error but log it.
+ ///
+ /// # Errors
+ ///
+ /// Backend failures only; a tool with no rules yields an empty vector.
+ pub async fn list_rules(&self, tool_name: &str) -> Result<Vec<ToolMemoryRule>, String> {
+ let namespace = tool_memory_namespace(tool_name);
+ let entries = self
+ .memory
+ .list(Some(&namespace), None, None)
+ .await
+ .map_err(|e| format!("list tool rules: {e:#}"))?;
+
+ let mut rules: Vec<ToolMemoryRule> = entries
+ .into_iter()
+ .filter(|entry| entry.key.starts_with("rule/"))
+ .filter_map(|entry| serde_json::from_str::<ToolMemoryRule>(&entry.content).ok())
+ .collect();
+
+ rules.sort_by(|a, b| {
+ b.priority
+ .cmp(&a.priority)
+ .then_with(|| b.updated_at.cmp(&a.updated_at))
+ });
+
+ Ok(rules)
+ }
+
+ /// The rules that must be surfaced eagerly (Critical + High), grouped by
+ /// tool name.
+ ///
+ /// `tools` constrains which tool namespaces to inspect; an empty slice
+ /// scans every known tool namespace via [`Self::list_tool_names`].
+ ///
+ /// Every `Critical` rule is retained and [`TOOL_MEMORY_PROMPT_CAP`] limits
+ /// only the `High` remainder, so the result can exceed the cap.
+ ///
+ /// # Errors
+ ///
+ /// Backend failures only.
+ pub async fn rules_for_prompt(
+ &self,
+ tools: &[String],
+ ) -> Result<HashMap<String, Vec<ToolMemoryRule>>, String> {
+ let tool_names = if tools.is_empty() {
+ self.list_tool_names().await?
+ } else {
+ tools
+ .iter()
+ .map(|name| name.trim().to_string())
+ .filter(|name| !name.is_empty())
+ .collect()
+ };
+
+ let mut collected: Vec<ToolMemoryRule> = Vec::new();
+ for tool in &tool_names {
+ let rules = self.list_rules(tool).await?;
+ collected.extend(rules.into_iter().filter(|r| r.priority.is_eager()));
+ }
+
+ // Critical first, then High; within a priority, freshest first.
+ collected.sort_by(|a, b| {
+ b.priority
+ .cmp(&a.priority)
+ .then_with(|| b.updated_at.cmp(&a.updated_at))
+ });
+ let critical_count = collected
+ .iter()
+ .take_while(|rule| rule.priority == ToolMemoryPriority::Critical)
+ .count();
+ collected.truncate(TOOL_MEMORY_PROMPT_CAP.max(critical_count));
+
+ let mut out: HashMap<String, Vec<ToolMemoryRule>> = HashMap::new();
+ for rule in collected {
+ out.entry(rule.tool_name.clone()).or_default().push(rule);
+ }
+ Ok(out)
+ }
+
+ /// Every tool that has at least one stored rule.
+ ///
+ /// # Errors
+ ///
+ /// Backend failures only.
+ pub async fn list_tool_names(&self) -> Result<Vec<String>, String> {
+ let summaries = self
+ .memory
+ .namespace_summaries()
+ .await
+ .map_err(|e| format!("list tool namespaces: {e:#}"))?;
+ let mut out = Vec::new();
+ for summary in summaries {
+ if let Some(tool) = summary.namespace.strip_prefix(TOOL_NAMESPACE_PREFIX) {
+ if !tool.is_empty() && tool != UNSCOPED_TOOL {
+ out.push(tool.to_string());
+ }
+ }
+ }
+ out.sort();
+ out.dedup();
+ Ok(out)
+ }
+
+ /// One rule by `(namespace, key)`, or `None`.
+ ///
+ /// A malformed row reads as absent so a corrupt entry cannot block the
+ /// upsert that would replace it.
+ async fn fetch_rule(
+ &self,
+ namespace: &str,
+ key: &str,
+ ) -> Result<Option<ToolMemoryRule>, String> {
+ let entry = self
+ .memory
+ .get(namespace, key)
+ .await
+ .map_err(|e| format!("get tool rule: {e:#}"))?;
+ Ok(entry.and_then(|entry| serde_json::from_str::<ToolMemoryRule>(&entry.content).ok()))
+ }
+}
+
+#[cfg(test)]
+#[path = "store_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/tool_memory/store_tests.rs b/src/openhuman/memory/tool_memory/store_tests.rs
new file mode 100644
index 0000000000..bbeaf7fe8a
--- /dev/null
+++ b/src/openhuman/memory/tool_memory/store_tests.rs
@@ -0,0 +1,297 @@
+//! Unit tests for the host-side rule store.
+//!
+//! These pin the parts that decide **where a rule lands** and **which rules
+//! reach the prompt** — the namespace, the key, the priority ordering, and the
+//! Critical-survives-the-cap rule. That is deliberately the set a divergence
+//! from the module's own writer would show up in first: both sides build the
+//! namespace and key from the contract, so a test that asserts the bytes here
+//! is asserting the shared convention rather than a local restatement of it.
+
+use super::*;
+use crate::openhuman::memory::api::tool_memory::ToolMemorySource;
+use crate::openhuman::memory::tool_memory::test_helpers::MockMemory;
+
+fn store() -> ToolMemoryStore {
+ let memory: Arc<dyn Memory> = Arc::new(MockMemory::default());
+ ToolMemoryStore::new(memory)
+}
+
+#[tokio::test]
+async fn record_lands_in_the_tool_scoped_namespace_under_a_rule_key() {
+ let memory: Arc<dyn Memory> = Arc::new(MockMemory::default());
+ let store = ToolMemoryStore::new(memory.clone());
+
+ let stored = store
+ .record(
+ " Send_Email ",
+ "never email Sarah",
+ ToolMemoryPriority::Critical,
+ ToolMemorySource::UserExplicit,
+ vec!["user-edict".to_string()],
+ )
+ .await
+ .unwrap();
+
+ // The write normalises the tool name, so namespace and display identity
+ // cannot skew.
+ assert_eq!(stored.tool_name, "send_email");
+
+ let entries = memory.list(Some("tool-send_email"), None, None).await.unwrap();
+ assert_eq!(entries.len(), 1, "one rule, in the tool-scoped namespace");
+ assert_eq!(entries[0].key, format!("rule/{}", stored.id));
+
+ // And a read-back with the caller's *raw* name still resolves.
+ let rules = store.list_rules(" Send_Email ").await.unwrap();
+ assert_eq!(rules.len(), 1);
+ assert_eq!(rules[0].rule, "never email Sarah");
+}
+
+#[tokio::test]
+async fn put_rule_preserves_created_at_on_upsert_and_refreshes_updated_at() {
+ let store = store();
+ let first = store
+ .record(
+ "shell",
+ "prefer rg over grep",
+ ToolMemoryPriority::Normal,
+ ToolMemorySource::PostTurn,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ let mut amended = first.clone();
+ amended.rule = "prefer rg over grep, always".to_string();
+ amended.created_at = "1999-01-01T00:00:00+00:00".to_string();
+ let second = store.put_rule(amended).await.unwrap();
+
+ assert_eq!(
+ second.created_at, first.created_at,
+ "an upsert keeps the original creation time, not the caller's claim"
+ );
+ assert!(second.updated_at >= first.updated_at);
+ assert_eq!(
+ store.list_rules("shell").await.unwrap().len(),
+ 1,
+ "same id upserts rather than appending"
+ );
+}
+
+#[tokio::test]
+async fn put_rule_rejects_a_blank_tool_name_or_body() {
+ let store = store();
+ let mut blank_tool = ToolMemoryRule::new(
+ " ",
+ "something",
+ ToolMemoryPriority::Normal,
+ ToolMemorySource::Programmatic,
+ );
+ blank_tool.tool_name = " ".to_string();
+ assert!(store.put_rule(blank_tool).await.is_err());
+
+ let blank_body = ToolMemoryRule::new(
+ "shell",
+ " ",
+ ToolMemoryPriority::Normal,
+ ToolMemorySource::Programmatic,
+ );
+ assert!(store.put_rule(blank_body).await.is_err());
+}
+
+#[tokio::test]
+async fn list_rules_orders_by_priority_then_freshness() {
+ let store = store();
+ for (body, priority) in [
+ ("normal one", ToolMemoryPriority::Normal),
+ ("critical one", ToolMemoryPriority::Critical),
+ ("high one", ToolMemoryPriority::High),
+ ] {
+ store
+ .record(
+ "shell",
+ body,
+ priority,
+ ToolMemorySource::Programmatic,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ }
+
+ let rules = store.list_rules("shell").await.unwrap();
+ let priorities: Vec<_> = rules.iter().map(|r| r.priority).collect();
+ assert_eq!(
+ priorities,
+ vec![
+ ToolMemoryPriority::Critical,
+ ToolMemoryPriority::High,
+ ToolMemoryPriority::Normal,
+ ]
+ );
+}
+
+#[tokio::test]
+async fn rules_for_prompt_keeps_only_eager_rules() {
+ let store = store();
+ store
+ .record(
+ "shell",
+ "normal guidance",
+ ToolMemoryPriority::Normal,
+ ToolMemorySource::PostTurn,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ store
+ .record(
+ "shell",
+ "critical constraint",
+ ToolMemoryPriority::Critical,
+ ToolMemorySource::UserExplicit,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ let grouped = store
+ .rules_for_prompt(&["shell".to_string()])
+ .await
+ .unwrap();
+ let rules = grouped.get("shell").expect("shell has eager rules");
+ assert_eq!(rules.len(), 1, "Normal rules are not eagerly surfaced");
+ assert_eq!(rules[0].rule, "critical constraint");
+}
+
+/// The cap bounds the High remainder; it never drops a safety constraint.
+#[tokio::test]
+async fn rules_for_prompt_never_drops_a_critical_rule_to_fit_the_cap() {
+ let store = store();
+ let critical_count = TOOL_MEMORY_PROMPT_CAP + 5;
+ for i in 0..critical_count {
+ store
+ .record(
+ "shell",
+ &format!("critical {i}"),
+ ToolMemoryPriority::Critical,
+ ToolMemorySource::UserExplicit,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ }
+ store
+ .record(
+ "shell",
+ "high one",
+ ToolMemoryPriority::High,
+ ToolMemorySource::PostTurn,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ let grouped = store
+ .rules_for_prompt(&["shell".to_string()])
+ .await
+ .unwrap();
+ let rules = grouped.get("shell").expect("shell has eager rules");
+ assert_eq!(
+ rules.len(),
+ critical_count,
+ "every Critical survives; the High remainder is what the cap trims"
+ );
+ assert!(rules.iter().all(|r| r.priority == ToolMemoryPriority::Critical));
+}
+
+#[tokio::test]
+async fn list_tool_names_skips_the_unscoped_sentinel_and_non_tool_namespaces() {
+ let memory: Arc<dyn Memory> = Arc::new(MockMemory::default());
+ let store = ToolMemoryStore::new(memory.clone());
+
+ store
+ .record(
+ "shell",
+ "a",
+ ToolMemoryPriority::Normal,
+ ToolMemorySource::Programmatic,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ store
+ .record(
+ UNSCOPED_TOOL,
+ "an edict captured with no tool call",
+ ToolMemoryPriority::Critical,
+ ToolMemorySource::UserExplicit,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ memory
+ .store(
+ "global",
+ "unrelated",
+ "not a rule",
+ MemoryCategory::Custom("other".into()),
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(store.list_tool_names().await.unwrap(), vec!["shell"]);
+}
+
+/// An unscoped edict is still *stored* — it is only withheld from the prompt
+/// prefetch, so the agent can refile it later.
+#[tokio::test]
+async fn the_unscoped_sentinel_is_withheld_from_prefetch_but_still_readable() {
+ let store = store();
+ store
+ .record(
+ UNSCOPED_TOOL,
+ "never do that",
+ ToolMemoryPriority::Critical,
+ ToolMemorySource::UserExplicit,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(store.list_rules(UNSCOPED_TOOL).await.unwrap().len(), 1);
+ assert!(
+ store.rules_for_prompt(&[]).await.unwrap().is_empty(),
+ "a whole-store prefetch must not pin an unscoped edict against every tool"
+ );
+}
+
+#[tokio::test]
+async fn list_rules_skips_a_corrupt_row_rather_than_failing() {
+ let memory: Arc<dyn Memory> = Arc::new(MockMemory::default());
+ let store = ToolMemoryStore::new(memory.clone());
+ store
+ .record(
+ "shell",
+ "good rule",
+ ToolMemoryPriority::Normal,
+ ToolMemorySource::Programmatic,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ memory
+ .store(
+ "tool-shell",
+ "rule/corrupt",
+ "{not json",
+ MemoryCategory::Custom("tool_memory".into()),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let rules = store.list_rules("shell").await.unwrap();
+ assert_eq!(rules.len(), 1);
+ assert_eq!(rules[0].rule, "good rule");
+}
diff --git a/src/openhuman/memory/tools/goals.rs b/src/openhuman/memory/tools/goals.rs
index a5e138a5ad..d022971eac 100644
--- a/src/openhuman/memory/tools/goals.rs
+++ b/src/openhuman/memory/tools/goals.rs
@@ -2,17 +2,55 @@
//!
//! These are the tools the background `goals_agent` (and, when allowed, the
//! main agent) uses to read and mutate the goals list over multiple turns.
-//! They are thin wrappers around [`super::store`] — all cap enforcement and
-//! persistence live there. Each tool is sandboxed to a single `workspace_dir`
-//! captured at construction time.
+//!
+//! # They are wrappers around [`goals::ops`], not around a store (#5560)
+//!
+//! Each tool used to call `tinycortex::memory::goals::store` against a
+//! `workspace_dir` captured at construction. Both halves of that changed:
+//!
+//! - The **store** is behind the loaded module now, reached through the goals
+//! family on the guarded driver.
+//! - The **validation** — the secret/PII and single-line guards — is host
+//! policy that the family deliberately does not carry, and it lives in
+//! [`goals::doc`](crate::openhuman::memory::goals::doc).
+//!
+//! Routing through [`goals::ops`](crate::openhuman::memory::goals::ops) is what
+//! keeps those two facts in one place. When these tools called the store
+//! directly they duplicated the RPC surface's sequence, so the tool path and
+//! the `memory_goals.*` path were two implementations of one operation; now
+//! they are the same one, and a goal added by the agent is validated,
+//! capped and reported exactly as a goal added over RPC.
+//!
+//! The constructors still take a `workspace_dir` and it is still what
+//! `tools::ops` passes: it is the sandbox identity these tools were built with,
+//! and dropping it would change four public signatures in the agent's tool
+//! registry for no behavioural gain. It is unused for storage — the goals
+//! document is workspace-wide on the driver's side too, so the tool and the
+//! ambient binding name the same file.
use std::path::PathBuf;
use async_trait::async_trait;
use serde_json::json;
+use crate::openhuman::memory::goals::ops;
+use crate::openhuman::memory::guard::MemoryGuard;
+use crate::openhuman::memory::ops::guard::active_memory_guard;
+use crate::openhuman::memory::api::provider::MemoryProvider;
use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};
-use tinycortex::memory::goals::store;
+
+/// The guarded driver for this call, checked to serve the goals family.
+///
+/// Returned as the guard because the family accessor borrows from it. The
+/// error text is what the agent reads back as a tool failure, so it names the
+/// missing capability rather than an internal path.
+async fn goals_guard() -> Result<std::sync::Arc<MemoryGuard>, String> {
+ let guard = active_memory_guard().await?;
+ if guard.as_goals().is_none() {
+ return Err("memory driver does not support the goals family".to_string());
+ }
+ Ok(guard)
+}
/// `goals_list` — read the current long-term goals list.
pub struct GoalsListTool {
@@ -47,11 +85,17 @@ impl Tool for GoalsListTool {
async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
log::debug!("[memory_goals] tool=goals_list");
- let doc = match store::load(&self.workspace_dir).map_err(|e| e.to_string()) {
- Ok(doc) => doc,
+ let guard = match goals_guard().await {
+ Ok(guard) => guard,
Err(e) => return Ok(ToolResult::error(e)),
};
- Ok(ToolResult::success(doc.render()))
+ let goals = guard.as_goals().expect("checked in goals_guard");
+ match ops::list(goals).await {
+ // `render()` is the contract type's own markdown, so the bytes the
+ // agent reads are unchanged.
+ Ok(outcome) => Ok(ToolResult::success(outcome.value.render())),
+ Err(e) => Ok(ToolResult::error(e)),
+ }
}
}
@@ -96,8 +140,16 @@ impl Tool for GoalsAddTool {
return Ok(ToolResult::error("Missing 'text' parameter"));
};
log::debug!("[memory_goals] tool=goals_add");
- match store::add(&self.workspace_dir, text).map_err(|e| e.to_string()) {
- Ok((id, _)) => Ok(ToolResult::success(format!("Added goal '{id}'."))),
+ let guard = match goals_guard().await {
+ Ok(guard) => guard,
+ Err(e) => return Ok(ToolResult::error(e)),
+ };
+ let goals = guard.as_goals().expect("checked in goals_guard");
+ match ops::add(goals, text).await {
+ Ok(outcome) => Ok(ToolResult::success(format!(
+ "Added goal '{}'.",
+ outcome.value.id
+ ))),
Err(e) => Ok(ToolResult::error(e)),
}
}
@@ -148,7 +200,12 @@ impl Tool for GoalsEditTool {
return Ok(ToolResult::error("Missing 'text' parameter"));
};
log::debug!("[memory_goals] tool=goals_edit id={id}");
- match store::edit(&self.workspace_dir, id, text).map_err(|e| e.to_string()) {
+ let guard = match goals_guard().await {
+ Ok(guard) => guard,
+ Err(e) => return Ok(ToolResult::error(e)),
+ };
+ let goals = guard.as_goals().expect("checked in goals_guard");
+ match ops::edit(goals, id, text).await {
Ok(_) => Ok(ToolResult::success(format!("Edited goal '{id}'."))),
Err(e) => Ok(ToolResult::error(e)),
}
@@ -196,7 +253,12 @@ impl Tool for GoalsDeleteTool {
return Ok(ToolResult::error("Missing 'id' parameter"));
};
log::debug!("[memory_goals] tool=goals_delete id={id}");
- match store::delete(&self.workspace_dir, id).map_err(|e| e.to_string()) {
+ let guard = match goals_guard().await {
+ Ok(guard) => guard,
+ Err(e) => return Ok(ToolResult::error(e)),
+ };
+ let goals = guard.as_goals().expect("checked in goals_guard");
+ match ops::delete(goals, id).await {
Ok(_) => Ok(ToolResult::success(format!("Deleted goal '{id}'."))),
Err(e) => Ok(ToolResult::error(e)),
}
diff --git a/src/openhuman/memory/tools/goals_tests.rs b/src/openhuman/memory/tools/goals_tests.rs
index 03399afe05..d1d03dc792 100644
--- a/src/openhuman/memory/tools/goals_tests.rs
+++ b/src/openhuman/memory/tools/goals_tests.rs
@@ -1,14 +1,64 @@
+//! Tests for the four agent-facing goals tools.
+//!
+//! These used to sandbox each tool with its own `tempfile::tempdir()`, because
+//! the tool held the workspace path and opened `MEMORY_GOALS.md` under it. The
+//! store is behind the loaded module now and the document is reached through
+//! the ambient binding, so isolation moves to where the binding reads it from:
+//! `OPENHUMAN_WORKSPACE`, pinned for the test and restored after — the same
+//! `isolated_config` shape `tools/tool_memory/put_tests.rs` uses for the same
+//! reason. `GLOBAL_MEMORY_TEST_LOCK` serialises them, since the workspace env
+//! var is process-wide.
+
use super::*;
+use std::ffi::OsString;
+
+use tempfile::TempDir;
+
+use crate::openhuman::config::TEST_ENV_LOCK;
+use crate::openhuman::tools::traits::Tool;
+
+struct WorkspaceEnvGuard {
+ _lock: std::sync::MutexGuard<'static, ()>,
+ previous: Option<OsString>,
+}
+
+impl WorkspaceEnvGuard {
+ fn set(path: &std::path::Path) -> Self {
+ let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());
+ let previous = std::env::var_os("OPENHUMAN_WORKSPACE");
+ std::env::set_var("OPENHUMAN_WORKSPACE", path);
+ Self {
+ _lock: lock,
+ previous,
+ }
+ }
+}
+
+impl Drop for WorkspaceEnvGuard {
+ fn drop(&mut self) {
+ if let Some(previous) = self.previous.as_ref() {
+ std::env::set_var("OPENHUMAN_WORKSPACE", previous);
+ } else {
+ std::env::remove_var("OPENHUMAN_WORKSPACE");
+ }
+ }
+}
+
#[tokio::test]
async fn add_then_list_reflects_change() {
- let tmp = tempfile::tempdir().unwrap();
+ let _serial = crate::openhuman::memory::ops::GLOBAL_MEMORY_TEST_LOCK
+ .lock()
+ .await;
+ let tmp = TempDir::new().expect("tempdir");
+ let _workspace = WorkspaceEnvGuard::set(tmp.path());
+
let add = GoalsAddTool::new(tmp.path().to_path_buf());
let res = add
.execute(json!({ "text": "help ship the app" }))
.await
.unwrap();
- assert!(!res.is_error);
+ assert!(!res.is_error, "add failed: {}", res.text());
let list = GoalsListTool::new(tmp.path().to_path_buf());
let res = list.execute(json!({})).await.unwrap();
@@ -17,7 +67,12 @@ async fn add_then_list_reflects_change() {
#[tokio::test]
async fn edit_and_delete_unknown_id_error() {
- let tmp = tempfile::tempdir().unwrap();
+ let _serial = crate::openhuman::memory::ops::GLOBAL_MEMORY_TEST_LOCK
+ .lock()
+ .await;
+ let tmp = TempDir::new().expect("tempdir");
+ let _workspace = WorkspaceEnvGuard::set(tmp.path());
+
let edit = GoalsEditTool::new(tmp.path().to_path_buf());
let res = edit
.execute(json!({ "id": "g9", "text": "x" }))
@@ -29,3 +84,55 @@ async fn edit_and_delete_unknown_id_error() {
let res = del.execute(json!({ "id": "g9" })).await.unwrap();
assert!(res.is_error);
}
+
+/// The host-side guards reach the agent through the tool result, not only
+/// through the RPC surface — the `goals_agent` is the main caller and this is
+/// the text it retries against.
+#[tokio::test]
+async fn add_refuses_pii_bearing_text_with_the_specific_reason() {
+ let _serial = crate::openhuman::memory::ops::GLOBAL_MEMORY_TEST_LOCK
+ .lock()
+ .await;
+ let tmp = TempDir::new().expect("tempdir");
+ let _workspace = WorkspaceEnvGuard::set(tmp.path());
+
+ let add = GoalsAddTool::new(tmp.path().to_path_buf());
+ let res = add
+ .execute(json!({ "text": "follow up with [email protected]" }))
+ .await
+ .unwrap();
+ assert!(res.is_error);
+ assert!(
+ res.text().contains("secrets or PII"),
+ "unexpected refusal text: {}",
+ res.text()
+ );
+}
+
+/// Argument validation is the tool's own and runs before anything is resolved,
+/// so it holds whatever the driver is.
+#[tokio::test]
+async fn missing_arguments_are_reported_as_tool_errors() {
+ let dir = std::env::temp_dir();
+ assert!(
+ GoalsAddTool::new(dir.clone())
+ .execute(json!({}))
+ .await
+ .unwrap()
+ .is_error
+ );
+ assert!(
+ GoalsEditTool::new(dir.clone())
+ .execute(json!({ "id": "g1" }))
+ .await
+ .unwrap()
+ .is_error
+ );
+ assert!(
+ GoalsDeleteTool::new(dir)
+ .execute(json!({}))
+ .await
+ .unwrap()
+ .is_error
+ );
+}
diff --git a/src/openhuman/memory/tools/search/hybrid_search.rs b/src/openhuman/memory/tools/search/hybrid_search.rs
index 02e5a06d10..cadca4f4ce 100644
--- a/src/openhuman/memory/tools/search/hybrid_search.rs
+++ b/src/openhuman/memory/tools/search/hybrid_search.rs
@@ -13,10 +13,118 @@ use crate::openhuman::memory::api::provider::MemoryProvider;
use crate::openhuman::memory::api::types::MemoryItemKind;
use crate::openhuman::memory::ops::guard::active_memory_guard;
use crate::openhuman::tools::traits::{Tool, ToolResult};
-use tinycortex::memory::WeightProfile;
pub struct MemoryHybridSearchTool;
+// ── Weight profiles and the re-ranking sum, brought home (#5560) ─────────────
+//
+// `WeightProfile` was `tinycortex::memory::WeightProfile` and the fold below
+// was `tinycortex::memory::retrieval::scoring::hybrid_score`. Both are ported
+// here rather than routed at the module contract, for the same reason the
+// vector tool's cosine is: they are pure arithmetic over four numbers the
+// driver has *already sent*. `MemoryRetrieval::recall_namespace_scored`
+// answers with each hit's `score_breakdown`, so the four raw signals are in
+// hand; re-weighting them is this tool's ranking policy and needs no bus at
+// all.
+//
+// This is the same split the engine already drew. Its own `scoring` module docs
+// say the profiles "live in `memory::config` and are read from config — never
+// hardcoded here", i.e. the weights were always the *caller's* input to a
+// function that only multiplied and added. The `mode` argument on this tool is
+// where that input comes from, so the table belongs beside it.
+
+/// Named hybrid-retrieval weight profiles (graph / vector / keyword /
+/// freshness), resolved from this tool's `mode` argument.
+///
+/// The final ranking score is the plain weighted sum
+/// `graph·graph_relevance + vector·vector_similarity + keyword·keyword_relevance
+/// + freshness·freshness`. Nothing here *enforces* that the four weights sum to
+/// `1.0` — the four built-ins are chosen that way by convention so scores land
+/// in a familiar `[0.0, 1.0]`-ish range when every signal is itself in
+/// `[0.0, 1.0]`. The constants are the engine's, value for value, so a query
+/// ranks exactly as it did before.
+#[derive(Debug, Clone, Copy, PartialEq)]
+struct WeightProfile {
+ /// Weight on graph/co-occurrence proximity signal.
+ graph: f64,
+ /// Weight on dense vector (cosine) similarity signal.
+ vector: f64,
+ /// Weight on lexical/keyword match signal.
+ keyword: f64,
+ /// Weight on recency; `0.0` disables freshness boosting.
+ freshness: f64,
+}
+
+impl WeightProfile {
+ /// `balanced`: graph 0.35, vector 0.35, keyword 0.15, freshness 0.15.
+ const BALANCED: Self = Self {
+ graph: 0.35,
+ vector: 0.35,
+ keyword: 0.15,
+ freshness: 0.15,
+ };
+ /// `semantic`: graph 0.15, vector 0.65, keyword 0.20.
+ const SEMANTIC: Self = Self {
+ graph: 0.15,
+ vector: 0.65,
+ keyword: 0.20,
+ freshness: 0.0,
+ };
+ /// `lexical`: graph 0.25, vector 0.15, keyword 0.60.
+ const LEXICAL: Self = Self {
+ graph: 0.25,
+ vector: 0.15,
+ keyword: 0.60,
+ freshness: 0.0,
+ };
+ /// `graph_first`: graph 0.55, vector 0.30, keyword 0.15.
+ const GRAPH_FIRST: Self = Self {
+ graph: 0.55,
+ vector: 0.30,
+ keyword: 0.15,
+ freshness: 0.0,
+ };
+
+ /// Resolve a profile by its wire name, returning `None` for unknown names.
+ ///
+ /// The names are the `mode` enum in [`MemoryHybridSearchTool`]'s parameter
+ /// schema and are therefore a published surface — a rename here is a
+ /// breaking change to what the model may ask for, not a refactor.
+ fn by_name(name: &str) -> Option<Self> {
+ match name {
+ "balanced" => Some(Self::BALANCED),
+ "semantic" => Some(Self::SEMANTIC),
+ "lexical" => Some(Self::LEXICAL),
+ "graph_first" => Some(Self::GRAPH_FIRST),
+ _ => None,
+ }
+ }
+}
+
+/// Fold four raw signals into one ranking score under `profile`.
+///
+/// Each signal is expected in `[0.0, 1.0]`; the result is the weighted sum
+/// `graph·g + vector·v + keyword·k + freshness·f`.
+///
+/// The engine's `hybrid_score` returned a whole `RetrievalScoreBreakdown` and
+/// this call site read `.final_score` off it and dropped the rest — the other
+/// five fields were the caller's own inputs echoed back, plus a hardcoded
+/// `episodic_relevance: 0.0` carried for wire compatibility with a payload
+/// nothing here serialises. So this returns the number instead of rebuilding a
+/// breakdown to immediately discard; the arithmetic is unchanged.
+fn hybrid_final_score(
+ profile: &WeightProfile,
+ graph_relevance: f64,
+ vector_similarity: f64,
+ keyword_relevance: f64,
+ freshness: f64,
+) -> f64 {
+ profile.graph * graph_relevance
+ + profile.vector * vector_similarity
+ + profile.keyword * keyword_relevance
+ + profile.freshness * freshness
+}
+
#[derive(Debug, Deserialize)]
struct Args {
query: String,
@@ -173,14 +281,13 @@ impl Tool for MemoryHybridSearchTool {
.enumerate()
.map(|(i, hit)| {
let bd = &hit.score_breakdown;
- let score = tinycortex::memory::retrieval::scoring::hybrid_score(
+ let score = hybrid_final_score(
&profile,
bd.graph_relevance,
bd.vector_similarity,
bd.keyword_relevance,
bd.freshness,
- )
- .final_score;
+ );
(i, score)
})
.filter(|(_, score)| *score > 0.0)
diff --git a/src/openhuman/memory/tools/search/vector_search.rs b/src/openhuman/memory/tools/search/vector_search.rs
index 23770074b5..fe322557e5 100644
--- a/src/openhuman/memory/tools/search/vector_search.rs
+++ b/src/openhuman/memory/tools/search/vector_search.rs
@@ -16,11 +16,172 @@ use crate::openhuman::memory::api::provider::ChunkQuery;
use crate::openhuman::memory::api::provider::MemoryProvider;
use crate::openhuman::memory::ops::guard::active_memory_guard;
use crate::openhuman::tools::traits::{Tool, ToolResult};
-use tinycortex::memory::retrieval::mmr::{mmr_select, MmrCandidate};
-use tinycortex::memory::store::vectors::cosine_similarity;
pub struct MemoryVectorSearchTool;
+// ── Ranking maths, brought home from the engine crate (#5560) ────────────────
+//
+// `cosine_similarity` and the MMR selector below were reached at
+// `tinycortex::memory::{store::vectors, retrieval::mmr}`. They are ported here
+// verbatim rather than routed at the module contract because there is nothing
+// on the contract to route them *at*, and nothing that would benefit if there
+// were: both are pure arithmetic over `&[f32]` slices this host already holds
+// in memory. The chunks and their embeddings come back over the bus
+// (`MemoryChunks::list_chunks` + `chunk_embeddings`); what happens to the
+// numbers afterwards is this tool's ranking policy, and shipping vectors back
+// across a bus boundary to have someone else multiply them would be a round
+// trip bought for nothing.
+//
+// That is also why they are private to this file rather than a shared module:
+// this tool is the only caller in the host. `archivist::boundary` keeps its own
+// `f32` cosine for its own threshold — see the divergence note on
+// [`cosine_similarity`], which is the reason those two are deliberately not
+// unified.
+
+/// Cosine similarity between two vectors, in `[-1.0, 1.0]`.
+///
+/// Returns `0.0` for mismatched lengths, empty vectors, or a zero-magnitude
+/// vector on either side. Accumulates in `f64` regardless of the `f32` inputs,
+/// so a long vector does not lose precision in the dot product.
+///
+/// # The `[0.0, 1.0]` clamp this does *not* do
+///
+/// The engine's `retrieval::mmr` module docs claim this function "clamps its
+/// result to `[0.0, 1.0]`", which would make an anti-correlated candidate
+/// indistinguishable from an orthogonal one inside [`mmr_select`]. **That
+/// comment is stale**: the code clamps to `[-1.0, 1.0]` — the mathematical
+/// range — and only to absorb floating-point drift. The port follows the code,
+/// so a negatively-correlated candidate keeps its sign and is treated by MMR as
+/// *more* diverse than an orthogonal one, which is the behaviour this tool has
+/// actually had. Do not "restore" the clamp the stale comment describes.
+///
+/// Distinct from `archivist::boundary`'s private `cosine_similarity`, which is
+/// `f32`-valued and unclamped; that one feeds a segment-boundary threshold, not
+/// a ranking, and the two are independent on purpose.
+fn cosine_similarity(a: &[f32], b: &[f32]) -> f64 {
+ if a.len() != b.len() || a.is_empty() {
+ return 0.0;
+ }
+ let mut dot = 0.0_f64;
+ let mut norm_a = 0.0_f64;
+ let mut norm_b = 0.0_f64;
+ for (x, y) in a.iter().zip(b.iter()) {
+ let x = f64::from(*x);
+ let y = f64::from(*y);
+ dot += x * y;
+ norm_a += x * x;
+ norm_b += y * y;
+ }
+ let denom = norm_a.sqrt() * norm_b.sqrt();
+ if denom <= f64::EPSILON {
+ return 0.0;
+ }
+ (dot / denom).clamp(-1.0, 1.0)
+}
+
+/// A candidate for MMR selection.
+struct MmrCandidate<'a> {
+ /// Caller-side index, echoed back on the result so the candidate can be
+ /// resolved to its original record.
+ index: usize,
+ /// Candidate embedding; must share dimensionality with every other
+ /// candidate, since cosine similarity is computed pairwise.
+ embedding: &'a [f32],
+ /// Precomputed relevance of this candidate to the query (here, its cosine
+ /// score). Higher is more relevant; weighted by `lambda` in the MMR
+ /// formula.
+ relevance: f64,
+}
+
+/// Result of MMR selection: the original index and its MMR score.
+struct MmrResult {
+ /// Caller-side index echoed from the chosen [`MmrCandidate::index`], used
+ /// to resolve the result back to its original record.
+ index: usize,
+ /// The MMR score at the step this item was selected:
+ /// `lambda · relevance − (1 − lambda) · max_similarity(c, selected)`.
+ /// Not comparable across runs with different `lambda`.
+ ///
+ /// Unread by this tool — the output reports each hit's *cosine* score, not
+ /// its MMR score, because the latter depends on selection order and would
+ /// read as an unstable percentage. Kept so the port stays a faithful copy
+ /// of the engine's shape rather than a narrowed re-derivation.
+ #[allow(dead_code, reason = "faithful port; this tool reports the cosine score instead")]
+ score: f64,
+}
+
+/// Select up to `limit` items from `candidates` using Maximal Marginal
+/// Relevance, balancing relevance against redundancy within the selected set.
+///
+/// `lambda` controls the relevance-diversity tradeoff:
+/// - `1.0` = pure relevance (no diversity)
+/// - `0.0` = pure diversity (ignores relevance)
+/// - `0.7` = the value this tool passes
+///
+/// For each selection step:
+/// `mmr(c) = lambda · relevance(c) − (1 − lambda) · max_similarity(c, selected)`.
+///
+/// `lambda` is clamped to `[0.0, 1.0]`; `limit` is clamped to
+/// `candidates.len()`. Returns `Vec::new()` immediately if `candidates` is
+/// empty or `limit == 0`.
+///
+/// # Relevance is precomputed, not derived from a query vector here
+///
+/// The engine's signature took a `query_vec` first argument and never read it —
+/// relevance came entirely from [`MmrCandidate::relevance`], which the caller
+/// had already derived from the query with the same [`cosine_similarity`] used
+/// below. The parameter is dropped in this port because the one call site fills
+/// `relevance` exactly that way, so it was provably inert; the selection is
+/// bit-for-bit what it was. If a future revision wants query-aware scoring
+/// inside the loop, add the parameter back *and wire it*, rather than
+/// reinstating a placeholder.
+fn mmr_select(candidates: &[MmrCandidate<'_>], limit: usize, lambda: f64) -> Vec<MmrResult> {
+ if candidates.is_empty() || limit == 0 {
+ return Vec::new();
+ }
+
+ let lambda = lambda.clamp(0.0, 1.0);
+ let limit = limit.min(candidates.len());
+
+ let mut selected_embeddings: Vec<&[f32]> = Vec::with_capacity(limit);
+ let mut results: Vec<MmrResult> = Vec::with_capacity(limit);
+ let mut available: Vec<bool> = vec![true; candidates.len()];
+
+ for _ in 0..limit {
+ let mut best_idx: Option<usize> = None;
+ let mut best_mmr = f64::NEG_INFINITY;
+
+ for (i, candidate) in candidates.iter().enumerate() {
+ if !available[i] {
+ continue;
+ }
+ let max_sim_to_selected = if selected_embeddings.is_empty() {
+ 0.0
+ } else {
+ selected_embeddings
+ .iter()
+ .map(|sel| cosine_similarity(candidate.embedding, sel))
+ .fold(0.0_f64, f64::max)
+ };
+ let mmr_score = lambda * candidate.relevance - (1.0 - lambda) * max_sim_to_selected;
+ if mmr_score > best_mmr {
+ best_mmr = mmr_score;
+ best_idx = Some(i);
+ }
+ }
+
+ let Some(idx) = best_idx else { break };
+ available[idx] = false;
+ selected_embeddings.push(candidates[idx].embedding);
+ results.push(MmrResult {
+ index: candidates[idx].index,
+ score: best_mmr,
+ });
+ }
+
+ results
+}
+
#[derive(Debug, Deserialize)]
struct Args {
query: String,
@@ -228,7 +389,7 @@ impl Tool for MemoryVectorSearchTool {
relevance: *score,
})
.collect();
- let mmr_results = mmr_select(&query_vec, &candidates, limit, 0.7);
+ let mmr_results = mmr_select(&candidates, limit, 0.7);
mmr_results
.into_iter()
.map(|r| {
diff --git a/src/openhuman/memory/tree/mod.rs b/src/openhuman/memory/tree/mod.rs
index fcf52208e8..85db4f8301 100644
--- a/src/openhuman/memory/tree/mod.rs
+++ b/src/openhuman/memory/tree/mod.rs
@@ -5,58 +5,50 @@
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
//! The glob re-export keeps every historical `memory::tree::…` path resolving.
//!
-//! # What the glob still carries, checked rather than assumed (#5560)
+//! # What the glob still carries, re-measured rather than assumed (#5560)
//!
//! Four of the nine module names it supplies (`health`, `retrieval`, `tree`,
//! `tree_runtime`) are shadowed by the `pub mod` declarations below — an
//! explicit item beats a glob import — so its live contribution is narrower
-//! than it looks, and all of it is engine-owned:
+//! than it looks. **Measured by deleting the line and reading the compiler**,
+//! rather than by grepping for the paths, the production surface is now two
+//! names in two files:
//!
-//! - `score`, `summarise`, `nlp`, `ingest` — real code in `tinymemory-core`,
-//! not thin aliases: `score::embed::{Embedder, build_embedder_from_config,
-//! effective_embedder_slug, EMBEDDING_DIM}`, `score::extract::EntityKind`,
-//! `score::store`, `score::resolver`, `summarise::{summarise,
-//! fallback_summary, SummaryContext, SummaryInput}` and
-//! `nlp::extract_query_entities` are reached from the archivist, the
-//! sub-agent runner, `read_rpc::entities`, `inference::embeddings::rpc` and
-//! `retrieval/rpc.rs` in this directory.
+//! - `score` — `read_rpc::entities` reaches `score::store` and
+//! `score::DEFAULT_DROP_THRESHOLD` for the chunk-score RPC.
+//! - `summarise` — `agent::harness::archivist::recap` reaches
+//! `summarise::{summarise, SummaryContext, SummaryInput}`.
//!
-//! The seven `Tree{LabelStrategy, LeafPayload, ReadHit, ReadRequest,
-//! ReadResult, WriteOutcome, WriteRequest}` I/O types used to be on that list
-//! too. They are **not** engine-owned — the crate re-exports them out of
-//! `engine::backend::tree`, i.e. `tinycortex` — so they are named there
-//! directly below and no longer depend on this glob. Nothing in `src/` uses
-//! them; `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs` names all
-//! seven, which is why they are still re-exported at all.
+//! Everything else the glob carries is now test-only or unreferenced.
+//! `ingest` (`ingest_summary` / `SummaryIngestInput`) survives for
+//! `tests/memory_sync_pipeline_e2e.rs`, `score::{embed, extract, resolver,
+//! signals}` and `summarise::fallback_summary` for the raw-coverage suites,
+//! and `nlp` and `graph` have no caller under this path at all — `nlp`
+//! **used** to be reached from `retrieval/rpc.rs` and no longer is. A glob is
+//! all-or-nothing, so the unused names ride along with the two that are left.
//!
-//! (`graph` is the fifth unshadowed name and has no caller under this path at
-//! all — it is carried only because the glob is all-or-nothing.)
+//! Neither survivor has a contract equivalent: `tinymemory_api::tree` is the
+//! summary-node vocabulary, not an embedder and not an entity extractor. So
+//! this shim is pinned by the engine's *scoring and summarisation* internals
+//! reached from two files outside this directory, and it goes when those two
+//! move — not before.
//!
-//! None of it has a contract equivalent: `tinymemory_api::tree` is the summary
-//! node vocabulary, not an embedder or an entity extractor. So this shim is
-//! pinned by the engine's *scoring and summarisation* internals, and it goes
-//! when those move behind the bus — not before.
-
-// The seven tree I/O contracts, named at the crate that defines them
-// (`tinycortex::memory::tree::io`). `tinymemory_core::tree` re-exports them out
-// of `engine::backend::tree`, which is `pub use tinycortex::memory::tree`, so
-// this is the same item under a different crate alias — an explicit `use`
-// shadowing the glob below with itself. Nothing in `src/` names them;
-// `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs` names all seven
-// through this path, which is why they are re-exported rather than dropped, and
-// why they now keep resolving once `tinymemory-core` leaves the build.
-pub use tinycortex::memory::tree::{
- TreeLabelStrategy, TreeLeafPayload, TreeReadHit, TreeReadRequest, TreeReadResult,
- TreeWriteOutcome, TreeWriteRequest,
-};
+//! The seven `Tree{LabelStrategy, LeafPayload, ReadHit, ReadRequest,
+//! ReadResult, WriteOutcome, WriteRequest}` I/O types were re-exported here
+//! explicitly until #5560's shed pass. **They are gone**: nothing in `src/`
+//! named them, and the one consumer —
+//! `tests/raw_coverage/memory_threads_raw_coverage_e2e.rs` — names
+//! `tinycortex::memory::tree::…` directly now. A production `pub use` that
+//! exists only to serve a test is exactly what keeps a crate in
+//! `[dependencies]`, which is the thing this issue is removing.
// What is left of the glob is the scoring and summarisation half, and it is
// `tinymemory-core`'s own code rather than a re-export: `score` (embed /
-// extract / store / resolver), `summarise`, `nlp` and `ingest`, plus `graph`,
-// which the glob carries because a glob is all-or-nothing. `tinymemory_api::tree`
-// is the summary-node vocabulary — not an embedder and not an entity extractor
-// — so there is nothing on the contract to route these at. This shim goes when
-// scoring and summarisation move behind the bus, not before.
+// extract / store / resolver / signals), `summarise`, `nlp` and `ingest`, plus
+// `graph`, which the glob carries because a glob is all-or-nothing.
+// `tinymemory_api::tree` is the summary-node vocabulary — not an embedder and
+// not an entity extractor — so there is nothing on the contract to route these
+// at. Two production files pin it; see the module docs above for which.
pub use tinymemory_core::tree::*;
pub mod health;
diff --git a/src/openhuman/memory/tree/retrieval/mod.rs b/src/openhuman/memory/tree/retrieval/mod.rs
index 8debba8cb0..a96116120b 100644
--- a/src/openhuman/memory/tree/retrieval/mod.rs
+++ b/src/openhuman/memory/tree/retrieval/mod.rs
@@ -3,41 +3,51 @@
//! The domain itself lives in the extracted crate; what stays here is its
//! JSON-RPC surface — handlers and controller schemas name OpenHuman's
//! `RpcOutcome` and `ControllerSchema`, which the engine crate cannot see.
-//! The glob re-export keeps every historical `memory::tree::retrieval::…` path resolving.
-
-// Engine-owned, and the names are a trap worth naming: `RetrievalHit`,
-// `QueryResponse`, `NodeKind` and `EntityMatch` here are **not** the contract's
-// `RetrievalHit`, `RetrievalResponse`, `RetrievalNodeKind` and `EntityMatch`.
-// Repointing this shim at `memory::api::provider` is a wire change and not a
-// path swap. Probe the item identity before assuming a carve-out is free.
-//
-// **The field that used to prove that has changed; the conclusion has not.**
-// This comment said the contract's hit "has no field for" `tree_kind`. It has
-// one as of the pinned v1.7.0 — `tree_kind: Option<String>`, `#[serde(default,
-// skip_serializing_if)]` — so re-derive the difference from the types rather
-// than from this sentence. What still separates them, checked against
-// `tinymemory-bus`'s `provider::retrieval` and tinycortex's
-// `memory::retrieval::types`:
-//
-// - `tree_kind` is an **open string** on the contract and the closed
-// `TreeKind` enum on the engine, so a hit crossing between them needs a
-// conversion that can fail in one direction and is lossy in neither;
-// - the engine's hit is non-optional there — a bare leaf reports
-// `TreeKind::Source` via `leaf_tree_placeholder`, where the contract encodes
-// the same absence as `None`. Those are different answers to "which tree did
-// this come from", and a swap would silently relabel every unsealed leaf.
-//
-// So this is still a wire change, and one whose translation has to be written
-// down at the handler rather than assumed by the type system.
-//
-// What keeps this line alive (#5560): `fast_retrieve` + `FastRetrieveOptions`
-// (memory::agent::ops, memory::schema::handlers), `types::{NodeKind,
-// QueryResponse, RetrievalHit}` (read_rpc::chunks, the sub-agent runner),
-// `source::{SourceQuery, query_source_scoped}` (read_rpc::chunks) and
-// `search::search_entities` — plus `{query_source, search_entities}` from the
-// memory e2e suites. Every one names a shape the contract does not carry, so
-// this is the same wire-change ask as the paragraph above, not a routing one.
-pub use tinymemory_core::tree::retrieval::*;
+//!
+//! # The engine glob is gone — it had no production caller left (#5560)
+//!
+//! This module used to open with `pub use tinymemory_core::tree::retrieval::*`,
+//! carried by a comment listing what kept it alive: `fast_retrieve` +
+//! `FastRetrieveOptions` from `memory::agent::ops` and
+//! `memory::schema::handlers`, `types::{NodeKind, QueryResponse,
+//! RetrievalHit}` from `read_rpc::chunks` and the sub-agent runner, and
+//! `source::{SourceQuery, query_source_scoped}`.
+//!
+//! **That list had gone stale, every entry of it.** Each of those call sites
+//! now takes the contract instead —
+//! `crate::openhuman::memory::api::provider::retrieval::{FastRetrieveQuery,
+//! RetrievalResponse, …}` — and `rpc.rs` and `schemas.rs` in this directory
+//! name nothing from the engine either. Deleting the line and compiling the
+//! lib produced **zero** errors, which is the check to repeat before trusting
+//! any sentence in this file: grep finds the path
+//! `memory::tree::retrieval::…`, but almost every hit is `retrieval::rpc`,
+//! the `pub mod` below, and a glob is invisible to grep anyway.
+//!
+//! The surviving callers were all tests, and they name
+//! `tinymemory_core::tree::retrieval::…` directly now: the engine crate is a
+//! dev-dependency, and a dev-dependency does not keep a crate in the shipped
+//! build the way a `pub use` in the lib does.
+//!
+//! # If you are tempted to re-add it, read this first
+//!
+//! The name collision that made the old glob dangerous has not gone away —
+//! it is just no longer this file's problem. `RetrievalHit`, `QueryResponse`,
+//! `NodeKind` and `EntityMatch` on the engine are **not** the contract's
+//! `RetrievalHit`, `RetrievalResponse`, `RetrievalNodeKind` and
+//! `EntityMatch`. Two differences survive, checked against `tinymemory-bus`'s
+//! `provider::retrieval` and tinycortex's `memory::retrieval::types`:
+//!
+//! - `tree_kind` is an **open string** on the contract and the closed
+//! `TreeKind` enum on the engine, so a hit crossing between them needs a
+//! conversion that can fail in one direction and is lossy in neither;
+//! - the engine's field is non-optional — a bare leaf reports
+//! `TreeKind::Source` via `leaf_tree_placeholder`, where the contract
+//! encodes the same absence as `None`. Those are different answers to "which
+//! tree did this come from", and a swap would silently relabel every
+//! unsealed leaf.
+//!
+//! So routing an engine hit through the contract is a wire change whose
+//! translation has to be written down at a handler, not a path swap.
pub mod rpc;
pub mod schemas;
diff --git a/src/openhuman/memory/tree/tree/rpc_part_01.rs b/src/openhuman/memory/tree/tree/rpc_part_01.rs
index 42cfa4081f..fcdc5315bf 100644
--- a/src/openhuman/memory/tree/tree/rpc_part_01.rs
+++ b/src/openhuman/memory/tree/tree/rpc_part_01.rs
@@ -1,16 +1,215 @@
-use serde::{Deserialize, Serialize};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use crate::openhuman::config::Config;
use crate::openhuman::memory::api::provider::ChunkQuery;
use crate::rpc::RpcOutcome;
-use tinycortex::memory::ingest::canonicalize::{
- chat::ChatBatch, document::DocumentInput, email::EmailThread,
-};
use tinymemory_api::chunks::{Chunk, DataSource, SourceKind, SourceRef};
use tinymemory_api::provider::types::{IngestItem, IngestOutcome};
use tinymemory_api::types::MemoryTaint;
+// ── The `memory_tree_ingest` payload shapes (#5560) ──────────────────────────
+//
+// `ChatBatch`, `EmailThread` and `DocumentInput` were imported from
+// `tinycortex::memory::ingest::canonicalize`. They are defined here now, and
+// the reason is that **this host is their only reader**: they are the request
+// half of an OpenHuman JSON-RPC method, deserialised by [`ingest_rpc`] below
+// and turned into contract [`IngestItem`]s by the three mappers further down.
+// Nothing on this side ever hands one of these structs to the engine — the
+// items are what cross the bus, and the driver rebuilds its own copy of these
+// shapes on the far end from those items. Two independent readers of one JSON
+// wire format, which is the same arrangement `memory::rpc_models`,
+// `memory::safety` and `memory::source_scope` already landed on.
+//
+// So there is no contract door to route this at, and asking for one would be
+// asking `tinymemory-api` to carry a payload that never crosses the bus. What
+// pins the *shape* is the wire, not the type: the driver's reconstruction is
+// documented field-for-field on [`email_items`] and [`chat_items`], and
+// `rpc_tests_part_01_tests` pins the serde tolerances. Change a field name
+// here and the round trip breaks in exactly the way those tests describe —
+// which is the same exposure the import had, since a rename upstream would
+// have reshaped this RPC's published request body without anything here
+// failing to compile.
+//
+// `Serialize` is derived alongside `Deserialize` because the engine derived
+// both and the round-trip is what the tests assert; nothing in `src/`
+// serialises one.
+
+/// Serde default for the two chat/mail message timestamps.
+///
+/// A payload missing the field falls back to `now()` rather than rejecting the
+/// whole batch, so a client with version skew (or a third-party integration
+/// that never sent one) does not lose an entire thread to one absent key.
+fn ingest_timestamp_now() -> DateTime<Utc> {
+ Utc::now()
+}
+
+/// Serde default for [`DocumentInput::provider`].
+fn default_document_provider() -> String {
+ "unknown".to_string()
+}
+
+/// Accept a timestamp as epoch-milliseconds, an RFC 3339 / ISO-8601 string, or
+/// `null`.
+///
+/// Three shapes because three generations of clients send three shapes, and
+/// the alternative to accepting all of them is silently dropping whichever the
+/// caller happens to use.
+///
+/// The near-epoch rejection is the load-bearing part: contemporary epoch
+/// *seconds* are ten digits and epoch *milliseconds* are thirteen, so a
+/// seconds value passed here would decode to 1970 and quietly poison ordering
+/// and staleness. Rejecting the ambiguous range makes that a loud error at the
+/// seam instead.
+fn deserialize_flexible_timestamp<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum RawTs {
+ Millis(i64),
+ Text(String),
+ Null,
+ }
+
+ fn epoch_millis<E: serde::de::Error>(ms: i64) -> Result<DateTime<Utc>, E> {
+ const MIN_PLAUSIBLE_EPOCH_MILLIS: u64 = 100_000_000_000;
+ if ms.unsigned_abs() < MIN_PLAUSIBLE_EPOCH_MILLIS {
+ return Err(E::custom(format!(
+ "epoch-ms value {ms} is too small; pass milliseconds, not seconds"
+ )));
+ }
+ chrono::TimeZone::timestamp_millis_opt(&Utc, ms)
+ .single()
+ .ok_or_else(|| E::custom(format!("invalid epoch-ms: {ms}")))
+ }
+
+ let raw = RawTs::deserialize(deserializer)?;
+ match raw {
+ RawTs::Null => Ok(Utc::now()),
+ RawTs::Millis(ms) => epoch_millis(ms),
+ RawTs::Text(s) => {
+ if let Ok(dt) = DateTime::parse_from_rfc3339(&s) {
+ return Ok(dt.with_timezone(&Utc));
+ }
+ if let Ok(ms) = s.parse::<i64>() {
+ return epoch_millis(ms);
+ }
+ Err(serde::de::Error::custom(format!(
+ "cannot parse '{s}' as RFC 3339 or epoch-ms"
+ )))
+ }
+ }
+}
+
+/// One chat message in a channel/group.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ChatMessage {
+ /// Author display name or id.
+ pub author: String,
+ /// When the message was sent (epoch-ms integer or RFC 3339 string).
+ /// When absent from the payload, defaults to `Utc::now()` — see
+ /// [`ingest_timestamp_now`].
+ #[serde(
+ default = "ingest_timestamp_now",
+ serialize_with = "chrono::serde::ts_milliseconds::serialize",
+ deserialize_with = "deserialize_flexible_timestamp"
+ )]
+ pub timestamp: DateTime<Utc>,
+ /// Plain text / markdown body.
+ pub text: String,
+ /// Optional per-message provenance pointer (permalink or `platform://...`).
+ #[serde(default)]
+ pub source_ref: Option<String>,
+}
+
+/// Adapter input — a batch of messages from one logical channel.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ChatBatch {
+ /// Platform name (e.g. `slack`, `discord`, `telegram`). Crosses verbatim
+ /// as [`IngestItem::platform`]; see [`chat_data_source`] for how it is
+ /// additionally mapped onto a [`DataSource`].
+ pub platform: String,
+ /// Human-readable channel / group name.
+ pub channel_label: String,
+ /// Ordered messages (chronological; the adapter sorts defensively).
+ pub messages: Vec<ChatMessage>,
+}
+
+/// One email in a thread.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct EmailMessage {
+ /// Sender address; rendered as the `From:` header and used as the
+ /// participant key when bucketing a thread.
+ pub from: String,
+ /// Primary recipient addresses; the `To:` header (omitted when empty).
+ #[serde(default)]
+ pub to: Vec<String>,
+ /// Carbon-copy recipient addresses; the `Cc:` header (omitted when empty).
+ #[serde(default)]
+ pub cc: Vec<String>,
+ /// Per-message subject; the `Subject:` header.
+ pub subject: String,
+ /// When the message was sent (epoch-ms integer or RFC 3339 string).
+ /// When absent, defaults to `Utc::now()` so one missing key does not
+ /// reject the whole thread.
+ #[serde(
+ default = "ingest_timestamp_now",
+ serialize_with = "chrono::serde::ts_milliseconds::serialize",
+ deserialize_with = "deserialize_flexible_timestamp"
+ )]
+ pub sent_at: DateTime<Utc>,
+ /// Plain-text or markdown body.
+ pub body: String,
+ /// Message-id header or provider URL; used for citation back to source.
+ #[serde(default)]
+ pub source_ref: Option<String>,
+ /// `List-Unsubscribe` header. Carried through because an unsubscribe flow
+ /// reads it back out of stored mail — dropping it makes that flow
+ /// impossible, not merely poorer (see [`email_items`]).
+ #[serde(default)]
+ pub list_unsubscribe: Option<String>,
+}
+
+/// A whole email thread.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct EmailThread {
+ /// Provider name (e.g. `gmail`, `outlook`). See [`email_data_source`].
+ pub provider: String,
+ /// Thread subject (usually the subject of the first message).
+ pub thread_subject: String,
+ /// Ordered messages (chronological; the adapter sorts defensively).
+ pub messages: Vec<EmailMessage>,
+}
+
+/// Adapter input for a single document.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct DocumentInput {
+ /// Provider name (e.g. `notion`, `drive`, `meeting_notes`). Defaults to
+ /// `"unknown"` when absent. See [`document_data_source`].
+ #[serde(default = "default_document_provider")]
+ pub provider: String,
+ /// Document title. Read only to decide whether the payload was wholly
+ /// empty — it does not cross to the driver; see [`document_item`].
+ pub title: String,
+ /// Document body (markdown preferred; plain text also accepted).
+ pub body: String,
+ /// When the document was last modified at the source.
+ ///
+ /// Accepts an epoch-milliseconds integer (back-compat), an RFC 3339 /
+ /// ISO-8601 string, or absent → `Utc::now()`.
+ #[serde(
+ default = "ingest_timestamp_now",
+ deserialize_with = "deserialize_flexible_timestamp"
+ )]
+ pub modified_at: DateTime<Utc>,
+ /// Optional pointer back to source (URL, file path, Notion page id).
+ #[serde(default)]
+ pub source_ref: Option<String>,
+}
+
/// Unified ingest request. The `payload` shape is adapter-specific and is
/// validated inside the dispatch based on `source_kind`.
#[derive(Clone, Debug, Serialize, Deserialize)]
diff --git a/src/openhuman/memory/tree/tree/rpc_tests.rs b/src/openhuman/memory/tree/tree/rpc_tests.rs
index 447862001b..1025cf8108 100644
--- a/src/openhuman/memory/tree/tree/rpc_tests.rs
+++ b/src/openhuman/memory/tree/tree/rpc_tests.rs
@@ -2,7 +2,12 @@ use super::*;
use chrono::Utc;
use serde_json::json;
use tempfile::TempDir;
-use tinycortex::memory::ingest::canonicalize::document::DocumentInput;
+// `DocumentInput` (and its `ChatBatch` / `EmailThread` siblings, which
+// `rpc_tests_part_01_tests` reaches the same way) now arrive through the
+// `use super::*` above: they are defined in `rpc_part_01.rs` rather than
+// imported from the engine crate. Naming the engine's copy here would compile
+// and then fail on the first call into `document_item`, since the two are
+// distinct types with identical fields.
use tinymemory_api::chunks::SourceKind;
fn test_config() -> (TempDir, Config) {
diff --git a/src/openhuman/memory/tree/tree_runtime/ops.rs b/src/openhuman/memory/tree/tree_runtime/ops.rs
index a174d15fed..7b5dc6e80c 100644
--- a/src/openhuman/memory/tree/tree_runtime/ops.rs
+++ b/src/openhuman/memory/tree/tree_runtime/ops.rs
@@ -4,9 +4,24 @@ use chrono::{DateTime, Utc};
use serde_json::{json, Value};
use crate::openhuman::config::Config;
+// The summary-tree node vocabulary, named at the **contract** (#5560).
+//
+// This was `use tinycortex::memory::tree::runtime::*;`, a glob whose entire
+// live contribution to this file was two names: `estimate_tokens` (the token
+// figure reported on an ingest) and `QueryResult` (the node + children envelope
+// `tree_summarizer_query` serialises). Both are `tinymemory-bus` items that the
+// engine crate merely re-exported — `tinycortex::memory::tree::runtime` aliases
+// its `types` module to `tinycortex_api::tree`, and `tinycortex-api` is a
+// deprecated re-export of `tinymemory-bus` — so this names the *same items*
+// under the path the module contract already uses, and no wire byte changes.
+// The sibling `tree_runtime/mod.rs` re-exports the same set for the same
+// reason; see its comment on the node model.
+//
+// Everything else this file reaches still comes from `engine` / `store` below,
+// which are `tinymemory-core`'s and are what actually pins that crate here.
+use crate::openhuman::memory::api::tree::{estimate_tokens, QueryResult};
use crate::openhuman::memory::tree::tree_runtime::{engine, store};
use crate::rpc::RpcOutcome;
-use tinycortex::memory::tree::runtime::*;
/// Append raw content to the ingestion buffer.
pub async fn tree_summarizer_ingest(
@@ -166,7 +181,8 @@ pub async fn tree_summarizer_rebuild(
/// `memory_tree.cloud_summarization_opt_in` setting.
///
/// Visibility note: `pub(crate)` so the embedded memory driver's
-/// [`MemoryTree`](tinycortex_api::provider::MemoryTree) `seal`/`cascade` reach
+/// [`MemoryTree`](crate::openhuman::memory::api::provider::MemoryTree)
+/// `seal`/`cascade` reach
/// the **same** resolver the RPC path uses. Duplicating the local-AI /
/// cloud-opt-in precedence in the driver would be new policy logic, and the
/// `summarizer_available` doc below is explicit that this function is the
diff --git a/src/openhuman/memory/tree/tree_runtime/ops_tests.rs b/src/openhuman/memory/tree/tree_runtime/ops_tests.rs
index 1076372fc8..678f5e6c46 100644
--- a/src/openhuman/memory/tree/tree_runtime/ops_tests.rs
+++ b/src/openhuman/memory/tree/tree_runtime/ops_tests.rs
@@ -2,6 +2,13 @@ use super::*;
use chrono::TimeZone;
use tempfile::TempDir;
+// `TreeNode`, `level_from_node_id` and `derive_parent_id` used to arrive
+// through `super::*` while `ops.rs` still globbed the engine crate's runtime
+// module. `ops.rs` names the contract explicitly now (#5560) and imports only
+// the two items it uses, so these are named here — the same items, from the
+// same crate the sibling `tree_runtime/mod.rs` re-exports them from.
+use crate::openhuman::memory::api::tree::{derive_parent_id, level_from_node_id, TreeNode};
+
fn rfc3339_z(ts: DateTime<Utc>) -> String {
ts.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
diff --git a/src/openhuman/security/credentials/ops_part_01.rs b/src/openhuman/security/credentials/ops_part_01.rs
index 75cde3a06e..0c4a9f9036 100644
--- a/src/openhuman/security/credentials/ops_part_01.rs
+++ b/src/openhuman/security/credentials/ops_part_01.rs
@@ -17,7 +17,7 @@ use crate::openhuman::config::{
default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, user_openhuman_dir,
write_active_user_id,
};
-use tinycortex::memory::conversations;
+use crate::openhuman::memory::conversations;
const AUTH_ME_STORE_RETRY_DELAY: Duration = Duration::from_millis(150);
const AUTH_ME_STORE_TRANSIENT_STATUSES: &[u16] = &[408, 429, 500, 502, 503, 504, 520];
diff --git a/src/openhuman/threads/ops_part_01.rs b/src/openhuman/threads/ops_part_01.rs
index fbb6370329..d7c3f5f006 100644
--- a/src/openhuman/threads/ops_part_01.rs
+++ b/src/openhuman/threads/ops_part_01.rs
@@ -17,6 +17,10 @@ use crate::openhuman::memory::{
// the store's `parking_lot` mutex, which starved the runtime and made
// `threads_create_new` blow the frontend's 30 s RPC budget (#5156).
use crate::openhuman::memory::conversations;
+use crate::openhuman::memory::conversations::{
+ ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
+ CrossThreadHit,
+};
use crate::openhuman::threads::title::{
build_title_request, is_auto_generated_thread_title, sanitize_generated_title,
title_from_user_message, title_log_fingerprint, THREAD_TITLE_LOG_PREFIX,
@@ -31,10 +35,6 @@ use crate::rpc::RpcOutcome;
use serde::Serialize;
use std::collections::BTreeMap;
use std::path::PathBuf;
-use tinycortex::memory::conversations::{
- ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
- CrossThreadHit,
-};
fn request_id() -> String {
uuid::Uuid::new_v4().to_string()
diff --git a/src/openhuman/threads/ops_tests.rs b/src/openhuman/threads/ops_tests.rs
index a5409c0237..d4443c27ef 100644
--- a/src/openhuman/threads/ops_tests.rs
+++ b/src/openhuman/threads/ops_tests.rs
@@ -5,6 +5,7 @@
use super::*;
// Re-imported here rather than through `ops`: `ops` itself no longer names
// these, so importing them there would be an unused import in a non-test build.
+use crate::openhuman::memory::conversations as conversations_store;
use crate::openhuman::threads::title::{build_title_prompt, THREAD_TITLE_SYSTEM_PROMPT};
use crate::openhuman::threads::turn_state::{
self, ClearTurnStateRequest, GetTurnStateRequest, TurnState,
@@ -13,7 +14,6 @@ use crate::openhuman::threads::ThreadsError;
use serde_json::{json, Value};
use std::ffi::OsString;
use std::path::Path;
-use tinycortex::memory::conversations as conversations_store;
struct EnvVarGuard {
key: &'static str,
diff --git a/src/openhuman/threads/welcome_migration.rs b/src/openhuman/threads/welcome_migration.rs
index bb657e5bf7..11f2ed483c 100644
--- a/src/openhuman/threads/welcome_migration.rs
+++ b/src/openhuman/threads/welcome_migration.rs
@@ -18,8 +18,8 @@
use std::fs;
use std::path::Path;
+use crate::openhuman::memory::conversations;
use serde_json::{json, Value};
-use tinycortex::memory::conversations;
const MIGRATION_MARKER: &str = "state/migrations/welcome_to_orchestrator_v1.done";
const WELCOME_THREAD_LABEL: &str = "onboarding";
diff --git a/src/openhuman/threads/welcome_migration_tests.rs b/src/openhuman/threads/welcome_migration_tests.rs
index a0c68c0119..e37e61bdc7 100644
--- a/src/openhuman/threads/welcome_migration_tests.rs
+++ b/src/openhuman/threads/welcome_migration_tests.rs
@@ -1,6 +1,8 @@
use super::*;
+use crate::openhuman::memory::conversations::{
+ ensure_thread, list_threads, CreateConversationThread,
+};
use tempfile::TempDir;
-use tinycortex::memory::conversations::{ensure_thread, list_threads, CreateConversationThread};
fn make_thread(id: &str, labels: Vec<String>) -> CreateConversationThread {
CreateConversationThread {
diff --git a/src/openhuman/tools/ops.rs b/src/openhuman/tools/ops.rs
index 04ac02f16c..5bb42d2b77 100644
--- a/src/openhuman/tools/ops.rs
+++ b/src/openhuman/tools/ops.rs
@@ -1435,16 +1435,21 @@ fn tool_group(name: &str) -> crate::core::all::DomainGroup {
/// wrong default is worse than no rule. Hence enumeration plus two narrow
/// prefix rules, backed by the drift guard.
///
-/// ## Honesty clause — three assignments run ahead of the plumbing
+/// ## Honesty clause — two assignments still run ahead of the plumbing
///
-/// `goals_*` is filesystem-backed today (`tinycortex::memory::goals::store`), not
-/// `MemoryGoals`; `tool_stats` reads the legacy `Arc<dyn Memory>` plus
+/// `tool_stats` reads the legacy `Arc<dyn Memory>` plus
/// `agent::learning::tool_tracker`, not `MemoryToolMemory`; `memory_diff` reads
/// `memory::diff::ops`, not `MemoryDiff`. Filtering them on the driver's
/// advertised set is nevertheless the correct M5 behaviour: §3.3 is a contract
/// about what the *model is told exists*, and the later re-point onto
/// `MemoryGuard` must not change the advertised surface. Assigning them `None`
/// to dodge the mismatch would bake the wrong contract in.
+///
+/// `goals_*` was the third and is no longer: it was filesystem-backed through
+/// `tinycortex::memory::goals::store`, and openhuman#5560 routed it onto the
+/// guarded `MemoryGoals` family. The advertised capability did not have to
+/// change when the plumbing caught up, which is the property this clause was
+/// written to protect.
fn tool_capability(name: &str) -> Option<tinymemory_api::capabilities::Capability> {
use tinymemory_api::capabilities::Capability;
diff --git a/tests/personality_e2e.rs b/tests/personality_e2e.rs
index 86c8788f7d..ba40e2401a 100644
--- a/tests/personality_e2e.rs
+++ b/tests/personality_e2e.rs
@@ -32,14 +32,16 @@ use openhuman_core::openhuman::agent::prompts::{
PromptSection, ToolCallFormat, UserFilesSection,
};
use openhuman_core::openhuman::inference::embeddings::NoopEmbedding;
+use openhuman_core::openhuman::memory::conversations::{
+ ensure_thread, list_threads, update_thread_title, ConversationStore, CreateConversationThread,
+};
use openhuman_core::openhuman::memory::NamespaceDocumentInput;
// The engine handle is named on the crate rather than reached through the
// memory module's public surface: it is an in-process engine type, not
// contract vocabulary, and the alias that used to re-export it existed for
-// callers that no longer exist (#5560).
-use tinycortex::memory::conversations::{
- ensure_thread, list_threads, update_thread_title, ConversationStore, CreateConversationThread,
-};
+// callers that no longer exist (#5560). This note is about `UnifiedMemory`
+// alone — the conversation store above is host code again as of #5560 and is
+// reached through the memory module's surface like any other host type.
use tinymemory_core::store::UnifiedMemory;
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/tests/raw_coverage/memory_core_threads_raw_coverage_e2e.rs b/tests/raw_coverage/memory_core_threads_raw_coverage_e2e.rs
index 9b94412323..49c794dd55 100644
--- a/tests/raw_coverage/memory_core_threads_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_core_threads_raw_coverage_e2e.rs
@@ -13,17 +13,27 @@ use tempfile::TempDir;
use openhuman_core::openhuman::agent::progress::AgentProgress;
use openhuman_core::openhuman::config::Config;
-use openhuman_core::openhuman::memory::read_rpc::{
- self, ChunkFilter, GraphMode,
+use openhuman_core::openhuman::memory::conversations::{
+ ensure_thread, list_threads, CreateConversationThread,
};
-use tinymemory_core::tree_source::get_or_create_source_tree;
+use openhuman_core::openhuman::memory::read_rpc::{self, ChunkFilter, GraphMode};
+use openhuman_core::openhuman::memory::tree::score::embed::pack_embedding;
+use openhuman_core::openhuman::memory::tree::score::extract::EntityKind;
+use openhuman_core::openhuman::memory::tree::score::resolver::CanonicalEntity;
+use openhuman_core::openhuman::memory::tree::score::signals::ScoreSignals;
+use openhuman_core::openhuman::memory::tree::score::store::{index_entity, upsert_score, ScoreRow};
use openhuman_core::openhuman::memory::{
AppendConversationMessageRequest, ConversationMessageRecord, ConversationMessagesRequest,
CreateConversationThreadRequest, DeleteConversationThreadRequest, EmptyRequest,
GenerateConversationThreadTitleRequest, UpdateConversationMessageRequest,
UpdateConversationThreadLabelsRequest, UpdateConversationThreadTitleRequest,
};
-use tinycortex::memory::conversations::{ensure_thread, list_threads, CreateConversationThread};
+use openhuman_core::openhuman::threads::ops as thread_ops;
+use openhuman_core::openhuman::threads::turn_state::{
+ self, ClearTurnStateRequest, GetTurnStateRequest, TurnLifecycle, TurnStateMirror,
+ TurnStateStore,
+};
+use openhuman_core::openhuman::threads::welcome_migration::migrate_welcome_agent_artifacts;
use tinymemory_core::store::chunks::store::{upsert_chunks, with_connection};
use tinymemory_core::store::chunks::types::{
approx_token_count, chunk_id, Chunk, Metadata, SourceKind, SourceRef,
@@ -31,17 +41,7 @@ use tinymemory_core::store::chunks::types::{
use tinymemory_core::store::content;
use tinymemory_core::store::trees::store as tree_store;
use tinymemory_core::store::trees::types::{SummaryNode, TreeKind};
-use openhuman_core::openhuman::memory::tree::score::embed::pack_embedding;
-use openhuman_core::openhuman::memory::tree::score::extract::EntityKind;
-use openhuman_core::openhuman::memory::tree::score::resolver::CanonicalEntity;
-use openhuman_core::openhuman::memory::tree::score::signals::ScoreSignals;
-use openhuman_core::openhuman::memory::tree::score::store::{index_entity, upsert_score, ScoreRow};
-use openhuman_core::openhuman::threads::ops as thread_ops;
-use openhuman_core::openhuman::threads::turn_state::{
- self, ClearTurnStateRequest, GetTurnStateRequest, TurnLifecycle, TurnStateMirror,
- TurnStateStore,
-};
-use openhuman_core::openhuman::threads::welcome_migration::migrate_welcome_agent_artifacts;
+use tinymemory_core::tree_source::get_or_create_source_tree;
struct EnvGuard {
key: &'static str,
diff --git a/tests/raw_coverage/memory_raw_coverage_e2e.rs b/tests/raw_coverage/memory_raw_coverage_e2e.rs
index 94e54611d6..86df008427 100644
--- a/tests/raw_coverage/memory_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_raw_coverage_e2e.rs
@@ -10,9 +10,13 @@ use tempfile::TempDir;
use openhuman_core::openhuman::config::Config;
use openhuman_core::openhuman::memory::{
- ExtractionMode, IngestionState, MemoryIngestionConfig, MemoryIngestionRequest,
- NamespaceDocumentInput,
+ ExtractionMode, MemoryIngestionConfig, MemoryIngestionRequest, NamespaceDocumentInput,
};
+// The in-process ingest queue is the engine's and has no bus representation, so
+// `memory::mod` stopped re-exporting it for a consumer that was only ever this
+// test (#5560). Named on the crate directly, exactly as `upsert_chunks` below
+// already is — `tinymemory-core` is a dev-dependency, which this target links.
+use tinymemory_core::ingestion::IngestionState;
use openhuman_core::openhuman::memory::sources::status::{source_status, FreshnessLabel};
use openhuman_core::openhuman::memory::sources::{MemorySourceEntry, SourceKind};
use tinymemory_core::store::chunks::store::upsert_chunks;
diff --git a/tests/transcript_search_e2e.rs b/tests/transcript_search_e2e.rs
index fd5d8e15c8..b88f88c6ab 100644
--- a/tests/transcript_search_e2e.rs
+++ b/tests/transcript_search_e2e.rs
@@ -19,11 +19,11 @@ use std::sync::OnceLock;
use serde_json::json;
use tempfile::tempdir;
-use openhuman_core::openhuman::threads::ops::transcript_search;
-use openhuman_core::openhuman::tools::traits::Tool;
-use tinycortex::memory::conversations::{
+use openhuman_core::openhuman::memory::conversations::{
ConversationMessage, ConversationStore, CreateConversationThread,
};
+use openhuman_core::openhuman::threads::ops::transcript_search;
+use openhuman_core::openhuman::tools::traits::Tool;
// ── Env isolation (mirrors tests/memory_roundtrip_e2e.rs) ────────────────────