Skip to content

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

fix(memory): three review findings in the migrated-home surfaces

Shanu5ae778913f9f
diff --git a/src/openhuman/memory/conversations/store/tokenize.rs b/src/openhuman/memory/conversations/store/tokenize.rs
index b9282a34a1..54c0847206 100644
--- a/src/openhuman/memory/conversations/store/tokenize.rs
+++ b/src/openhuman/memory/conversations/store/tokenize.rs
@@ -43,7 +43,10 @@
//! 4. **Non-decomposing fold** — small per-letter table for decorated letters
//! that have no canonical base (Polish ł, German ß, Norwegian ø, Icelandic
//! þ/ð, Latin æ/œ, Turkish ı, Croatian đ, Maltese ħ, Sami ŋ).
-//! 5. **Half-width → full-width katakana** — unifies the half-width and
+//! 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
@@ -66,6 +69,8 @@ pub fn normalize(text: &str) -> String {
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 {
@@ -75,6 +80,27 @@ pub fn normalize(text: &str) -> String {
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`
diff --git a/src/openhuman/memory/conversations/store/tokenize_tests.rs b/src/openhuman/memory/conversations/store/tokenize_tests.rs
index 67e617600a..14b201dee9 100644
--- a/src/openhuman/memory/conversations/store/tokenize_tests.rs
+++ b/src/openhuman/memory/conversations/store/tokenize_tests.rs
@@ -106,3 +106,14 @@ fn is_cjk_classifies_common_scripts() {
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/src/openhuman/memory/sources/status.rs b/src/openhuman/memory/sources/status.rs
index 2ba65478fe..3563927c3a 100644
--- a/src/openhuman/memory/sources/status.rs
+++ b/src/openhuman/memory/sources/status.rs
@@ -127,7 +127,15 @@ pub(crate) fn source_id_prefix(source: &MemorySourceEntry) -> String {
SourceKind::Composio => {
match (source.toolkit.as_deref(), source.connection_id.as_deref()) {
(Some(toolkit), Some(connection_id)) => format!("{toolkit}:{connection_id}:"),
- (Some(toolkit), None) => format!("{toolkit}:"),
+ // A connection-less entry gets an unmatchable prefix, not the
+ // bare `{toolkit}:` — that widened prefix matched *every*
+ // connection of the toolkit, so a malformed or legacy Gmail
+ // source reported another Gmail connection's ingest counts as
+ // its own. Chunk ids are `{toolkit}:{connection_id}:{doc}`, so
+ // an entry with no connection id has no rows it could name;
+ // the driver's zero-fill guarantee turns the non-match into an
+ // idle row. Same sentinel style as `__no_toolkit__` below.
+ (Some(toolkit), None) => format!("{toolkit}:__no_connection__:"),
(None, _) => "__no_toolkit__:".to_string(),
}
}
diff --git a/src/openhuman/memory/sources/status_tests.rs b/src/openhuman/memory/sources/status_tests.rs
index 140d2c353d..6842ac29cb 100644
--- a/src/openhuman/memory/sources/status_tests.rs
+++ b/src/openhuman/memory/sources/status_tests.rs
@@ -47,8 +47,11 @@ fn source_id_prefix_dispatch() {
entry.connection_id = Some("conn-1".into());
assert_eq!(source_id_prefix(&entry), "gmail:conn-1:");
+ // Connection-less entries must not widen to the bare toolkit prefix --
+ // that matched every gmail connection's chunks, so a malformed source
+ // reported another connection's counts as its own.
entry.connection_id = None;
- assert_eq!(source_id_prefix(&entry), "gmail:");
+ assert_eq!(source_id_prefix(&entry), "gmail:__no_connection__:");
entry.toolkit = None;
assert_eq!(source_id_prefix(&entry), "__no_toolkit__:");
diff --git a/src/openhuman/memory/tools/search/vector_search.rs b/src/openhuman/memory/tools/search/vector_search.rs
index 6109286872..8418d93244 100644
--- a/src/openhuman/memory/tools/search/vector_search.rs
+++ b/src/openhuman/memory/tools/search/vector_search.rs
@@ -161,10 +161,17 @@ fn mmr_select(candidates: &[MmrCandidate<'_>], limit: usize, lambda: f64) -> Vec
let max_sim_to_selected = if selected_embeddings.is_empty() {
0.0
} else {
+ // Seeded with NEG_INFINITY, not 0.0: when every selected
+ // similarity is negative, a 0.0 seed would win the fold and
+ // report an anti-correlated candidate as orthogonal — the
+ // exact collapse the `[0.0, 1.0]` note on
+ // [`cosine_similarity`] warns against reintroducing. The
+ // iterator is non-empty on this branch, so the seed never
+ // escapes.
selected_embeddings
.iter()
.map(|sel| cosine_similarity(candidate.embedding, sel))
- .fold(0.0_f64, f64::max)
+ .fold(f64::NEG_INFINITY, f64::max)
};
let mmr_score = lambda * candidate.relevance - (1.0 - lambda) * max_sim_to_selected;
if mmr_score > best_mmr {
@@ -441,3 +448,7 @@ impl Tool for MemoryVectorSearchTool {
Ok(ToolResult::success(output))
}
}
+
+#[cfg(test)]
+#[path = "vector_search_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/tools/search/vector_search_tests.rs b/src/openhuman/memory/tools/search/vector_search_tests.rs
new file mode 100644
index 0000000000..1c8fd9f589
--- /dev/null
+++ b/src/openhuman/memory/tools/search/vector_search_tests.rs
@@ -0,0 +1,59 @@
+//! MMR selection tests.
+//!
+//! The regression here pins the sign-preserving contract documented on
+//! [`cosine_similarity`]: an anti-correlated candidate is *more* diverse than
+//! an orthogonal one, and the redundancy fold must not clamp that away.
+
+use super::*;
+
+/// Unit-ish vectors chosen so cosine similarity is exactly their dot product.
+fn candidate<'a>(embedding: &'a [f32], relevance: f64, index: usize) -> MmrCandidate<'a> {
+ MmrCandidate {
+ index,
+ embedding,
+ relevance,
+ }
+}
+
+#[test]
+fn mmr_prefers_anti_correlated_over_orthogonal_at_equal_relevance() {
+ // First pick is the highest-relevance candidate: `a` at [1, 0].
+ // The two remaining candidates tie on relevance; `anti` at [-1, 0] has
+ // similarity -1.0 to the selection, `ortho` at [0, 1] has 0.0. With the
+ // fold seeded at 0.0 both reported 0.0 and the tie broke by index order,
+ // selecting `ortho`; seeded at NEG_INFINITY the negative survives and the
+ // MMR penalty term rewards `anti` as the more diverse pick.
+ let a: [f32; 2] = [1.0, 0.0];
+ let ortho: [f32; 2] = [0.0, 1.0];
+ let anti: [f32; 2] = [-1.0, 0.0];
+ let candidates = vec![
+ candidate(&a, 1.0, 0),
+ candidate(&ortho, 0.5, 1),
+ candidate(&anti, 0.5, 2),
+ ];
+
+ let picked = mmr_select(&candidates, 2, 0.5);
+
+ assert_eq!(picked.len(), 2);
+ assert_eq!(picked[0].index, 0, "highest relevance is selected first");
+ assert_eq!(
+ picked[1].index, 2,
+ "with only negative similarity to the selection, the anti-correlated \
+ candidate must out-score the orthogonal one instead of tying at a \
+ clamped 0.0"
+ );
+}
+
+#[test]
+fn mmr_first_pick_is_pure_relevance() {
+ // With nothing selected yet there is no redundancy term; the seed change
+ // must not leak into the first iteration.
+ let a: [f32; 2] = [1.0, 0.0];
+ let b: [f32; 2] = [0.0, 1.0];
+ let candidates = vec![candidate(&a, 0.2, 0), candidate(&b, 0.9, 1)];
+
+ let picked = mmr_select(&candidates, 1, 0.7);
+
+ assert_eq!(picked.len(), 1);
+ assert_eq!(picked[0].index, 1);
+}