Skip to content

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

feat(memory): replace local conversation store with tinymemory-conversations crate

Steven Enamakelc1de0428acab
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index a14598497d..8c527dfd1e 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -238,6 +238,10 @@ tinyconnectors-bus = { path = "../../vendor/tinyconnectors/crates/tinyconnectors
# directly (EXTRACT_ENTITIES, EMBED_TEXT, EMBEDDER_SLUG) — prefer compile
# errors on renaming over MemberNotFound at runtime.
tinymemory-bus = { path = "../../vendor/tinymemory/crates/tinymemory-bus" }
+# `tinymemory-conversations` is the workspace conversation store (JSONL
+# threads/messages, cross-thread inverted index). A pure library: serde,
+# parking_lot, uuid, chrono, async-trait, sha2. No SQLite/HTTP/engine crate.
+tinymemory-conversations = { path = "../../vendor/tinymemory/crates/tinymemory-conversations" }
# `tinymemory-sources` is the source registry, its types and its readers, in a
# crate of its own. Taken directly rather than through `tinymemory-core`
# (OpenHuman#5560): `tinymemory_core::sources` is a thin layer over it —
diff --git a/crates/openhuman-core/src/memory/conversations/mod.rs b/crates/openhuman-core/src/memory/conversations/mod.rs
index 3f7c67dde7..43655e0138 100644
--- a/crates/openhuman-core/src/memory/conversations/mod.rs
+++ b/crates/openhuman-core/src/memory/conversations/mod.rs
@@ -49,7 +49,7 @@
pub mod blocking;
mod bus;
-mod store;
+use tinymemory_conversations as store;
pub use bus::register_conversation_persistence_subscriber;
pub use store::{
diff --git a/crates/openhuman-core/src/memory/conversations/store/inverted_index.rs b/crates/openhuman-core/src/memory/conversations/store/inverted_index.rs
deleted file mode 100644
index e29ca14b86..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/inverted_index.rs
+++ /dev/null
@@ -1,445 +0,0 @@
-//! 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/crates/openhuman-core/src/memory/conversations/store/inverted_index_tests.rs b/crates/openhuman-core/src/memory/conversations/store/inverted_index_tests.rs
deleted file mode 100644
index 7f577f4895..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/inverted_index_tests.rs
+++ /dev/null
@@ -1,254 +0,0 @@
-//! 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/crates/openhuman-core/src/memory/conversations/store/mod.rs b/crates/openhuman-core/src/memory/conversations/store/mod.rs
deleted file mode 100644
index 7eefa9d11b..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/mod.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-//! 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::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,
-//! root lifecycle coordination, per-root metadata and per-thread message
-//! locks, 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_messages_from, delete_thread, ensure_thread, get_messages, list_threads,
- purge_threads, update_message, update_thread_labels, update_thread_title,
- ConversationPurgeStats, ConversationStore,
-};
-pub use types::{
- is_deterministic_message_id, reply_run_id, run_reply_message_id, ConversationMessage,
- ConversationMessagePatch, ConversationThread, CreateConversationThread, CrossThreadHit,
-};
diff --git a/crates/openhuman-core/src/memory/conversations/store/store.rs b/crates/openhuman-core/src/memory/conversations/store/store.rs
deleted file mode 100644
index b714a41552..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store.rs
+++ /dev/null
@@ -1,481 +0,0 @@
-//! 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.
-//!
-//! On-disk mutations synchronize at the narrowest safe scope: lifecycle per
-//! conversation root, shared metadata per root, and messages per thread.
-//!
-//! 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;
-#[path = "store_locks.rs"]
-mod locks;
-
-/// 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";
-
-/// 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
-///
-/// Every operation first takes the root lifecycle lock. Message operations
-/// then take their per-thread lock and briefly take the metadata lock when
-/// they must inspect or append `threads.jsonl`. When metadata and the index
-/// cache are both needed, metadata is acquired first. No code may acquire a
-/// thread or metadata lock while holding `CONVERSATION_INDEX_CACHE`.
-///
-/// `prime_index_if_cold` minimises shared locking. It may hold both
-/// metadata and index locks only momentarily, and always in the metadata
-/// → `CONVERSATION_INDEX_CACHE` order above: while holding metadata
-/// 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 metadata before reading each transcript under that thread's own
-/// lock and finally acquires `CONVERSATION_INDEX_CACHE` alone to insert the
-/// built index. It never holds both across the slow JSONL walk.
-///
-/// `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 shared metadata 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 {
- root_dir: PathBuf,
- locks: std::sync::Arc<locks::StoreLocks>,
-}
-
-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 {
- let root = locks::normalized_root(&workspace_dir.join("memory").join("conversations"));
- let locks = locks::for_root(&root);
- Self {
- root_dir: root,
- locks,
- }
- }
-
- #[cfg(test)]
- pub(super) fn lock_identity_for_test(&self) -> usize {
- std::sync::Arc::as_ptr(&self.locks) as usize
- }
-
- #[cfg(test)]
- pub(super) fn thread_lock_identity_for_test(&self, thread_id: &str) -> usize {
- std::sync::Arc::as_ptr(&self.locks.thread(thread_id)) as usize
- }
-
- #[cfg(test)]
- pub(super) fn thread_lock_count_for_test(&self) -> usize {
- self.locks.thread_count()
- }
-}
-
-/// 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(),
- // Labels written by the retired background-reasoning engine. Its
- // threads are ordinary conversations now.
- "from_reflection" | "subconscious_tick" | "subconscious" => "general".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)
-}
-
-/// Find one message in a thread's JSONL log by id, without materializing the
-/// whole transcript.
-///
-/// Only the lines whose raw text carries the quoted id are deserialized, so a
-/// lookup costs one parse rather than one per stored message; a line that
-/// merely quotes the id inside its own content is rejected by the `id` check.
-/// Mirrors [`read_jsonl`]'s tolerance of blank and corrupt lines.
-pub(super) fn find_message_by_id(
- path: &Path,
- id: &str,
-) -> Result<Option<ConversationMessage>, String> {
- if !path.exists() {
- return Ok(None);
- }
- let needle = serde_json::to_string(id).map_err(|e| format!("encode message id {id}: {e}"))?;
- let file = File::open(path).map_err(|e| format!("open {}: {e}", path.display()))?;
- for (line_no, line) in BufReader::new(file).lines().enumerate() {
- let line =
- line.map_err(|e| format!("read {} line {}: {e}", path.display(), line_no + 1))?;
- if !line.contains(&needle) {
- continue;
- }
- match serde_json::from_str::<ConversationMessage>(&line) {
- Ok(message) if message.id == id => return Ok(Some(message)),
- _ => continue,
- }
- }
- Ok(None)
-}
-
-/// 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::delete_messages_from`].
-pub fn delete_messages_from(
- workspace_dir: PathBuf,
- thread_id: &str,
- message_id: &str,
-) -> Result<Option<usize>, String> {
- ConversationStore::new(workspace_dir).delete_messages_from(thread_id, message_id)
-}
-
-/// 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/crates/openhuman-core/src/memory/conversations/store/store_concurrency_tests.rs b/crates/openhuman-core/src/memory/conversations/store/store_concurrency_tests.rs
deleted file mode 100644
index b4fa6ad2fd..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store_concurrency_tests.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-use super::*;
-
-#[test]
-fn one_hundred_agent_threads_append_without_loss_or_corruption() {
- use std::sync::{Arc, Barrier};
-
- let temp = TempDir::new().unwrap();
- let store = ConversationStore::new(temp.path().to_path_buf());
- let created_at = "2026-09-10T00:00:00Z".to_string();
-
- for index in 0..100 {
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: format!("agent-{index}"),
- title: format!("Agent {index}"),
- created_at: created_at.clone(),
- labels: None,
- personality_id: None,
- })
- .unwrap();
- }
-
- let barrier = Arc::new(Barrier::new(101));
- let mut writers = Vec::with_capacity(100);
- for index in 0..100 {
- let store = store.clone();
- let barrier = Arc::clone(&barrier);
- let created_at = created_at.clone();
- writers.push(std::thread::spawn(move || {
- barrier.wait();
- store.append_message(
- &format!("agent-{index}"),
- ConversationMessage {
- id: format!("message-{index}"),
- content: format!("reply from agent {index}"),
- message_type: "text".to_string(),
- extra_metadata: serde_json::json!({}),
- sender: "assistant".to_string(),
- created_at,
- },
- )
- }));
- }
- barrier.wait();
-
- for writer in writers {
- writer.join().expect("writer panicked").expect("append");
- }
-
- let threads = store.list_threads().unwrap();
- assert_eq!(threads.len(), 100);
- assert!(threads.iter().all(|thread| thread.message_count == 1));
- for index in 0..100 {
- let messages = store.get_messages(&format!("agent-{index}")).unwrap();
- assert_eq!(messages.len(), 1);
- assert_eq!(messages[0].id, format!("message-{index}"));
- }
-}
-
-#[test]
-fn one_unreadable_transcript_does_not_stop_other_repairs() {
- let temp = TempDir::new().unwrap();
- let store = ConversationStore::new(temp.path().to_path_buf());
- let created_at = "2026-09-10T00:00:00Z".to_string();
-
- for id in ["a-unreadable", "z-readable"] {
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: id.to_string(),
- title: id.to_string(),
- created_at: created_at.clone(),
- labels: None,
- personality_id: None,
- })
- .unwrap();
- }
-
- std::fs::create_dir_all(store.thread_messages_path("a-unreadable")).unwrap();
- append_jsonl(
- &store.thread_messages_path("z-readable"),
- &ConversationMessage {
- id: "message".to_string(),
- content: "recover me".to_string(),
- message_type: "text".to_string(),
- extra_metadata: serde_json::json!({}),
- sender: "assistant".to_string(),
- created_at,
- },
- )
- .unwrap();
-
- let threads = store.list_threads().unwrap();
- let readable = threads
- .iter()
- .find(|thread| thread.id == "z-readable")
- .unwrap();
- assert_eq!(readable.message_count, 1);
-
- let folded = store.thread_index_unlocked().unwrap();
- assert_eq!(folded["z-readable"].message_count, Some(1));
- assert_eq!(folded["a-unreadable"].message_count, None);
-}
diff --git a/crates/openhuman-core/src/memory/conversations/store/store_index.rs b/crates/openhuman-core/src/memory/conversations/store/store_index.rs
deleted file mode 100644
index 854178e110..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store_index.rs
+++ /dev/null
@@ -1,446 +0,0 @@
-//! 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, HashSet};
-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,
- THREADS_FILENAME, THREAD_MESSAGES_DIR,
-};
-
-impl ConversationStore {
- /// If no index entry exists for this workspace, serialize cold builders,
- /// start a short-lived append journal, snapshot the live thread IDs under
- /// the root metadata lock, release it, and read every JSONL file under its
- /// per-thread lock. Publication folds in every append journaled during the
- /// scan while holding metadata, so it cannot publish stale and never needs
- /// to retry under sustained write traffic.
- ///
- /// 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> {
- self.prime_index_if_cold_with_hook(|| {})
- }
-
- /// `after_scan` is a deterministic test seam for mutations that land
- /// after file reads but before publication. Production always passes a
- /// no-op closure through [`Self::prime_index_if_cold`].
- pub(super) fn prime_index_if_cold_with_hook(
- &self,
- mut after_scan: impl FnMut(),
- ) -> Result<(), String> {
- let key = self.root_dir();
- if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {
- return Ok(());
- }
-
- let _build = self.locks.index_build.lock();
- if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {
- return Ok(());
- }
- self.locks.begin_index_build();
-
- // This is header-only O(threads) work. Do not use
- // `list_threads_unlocked`: legacy workspaces can make that measure and
- // append stats for every thread while metadata is held.
- let thread_ids: Vec<String> = {
- let _metadata = self.locks.metadata.lock();
- match self.thread_index_unlocked() {
- Ok(index) => index.into_keys().collect(),
- Err(error) => {
- self.locks.cancel_index_build();
- return Err(error);
- }
- }
- };
-
- let mut idx = InvertedIndex::new();
- for thread_id in &thread_ids {
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_lock.lock();
- 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);
- }
- }
- }
- after_scan();
-
- // Append finalization takes metadata too. Therefore every append is
- // either already in the journal drained here, or waits until after
- // publication and updates the now-warm cache directly.
- let _metadata = self.locks.metadata.lock();
- for (thread_id, message) in self.locks.finish_index_build() {
- idx.insert(&thread_id, message);
- }
- CONVERSATION_INDEX_CACHE.lock().insert(key, idx);
- Ok(())
- }
-
- /// Acquire an index that the caller has already warmed with
- /// [`Self::prime_index_if_cold`] and run `f` against it. The only
- /// production caller, `search_cross_thread_messages`, holds the root's
- /// lifecycle read guard across both calls, so purge cannot remove the
- /// entry between priming and access.
- pub(super) fn with_primed_index<R>(
- &self,
- f: impl FnOnce(&mut InvertedIndex) -> R,
- ) -> Result<R, String> {
- let key = self.root_dir();
- let mut cache = CONVERSATION_INDEX_CACHE.lock();
- let idx = cache
- .get_mut(&key)
- .ok_or_else(|| "conversation index missing after required prime".to_string())?;
- Ok(f(idx))
- }
-
- /// 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.root_dir.clone()
- }
-
- /// 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);
- }
- }
- }
-
- Ok(Self::threads_from_index(index))
- }
-
- /// Fold and repair thread metadata without inverting the lock order used
- /// by message mutations. Recovery reads take the target thread lock before
- /// metadata; a newly-created thread discovered between passes is handled
- /// by the next iteration.
- pub(super) fn list_threads_coordinated(&self) -> Result<Vec<ConversationThread>, String> {
- let mut unreadable = HashSet::new();
- loop {
- let (index, missing) = {
- let _metadata = self.locks.metadata.lock();
- let index = self.thread_index_unlocked()?;
- let missing = index
- .iter()
- .filter(|(_, entry)| {
- entry.message_count.is_none() || entry.last_message_at.is_none()
- })
- .filter(|(thread_id, _)| !unreadable.contains(*thread_id))
- .map(|(thread_id, _)| thread_id.clone())
- .collect::<Vec<_>>();
- (index, missing)
- };
- if missing.is_empty() {
- return Ok(Self::threads_from_index(index));
- }
-
- for thread_id in missing {
- let thread_lock = self.locks.thread(&thread_id);
- let _thread = thread_lock.lock();
- let _metadata = self.locks.metadata.lock();
- let index = self.thread_index_unlocked()?;
- let Some(entry) = index.get(&thread_id) else {
- continue;
- };
- if entry.message_count.is_some() && entry.last_message_at.is_some() {
- continue;
- }
- let Ok((count, last_message_at)) = self.measure_messages_unlocked(&thread_id)
- else {
- // Quarantine this thread for this invocation so it neither
- // blocks repairs for later threads nor causes the outer
- // loop to retry it forever. A future list call retries it.
- unreadable.insert(thread_id);
- continue;
- };
- let resolved_last = last_message_at.unwrap_or_else(|| entry.created_at.clone());
- append_jsonl(
- &self.ensure_root()?.join(THREADS_FILENAME),
- &ThreadLogEntry::Stats {
- thread_id,
- message_count: count,
- last_message_at: resolved_last,
- },
- )?;
- }
- }
- }
-
- fn threads_from_index(index: BTreeMap<String, ThreadIndexEntry>) -> Vec<ConversationThread> {
- 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)))
- });
- 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/crates/openhuman-core/src/memory/conversations/store/store_locks.rs b/crates/openhuman-core/src/memory/conversations/store/store_locks.rs
deleted file mode 100644
index 651d81e5fa..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store_locks.rs
+++ /dev/null
@@ -1,137 +0,0 @@
-//! Lock registry for the JSONL conversation store.
-//!
-//! A root owns shared metadata (`threads.jsonl`) and many independent message
-//! files. Keeping those synchronization scopes separate lets unrelated agent
-//! sessions write their message files concurrently while preserving atomic
-//! metadata appends and purge semantics.
-
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, Weak};
-
-use parking_lot::{Mutex, RwLock};
-
-use super::super::types::ConversationMessage;
-
-#[derive(Debug, Default)]
-pub(super) struct StoreLocks {
- /// Ordinary operations take a read guard; purge takes the write guard.
- pub(super) lifecycle: RwLock<()>,
- /// Serializes reads and appends of the root's shared `threads.jsonl`.
- pub(super) metadata: Mutex<()>,
- /// Only one cold scan may construct this root's in-memory index.
- pub(super) index_build: Mutex<()>,
- threads: Mutex<HashMap<String, Weak<Mutex<()>>>>,
- /// Appends completed while a cold scan is in flight. `None` means no scan
- /// is active, so the warm-cache path alone owns index maintenance.
- pending_index_appends: Mutex<Option<Vec<(String, ConversationMessage)>>>,
-}
-
-impl StoreLocks {
- pub(super) fn thread(&self, thread_id: &str) -> Arc<Mutex<()>> {
- let mut locks = self.threads.lock();
- locks.retain(|_, lock| lock.strong_count() > 0);
- if let Some(lock) = locks.get(thread_id).and_then(Weak::upgrade) {
- return lock;
- }
- let lock = Arc::new(Mutex::new(()));
- locks.insert(thread_id.to_string(), Arc::downgrade(&lock));
- lock
- }
-
- pub(super) fn begin_index_build(&self) {
- let previous = self.pending_index_appends.lock().replace(Vec::new());
- debug_assert!(previous.is_none(), "index builds must be serialized");
- }
-
- pub(super) fn record_index_append(&self, thread_id: &str, message: &ConversationMessage) {
- if let Some(pending) = self.pending_index_appends.lock().as_mut() {
- pending.push((thread_id.to_string(), message.clone()));
- }
- }
-
- pub(super) fn finish_index_build(&self) -> Vec<(String, ConversationMessage)> {
- self.pending_index_appends.lock().take().unwrap_or_default()
- }
-
- pub(super) fn cancel_index_build(&self) {
- self.pending_index_appends.lock().take();
- }
-
- /// Call only while holding the lifecycle write guard.
- pub(super) fn remove_thread(&self, thread_id: &str) {
- self.threads.lock().remove(thread_id);
- }
-
- /// Call only while holding the lifecycle write guard.
- pub(super) fn clear_threads(&self) {
- self.threads.lock().clear();
- }
-
- #[cfg(test)]
- pub(super) fn thread_count(&self) -> usize {
- self.threads
- .lock()
- .values()
- .filter(|lock| lock.strong_count() > 0)
- .count()
- }
-}
-
-/// Separate `ConversationStore::new` calls for the same root must coordinate.
-/// Weak entries avoid retaining one lock set for every temporary workspace a
-/// long-running process has ever touched.
-static ROOTS: LazyLock<Mutex<HashMap<PathBuf, Weak<StoreLocks>>>> =
- LazyLock::new(|| Mutex::new(HashMap::new()));
-
-pub(super) fn for_root(root: &Path) -> Arc<StoreLocks> {
- let root = normalized_root(root);
- let mut roots = ROOTS.lock();
- // A process may open many ephemeral workspaces over its lifetime. The
- // weak value avoids retaining each lock set; pruning dead values here also
- // prevents their path keys from making the registry itself grow forever.
- roots.retain(|_, locks| locks.strong_count() > 0);
- if let Some(existing) = roots.get(&root).and_then(Weak::upgrade) {
- return existing;
- }
- let locks = Arc::new(StoreLocks::default());
- roots.insert(root, Arc::downgrade(&locks));
- locks
-}
-
-/// Resolve aliases even before the conversation directory itself exists.
-/// Canonicalizing the nearest existing ancestor handles symlinks and `..`;
-/// the missing suffix is then appended without touching the filesystem.
-pub(super) fn normalized_root(root: &Path) -> PathBuf {
- let absolute;
- let root = if root.is_absolute() {
- root
- } else {
- absolute = std::env::current_dir()
- .map(|cwd| cwd.join(root))
- .unwrap_or_else(|_| root.to_path_buf());
- &absolute
- };
- if let Ok(canonical) = root.canonicalize() {
- return canonical;
- }
-
- let mut suffix = Vec::new();
- let mut ancestor = root;
- loop {
- if let Ok(canonical) = ancestor.canonicalize() {
- return suffix
- .iter()
- .rev()
- .fold(canonical, |path, component| path.join(component));
- }
- let Some(name) = ancestor.file_name() else {
- return root.to_path_buf();
- };
- suffix.push(name.to_os_string());
- let Some(parent) = ancestor.parent() else {
- return root.to_path_buf();
- };
- ancestor = parent;
- }
-}
diff --git a/crates/openhuman-core/src/memory/conversations/store/store_ops.rs b/crates/openhuman-core/src/memory/conversations/store/store_ops.rs
deleted file mode 100644
index 215eca8ec2..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store_ops.rs
+++ /dev/null
@@ -1,422 +0,0 @@
-//! 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::{
- is_deterministic_message_id, ConversationMessage, ConversationMessagePatch, ConversationThread,
- CreateConversationThread, CrossThreadHit,
-};
-use super::{
- append_jsonl, find_message_by_id, normalize_labels, read_jsonl, rewrite_jsonl,
- ConversationPurgeStats, ConversationStore, ThreadLogEntry, CONVERSATION_INDEX_CACHE,
- 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 _lifecycle = self.locks.lifecycle.read();
- let thread_lock = self.locks.thread(&request.id);
- let _thread = thread_lock.lock();
- let _metadata = self.locks.metadata.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 _lifecycle = self.locks.lifecycle.read();
- self.list_threads_coordinated()
- }
-
- /// Read every persisted message for a thread in append order.
- pub fn get_messages(&self, thread_id: &str) -> Result<Vec<ConversationMessage>, String> {
- let _lifecycle = self.locks.lifecycle.read();
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_lock.lock();
- {
- let _metadata = self.locks.metadata.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 the root lifecycle read guard and
- /// `CONVERSATION_INDEX_CACHE`, with no metadata or thread lock.
- ///
- /// **Cold path (first access):** snapshots the thread list under
- /// the root metadata lock (brief), then releases it before reading each
- /// JSONL file under its per-thread lock. This avoids blocking unrelated
- /// threads during the potentially-long rebuild. Appends completed during
- /// that scan are journaled and folded into the index atomically at
- /// publication.
- pub fn search_cross_thread_messages(
- &self,
- query: &str,
- limit: usize,
- exclude_thread_id: Option<&str>,
- ) -> Result<Vec<CrossThreadHit>, String> {
- // Warm the index without the metadata 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.
- let _lifecycle = self.locks.lifecycle.read();
- self.prime_index_if_cold()?;
- self.with_primed_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.
- ///
- /// Idempotent for the ids the core mints deterministically
- /// ([`is_deterministic_message_id`]): when the thread already holds a row
- /// with that id, nothing is written (no message row, no stat bump, no index
- /// insert) and the stored row is returned exactly as a fresh append would
- /// return its input. Two writers can legitimately persist the same reply —
- /// background delivery and the client that
- /// also persists the `chat_done` it announced (#5933) — and a thread must
- /// never carry two messages under one id (the frontend keys React and
- /// assistant-ui resources by it).
- ///
- /// The lookup is deliberately narrow. Every other id in the store is
- /// UUID-fresh by construction and cannot be re-presented, so it must not
- /// pay to have that verified: a lookup on *every* append would put a scan
- /// of the thread's transcript on every hot write and make growing a thread
- /// quadratic.
- pub fn append_message(
- &self,
- thread_id: &str,
- message: ConversationMessage,
- ) -> Result<ConversationMessage, String> {
- let _lifecycle = self.locks.lifecycle.read();
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_lock.lock();
- {
- let _metadata = self.locks.metadata.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 is_deterministic_message_id(&message.id) {
- if let Some(existing) = find_message_by_id(&path, &message.id)? {
- return Ok(existing);
- }
- }
- 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 _metadata = self.locks.metadata.lock();
- // The transcript row is already durable. Publish it to an active
- // cold-build journal and any warm cache before the derived stats
- // append, which may fail independently.
- self.locks.record_index_append(thread_id, &message);
- let mut cache = CONVERSATION_INDEX_CACHE.lock();
- if let Some(idx) = cache.get_mut(&self.root_dir()) {
- idx.insert(thread_id, message.clone());
- }
- drop(cache);
- 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(),
- },
- )?;
- }
- 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 _lifecycle = self.locks.lifecycle.read();
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_lock.lock();
- let _metadata = self.locks.metadata.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 _lifecycle = self.locks.lifecycle.read();
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_lock.lock();
- let _metadata = self.locks.metadata.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 _lifecycle = self.locks.lifecycle.read();
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_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)
- }
-
- /// Truncate a thread's message log at `message_id`: drop that message and
- /// every message after it (append order == chronological order), keeping
- /// everything before it. Backs `threads.edit_message` / `threads.regenerate`
- /// (edit/regenerate rewrite the tail of a conversation, never the middle).
- ///
- /// Returns the number of messages removed, or `Ok(None)` if `message_id`
- /// is not present in the thread (a stale/unknown cut point — the caller
- /// should treat this as "nothing to truncate", not silently drop the
- /// whole log).
- ///
- /// Evicts the thread from the cross-thread search index the same way
- /// [`Self::delete_thread`] does: the index has no per-message removal, so
- /// the conservative move is to drop the whole thread's postings rather
- /// than search a stale truncated message back into a hit. The next
- /// cross-thread search that touches this thread re-primes it from the
- /// (now-truncated) file on disk.
- pub fn delete_messages_from(
- &self,
- thread_id: &str,
- message_id: &str,
- ) -> Result<Option<usize>, String> {
- let _lifecycle = self.locks.lifecycle.read();
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_lock.lock();
- let path = self.thread_messages_path(thread_id);
- let messages = read_jsonl::<ConversationMessage>(&path)?;
- let Some(cut_at) = messages.iter().position(|m| m.id == message_id) else {
- return Ok(None);
- };
- let removed = messages.len() - cut_at;
- let kept = &messages[..cut_at];
- rewrite_jsonl(&path, kept)?;
- // The compact stat trail in `threads.jsonl` (`MessageAppended`/
- // `Stats`) only ever grows via `append_message`'s increment — it has
- // no notion of a truncation. Append an authoritative `Stats` snapshot
- // now so `list_threads`'s `message_count`/`last_message_at` reflect
- // the post-truncation file immediately, instead of staying
- // overcounted until this thread is next quarantined as unreadable
- // and rescanned (which never happens on its own — see
- // `list_threads_coordinated`, which only remeasures a `None` count).
- let last_message_at = kept.last().map(|m| m.created_at.clone());
- {
- let _metadata = self.locks.metadata.lock();
- let resolved_last = match last_message_at {
- Some(ts) => ts,
- None => self
- .thread_summary_unlocked(thread_id)?
- .map(|t| t.created_at)
- .unwrap_or_default(),
- };
- append_jsonl(
- &self.ensure_root()?.join(THREADS_FILENAME),
- &ThreadLogEntry::Stats {
- thread_id: thread_id.to_string(),
- message_count: kept.len(),
- last_message_at: resolved_last,
- },
- )?;
- }
- {
- let mut cache = CONVERSATION_INDEX_CACHE.lock();
- if let Some(idx) = cache.get_mut(&self.root_dir()) {
- idx.remove_thread(thread_id);
- }
- }
- Ok(Some(removed))
- }
-
- /// 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> {
- // Deletion also evicts the thread's lock entry. Exclusive lifecycle
- // ownership prevents a new operation from retaining the old lock
- // while the registry entry is replaced.
- let _lifecycle = self.locks.lifecycle.write();
- let thread_lock = self.locks.thread(thread_id);
- let _thread = thread_lock.lock();
- {
- let _metadata = self.locks.metadata.lock();
- if !self.thread_exists_unlocked(thread_id)? {
- self.locks.remove_thread(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);
- let remove_result = match fs::remove_file(&messages_path) {
- Ok(()) => Ok(()),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
- Err(error) => Err(format!(
- "delete conversation messages {}: {error}",
- messages_path.display()
- )),
- };
- // Evict on every path after the tombstone is durable, including a
- // filesystem deletion error. The lifecycle write guard prevents a new
- // operation from observing a replacement lock before this one drops.
- self.locks.remove_thread(thread_id);
- // 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);
- }
- }
- remove_result?;
- Ok(true)
- }
-
- /// Wipe the entire conversation directory and re-create an empty layout.
- pub fn purge_threads(&self) -> Result<ConversationPurgeStats, String> {
- let _lifecycle = self.locks.lifecycle.write();
- let _metadata = self.locks.metadata.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);
- }
- self.locks.clear_threads();
- Ok(stats)
- }
-}
diff --git a/crates/openhuman-core/src/memory/conversations/store/store_tests.rs b/crates/openhuman-core/src/memory/conversations/store/store_tests.rs
deleted file mode 100644
index 7fbfaf7822..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store_tests.rs
+++ /dev/null
@@ -1,602 +0,0 @@
-//! 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 append_message_is_idempotent_by_message_id() {
- let (_temp, store) = make_store();
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: "t".to_string(),
- title: "Conversation".to_string(),
- created_at: "2026-04-10T12:00:00Z".to_string(),
- labels: None,
- personality_id: None,
- })
- .expect("ensure thread");
- let first = ConversationMessage {
- id: "agent:run-1".to_string(),
- content: "first".to_string(),
- message_type: "text".to_string(),
- extra_metadata: json!({}),
- sender: "agent".to_string(),
- created_at: "2026-04-10T12:01:00Z".to_string(),
- };
- store.append_message("t", first.clone()).expect("append");
-
- // A second writer racing for the same id (the client persisting the
- // `chat_done` an autonomous run already persisted itself — #5933).
- let returned = store
- .append_message(
- "t",
- ConversationMessage {
- content: "second".to_string(),
- created_at: "2026-04-10T12:02:00Z".to_string(),
- ..first
- },
- )
- .expect("append again");
-
- // The stored row wins, and is what the second writer gets back.
- assert_eq!(returned.content, "first");
- assert_eq!(returned.created_at, "2026-04-10T12:01:00Z");
- let messages = store.get_messages("t").expect("get messages");
- assert_eq!(messages.len(), 1, "one id, one row");
- assert_eq!(messages[0].content, "first");
- // The no-op append did not bump the stat trail either.
- let threads = store.list_threads().expect("list threads");
- assert_eq!(threads[0].message_count, 1);
- assert_eq!(threads[0].last_message_at, "2026-04-10T12:01:00Z");
-}
-
-#[test]
-fn append_message_does_not_dedupe_client_generated_ids() {
- // The idempotency lookup is scoped to the ids the core mints
- // deterministically. Client-generated ids are UUID-fresh per message, so
- // paying a transcript scan to verify that on every append would make the
- // per-thread write path quadratic — the store takes them at face value
- // instead.
- let (_temp, store) = make_store();
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: "t".to_string(),
- title: "Conversation".to_string(),
- created_at: "2026-04-10T12:00:00Z".to_string(),
- labels: None,
- personality_id: None,
- })
- .expect("ensure thread");
- let message = ConversationMessage {
- id: "user:5f1d0c3e-1f8b-4c1a-9c2e-2a7b6d4e8f90".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(),
- };
- store.append_message("t", message.clone()).expect("append");
- store.append_message("t", message).expect("append again");
-
- assert_eq!(store.get_messages("t").expect("get messages").len(), 2);
-}
-
-#[test]
-fn append_message_idempotency_ignores_an_id_quoted_inside_content() {
- // The lookup narrows candidate lines by raw text before parsing them; a
- // message that merely *quotes* another message's id must not be mistaken
- // for that message and swallow the real append.
- let (_temp, store) = make_store();
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: "t".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(
- "t",
- ConversationMessage {
- id: "user:1".to_string(),
- content: "agent:run-9".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 quoting message");
- let stored = store
- .append_message(
- "t",
- ConversationMessage {
- id: "agent:run-9".to_string(),
- content: "the real reply".to_string(),
- message_type: "text".to_string(),
- extra_metadata: json!({}),
- sender: "agent".to_string(),
- created_at: "2026-04-10T12:02:00Z".to_string(),
- },
- )
- .expect("append reply");
-
- assert_eq!(stored.content, "the real reply");
- let messages = store.get_messages("t").expect("get messages");
- assert_eq!(messages.len(), 2);
- assert_eq!(messages[1].id, "agent:run-9");
-}
-
-#[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-reflection-thread".to_string(),
- title: "Legacy Reflection Chat".to_string(),
- created_at: "2026-04-10T12:00:00Z".to_string(),
- labels: Some(vec![
- "from_reflection".to_string(),
- "subconscious_tick".to_string(),
- "subconscious".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-reflection-thread")
- .unwrap();
- assert_eq!(legacy.labels, vec!["general"]);
- }
- {
- 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/crates/openhuman-core/src/memory/conversations/store/store_tests_late.rs b/crates/openhuman-core/src/memory/conversations/store/store_tests_late.rs
deleted file mode 100644
index 41d0167b05..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store_tests_late.rs
+++ /dev/null
@@ -1,725 +0,0 @@
-use super::*;
-use std::sync::Arc;
-
-#[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");
-}
-
-#[test]
-fn one_hundred_agent_threads_use_independent_message_locks() {
- let temp = TempDir::new().unwrap();
- let store = ConversationStore::new(temp.path().to_path_buf());
- let root_lock = store.lock_identity_for_test();
- let mut message_locks = std::collections::HashSet::new();
- let mut retained_locks = Vec::new();
-
- for index in 0..100 {
- let clone = ConversationStore::new(temp.path().to_path_buf());
- assert_eq!(clone.lock_identity_for_test(), root_lock);
- let lock = clone.locks.thread(&format!("agent-{index}"));
- assert!(message_locks.insert(Arc::as_ptr(&lock) as usize));
- retained_locks.push(lock);
- }
-
- assert_eq!(message_locks.len(), 100);
-}
-
-#[test]
-fn equivalent_workspace_paths_share_the_same_lock_registry_entry() {
- let temp = TempDir::new().unwrap();
- let child = temp.path().join("child");
- std::fs::create_dir(&child).unwrap();
-
- let direct = ConversationStore::new(temp.path().to_path_buf());
- let dotted = ConversationStore::new(child.join(".."));
-
- assert_eq!(
- direct.lock_identity_for_test(),
- dotted.lock_identity_for_test()
- );
- assert_eq!(direct.root_dir(), dotted.root_dir());
-}
-
-#[test]
-fn nonexistent_relative_and_absolute_workspaces_share_store_identity() {
- let relative = PathBuf::from(format!("target/store-alias-{}", uuid::Uuid::new_v4()));
- let absolute = std::env::current_dir().unwrap().join(&relative);
-
- let relative_store = ConversationStore::new(relative);
- let absolute_store = ConversationStore::new(absolute);
-
- assert_eq!(
- relative_store.lock_identity_for_test(),
- absolute_store.lock_identity_for_test()
- );
- assert_eq!(relative_store.root_dir(), absolute_store.root_dir());
-}
-
-#[cfg(unix)]
-#[test]
-fn symlinked_workspace_paths_share_the_same_lock_registry_entry() {
- let temp = TempDir::new().unwrap();
- let workspace = temp.path().join("workspace");
- let alias = temp.path().join("alias");
- std::fs::create_dir(&workspace).unwrap();
- std::os::unix::fs::symlink(&workspace, &alias).unwrap();
-
- let direct = ConversationStore::new(workspace);
- let linked = ConversationStore::new(alias);
-
- assert_eq!(
- direct.lock_identity_for_test(),
- linked.lock_identity_for_test()
- );
- assert_eq!(direct.root_dir(), linked.root_dir());
-}
-
-// ── 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
-/// moved the rebuild outside that lock (`prime_index_if_cold`). The current
-/// store additionally takes only the target thread lock while reading each
-/// transcript, so unrelated appends complete independently.
-///
-/// 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
-/// serialized through one shared lock.
-#[test]
-fn search_cold_rebuild_does_not_block_concurrent_append() {
- use std::sync::mpsc;
- 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();
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: "t2".to_string(),
- title: "Concurrent append target".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();
-
- let (scanned_tx, scanned_rx) = mpsc::channel();
- let (release_tx, release_rx) = mpsc::channel();
- let search_handle = thread::spawn(move || {
- let _lifecycle = store_search.locks.lifecycle.read();
- store_search.prime_index_if_cold_with_hook(|| {
- scanned_tx.send(()).unwrap();
- release_rx.recv().unwrap();
- })?;
- store_search.with_primed_index(|idx| idx.search("seed message", 5, None))
- });
-
- scanned_rx
- .recv_timeout(Duration::from_secs(5))
- .expect("cold rebuild did not reach the post-scan test seam");
- let (tx, rx) = mpsc::channel();
- thread::spawn(move || {
- let result = store_append.append_message(
- "t2",
- 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);
- });
-
- // The unrelated append must finish while publication is deliberately
- // paused. Releasing the rebuild first would let root-wide serialization
- // pass this test eventually and prove nothing about overlap.
- let append_result = rx
- .recv_timeout(Duration::from_secs(5))
- .expect("unrelated append blocked behind a cold rebuild");
- assert!(
- append_result.is_ok(),
- "append failed: {:?}",
- append_result.err()
- );
- release_tx.send(()).unwrap();
-
- let search_result = search_handle.join().expect("search thread panicked");
- assert!(
- search_result.is_ok(),
- "search failed: {:?}",
- search_result.err()
- );
- let appended = store
- .search_cross_thread_messages("written during cold rebuild", 10, None)
- .unwrap();
- assert!(
- appended
- .iter()
- .any(|hit| hit.message_id == "concurrent-append"),
- "completed append was omitted from index: {appended:?}"
- );
-}
-
-#[test]
-fn delete_during_cold_prime_cannot_republish_stale_messages() {
- use std::sync::mpsc;
- use std::thread;
- use std::time::Duration;
-
- let (temp, store) = make_store();
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: "t1".to_string(),
- title: "Delete race".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: "hello from a soon-deleted thread".to_string(),
- message_type: "text".to_string(),
- extra_metadata: serde_json::json!({}),
- sender: "user".to_string(),
- created_at: "2026-04-10T12:01:00Z".to_string(),
- },
- )
- .unwrap();
- let store_prime = store.clone();
- let store_delete = store.clone();
- let root = store.root_dir();
- CONVERSATION_INDEX_CACHE.lock().remove(&root);
-
- let (scanned_tx, scanned_rx) = mpsc::channel();
- let (release_tx, release_rx) = mpsc::channel();
- let prime = thread::spawn(move || {
- let _lifecycle = store_prime.locks.lifecycle.read();
- store_prime.prime_index_if_cold_with_hook(|| {
- scanned_tx.send(()).unwrap();
- release_rx.recv().unwrap();
- })
- });
- scanned_rx
- .recv_timeout(Duration::from_secs(5))
- .expect("prime did not reach post-scan seam");
-
- let (delete_tx, delete_rx) = mpsc::channel();
- thread::spawn(move || {
- let result = store_delete.delete_thread("t1", "2026-04-10T12:02:00Z");
- delete_tx.send(result).unwrap();
- });
- assert!(
- delete_rx.recv_timeout(Duration::from_millis(100)).is_err(),
- "delete must wait for the cold prime's lifecycle read guard"
- );
- release_tx.send(()).unwrap();
- prime.join().unwrap().unwrap();
- assert!(delete_rx
- .recv_timeout(Duration::from_secs(5))
- .unwrap()
- .unwrap());
-
- let hits = store
- .search_cross_thread_messages("hello", 10, None)
- .unwrap();
- assert!(hits.is_empty(), "deleted content was republished: {hits:?}");
- drop(temp);
-}
-
-#[test]
-fn delete_and_purge_evict_historical_thread_locks() {
- let (_temp, store) = make_store();
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: "t1".to_string(),
- title: "Eviction".to_string(),
- created_at: "2026-04-10T12:00:00Z".to_string(),
- labels: None,
- personality_id: None,
- })
- .unwrap();
- let t1_lock = store.locks.thread("t1");
- assert_eq!(store.thread_lock_count_for_test(), 1);
- assert!(store.delete_thread("t1", "2026-04-10T12:02:00Z").unwrap());
- assert_eq!(store.thread_lock_count_for_test(), 0);
- drop(t1_lock);
-
- let historical_locks = (0..100)
- .map(|index| store.locks.thread(&format!("historical-{index}")))
- .collect::<Vec<_>>();
- assert_eq!(store.thread_lock_count_for_test(), 100);
- store.purge_threads().unwrap();
- assert_eq!(store.thread_lock_count_for_test(), 0);
- drop(historical_locks);
-}
-
-// ── 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`, formerly while holding `CONVERSATION_STORE_LOCK` and now
-/// while holding the root's metadata 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 metadata lock, then reads each JSONL file under its
-/// per-thread 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 the metadata 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()
- );
-}
-
-#[test]
-fn delete_error_still_evicts_tombstoned_thread_from_warm_index() {
- let (_temp, store) = make_store();
- store
- .ensure_thread(CreateConversationThread {
- parent_thread_id: None,
- id: "delete-error".to_string(),
- title: "Delete error".to_string(),
- created_at: "2026-04-10T12:00:00Z".to_string(),
- labels: None,
- personality_id: None,
- })
- .unwrap();
- store
- .append_message(
- "delete-error",
- ConversationMessage {
- id: "indexed-before-delete-error".to_string(),
- content: "must disappear after tombstone".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
- .search_cross_thread_messages("disappear after tombstone", 10, None)
- .unwrap()
- .len(),
- 1
- );
-
- // A directory at the transcript path makes remove_file fail after the
- // metadata tombstone has already become durable.
- let transcript = store.thread_messages_path("delete-error");
- std::fs::remove_file(&transcript).unwrap();
- std::fs::create_dir(&transcript).unwrap();
- assert!(store
- .delete_thread("delete-error", "2026-04-10T12:02:00Z")
- .is_err());
-
- let hits = store
- .search_cross_thread_messages("disappear after tombstone", 10, None)
- .unwrap();
- assert!(
- hits.is_empty(),
- "tombstoned thread remained indexed: {hits:?}"
- );
-}
-
-#[path = "store_concurrency_tests.rs"]
-mod concurrency;
diff --git a/crates/openhuman-core/src/memory/conversations/store/store_tests_more.rs b/crates/openhuman-core/src/memory/conversations/store/store_tests_more.rs
deleted file mode 100644
index dd19b0796c..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/store_tests_more.rs
+++ /dev/null
@@ -1,429 +0,0 @@
-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/crates/openhuman-core/src/memory/conversations/store/tokenize.rs b/crates/openhuman-core/src/memory/conversations/store/tokenize.rs
deleted file mode 100644
index 54c0847206..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/tokenize.rs
+++ /dev/null
@@ -1,287 +0,0 @@
-//! 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. **Full-width ASCII → ASCII** — folds the full-width variants
-//! (`ABC` → `abc`, U+FF01..=U+FF5E, plus the ideographic space) so an
-//! ASCII query retrieves full-width Latin content, matching NFKC.
-//! 6. **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(ascii) = fullwidth_to_ascii(c) {
- out.push(ascii);
- } else if let Some(full) = halfwidth_to_fullwidth(c) {
- out.push(full);
- } else {
- out.push(c);
- }
- }
- out
-}
-
-/// Full-width ASCII variants (U+FF01..=U+FF5E) → their ASCII originals, plus
-/// the ideographic space (U+3000) → an ordinary space.
-///
-/// These are NFKC compatibility folds — `ABC` normalizes to `ABC` under
-/// NFKC — and the pipeline this port reproduces ran NFKD→NFKC, so without
-/// this arm an ASCII query could not retrieve indexed full-width Latin
-/// content (common in CJK text, where full-width forms are produced by the
-/// IME). The offset is uniform: full-width `!` (U+FF01) through `~`
-/// (U+FF5E) sit exactly `0xFEE0` above `!`..=`~`. Lowercasing has already
-/// happened by the time this runs, and `char::to_lowercase` maps full-width
-/// `A`→`a` within the full-width block, so the subtraction lands on the
-/// lowercase ASCII letter directly. Disjoint from the half-width katakana
-/// range (U+FF61..) handled below.
-fn fullwidth_to_ascii(c: char) -> Option<char> {
- match c {
- '\u{FF01}'..='\u{FF5E}' => char::from_u32(c as u32 - 0xFEE0),
- '\u{3000}' => Some(' '),
- _ => None,
- }
-}
-
-/// 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/crates/openhuman-core/src/memory/conversations/store/tokenize_tests.rs b/crates/openhuman-core/src/memory/conversations/store/tokenize_tests.rs
deleted file mode 100644
index 14b201dee9..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/tokenize_tests.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-//! 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
-}
-
-#[test]
-fn normalize_folds_fullwidth_ascii() {
- // NFKC folds the full-width ASCII variants; the port must too, or an
- // ASCII query cannot retrieve indexed full-width Latin content.
- assert_eq!(normalize("ABC"), "abc");
- assert_eq!(normalize("hello world"), "hello world");
- assert_eq!(normalize("123!"), "123!");
- // Idempotent: the fold lands on plain ASCII, which passes through.
- assert_eq!(normalize(&normalize("ABC")), "abc");
-}
diff --git a/crates/openhuman-core/src/memory/conversations/store/types.rs b/crates/openhuman-core/src/memory/conversations/store/types.rs
deleted file mode 100644
index 6510c7b356..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/types.rs
+++ /dev/null
@@ -1,165 +0,0 @@
-//! 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,
-}
-
-/// Prefix of the message ids the core mints **deterministically** rather than
-/// from a fresh UUID.
-///
-/// Only such an id can be presented to the store twice by two different
-/// writers, so it is also the marker
-/// [`is_deterministic_message_id`] keys the store's idempotency lookup on.
-pub const DETERMINISTIC_MESSAGE_ID_PREFIX: &str = "agent:";
-
-/// The id an autonomous run's closing reply is stored under.
-///
-/// Two writers legitimately persist that one reply — the core's
-/// background-delivery path and the client that also persists the
-/// `chat_done` the run announces (`ChatRuntimeProvider` mirrors this shape for
-/// `client_id: "system"` turns) — so both must derive the same id and the store
-/// must collapse the second write onto the first (#5933).
-pub fn run_reply_message_id(run_id: &str) -> String {
- format!("{DETERMINISTIC_MESSAGE_ID_PREFIX}{run_id}")
-}
-
-/// Whether `id` is one the core mints deterministically, i.e. one a second
-/// writer can legitimately present again.
-///
-/// This is what buys back the constant-time append path: every other id in the
-/// store is UUID-fresh by construction (`user:<uuid>`, `<sender>:<uuid>`), can
-/// never be re-presented, and so must not pay for a duplicate lookup. The
-/// `agent:<uuid>` ids the subagent/worker-thread writers mint do match — they
-/// pay for a lookup they can never hit, which is one cheap scan of a
-/// two-message worker transcript.
-pub fn is_deterministic_message_id(id: &str) -> bool {
- id.starts_with(DETERMINISTIC_MESSAGE_ID_PREFIX)
-}
-
-/// The run/request id [`run_reply_message_id`] minted `id` from, or `None`
-/// when `id` is not a deterministic reply id (see
-/// [`is_deterministic_message_id`]).
-///
-/// Backs `threads.edit_message` / `threads.regenerate`: an assistant reply's
-/// store id is the one place the conversation-store id space and the
-/// model-facing transcript's `request_id` space provably correlate, so
-/// recovering the run id from the store id is how a UI message id resolves
-/// to a transcript cut point.
-pub fn reply_run_id(id: &str) -> Option<&str> {
- id.strip_prefix(DETERMINISTIC_MESSAGE_ID_PREFIX)
-}
-
-#[cfg(test)]
-#[path = "types_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/conversations/store/types_tests.rs b/crates/openhuman-core/src/memory/conversations/store/types_tests.rs
deleted file mode 100644
index e6bee4eac6..0000000000
--- a/crates/openhuman-core/src/memory/conversations/store/types_tests.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-//! 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());
-}
-
-#[test]
-fn run_reply_id_is_deterministic_and_recognised_as_such() {
- // The background-delivery producer and the predicate the store
- // gates its idempotency lookup on must agree, or the two writers of an
- // autonomous reply stop collapsing onto one row (#5933).
- assert_eq!(run_reply_message_id("run-7"), "agent:run-7");
- assert!(is_deterministic_message_id(&run_reply_message_id("run-7")));
-}
-
-#[test]
-fn client_generated_ids_are_not_deterministic() {
- // These are UUID-fresh per message, so they can never be re-presented and
- // must keep the constant-time append path.
- assert!(!is_deterministic_message_id(
- "user:5f1d0c3e-1f8b-4c1a-9c2e-2a7b6d4e8f90"
- ));
- assert!(!is_deterministic_message_id(
- "assistant:5f1d0c3e-1f8b-4c1a-9c2e-2a7b6d4e8f90"
- ));
-}