Skip to content

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

fix(archivist): stop persisting, embedding and enriching from a heuristic recap

Shanu6df61b210c44
diff --git a/src/openhuman/agent/harness/archivist/lifecycle.rs b/src/openhuman/agent/harness/archivist/lifecycle.rs
index 8817a0a1e2..aceb0dafda 100644
--- a/src/openhuman/agent/harness/archivist/lifecycle.rs
+++ b/src/openhuman/agent/harness/archivist/lifecycle.rs
@@ -21,6 +21,23 @@ use std::time::{SystemTime, UNIX_EPOCH};
/// question of the same role.
const RECAP_INFERENCE_ROLE: &str = "summarization";
+/// Whether a finalize-time recap may be handed to a consumer that will treat
+/// it as real conversation content.
+///
+/// `from_llm == false` means [`ArchivistHook::summarize_entries`] returned the
+/// `boundary::fallback_summary` bookend — the segment's first and last 200
+/// characters joined by a pipe. That string is not a summary of anything; it
+/// is a placeholder that reads like one.
+///
+/// The emptiness term is a belt: a successful LLM recap is already non-empty
+/// by construction, because `summarize_entries` only reports `true` from the
+/// `Ok(output) if !output.content.is_empty()` arm. It fires on a shape that
+/// cannot occur today, and exists so a future arm cannot quietly reintroduce
+/// one.
+pub(super) fn recap_is_usable(from_llm: bool, summary: &str) -> bool {
+ from_llm && !summary.trim().is_empty()
+}
+
impl ArchivistHook {
/// Create an Archivist hook over the workspace's bound memory driver.
///
@@ -301,9 +318,16 @@ impl ArchivistHook {
/// Called when a segment is closed.
///
- /// Produces a segment recap (LLM if a chat provider is configured,
- /// otherwise the heuristic fallback), embeds the recap, extracts
- /// heuristic events, and updates the user profile.
+ /// Produces a segment recap, extracts heuristic events, updates the user
+ /// profile, and pipes the segment's raw turns into the memory tree.
+ ///
+ /// What happens to the recap depends on where it came from (#6156). An LLM
+ /// recap is persisted with `set_segment_summary`, embedded, and handed to
+ /// goals enrichment. The heuristic `boundary::fallback_summary` bookend is
+ /// none of those things — it is logged and dropped, leaving the segment
+ /// unsummarised on purpose. Everything downstream of the recap (events,
+ /// profile facets, tree ingest) runs either way, because none of it reads
+ /// the summary.
///
/// Soft-fallback contract (mirrors `LlmSummariser`): this function
/// never returns `Err`; all failures are logged and ignored.
@@ -344,33 +368,74 @@ impl ArchivistHook {
.join(". ");
// ── Segment recap (LLM or heuristic fallback) ────────────────────
- let (summary, _from_llm) = self
+ let (summary, from_llm) = self
.summarize_entries(&segment_entries, &segment.segment_id, segment.turn_count)
.await;
- // Persist the recap.
- let set_summary = match self.episodic() {
- Some(episodic) => {
- episodic
- .set_segment_summary(&segment.segment_id, &summary, now)
- .await
- }
- None => return,
+ // Hoisted above the two recap arms because what is missing here is the
+ // driver, not the summary: with no episodic family there is nothing to
+ // write on either arm, and this is the exit that path has always taken.
+ let Some(episodic) = self.episodic() else {
+ return;
};
- if let Err(e) = set_summary {
- tracing::warn!("[archivist] failed to set segment summary: {e}");
+
+ if recap_is_usable(from_llm, &summary) {
+ // Persist the recap.
+ let set_summary = episodic
+ .set_segment_summary(&segment.segment_id, &summary, now)
+ .await;
+ if let Err(e) = set_summary {
+ tracing::warn!("[archivist] failed to set segment summary: {e}");
+ } else {
+ tracing::debug!(
+ "[archivist] recap persisted segment={} summary_chars={}",
+ segment.segment_id,
+ summary.len()
+ );
+ }
+
+ // ── Finalize-time embedding ───────────────────────────────────
+ self.embed_segment_recap(&segment.segment_id, &summary, now)
+ .await;
} else {
- tracing::debug!(
- "[archivist] recap persisted segment={} summary_chars={}",
- segment.segment_id,
- summary.len()
- );
+ // #6156. The bookend is not written, not embedded, and not handed
+ // to goals enrichment.
+ //
+ // Persisting it would be worse than storing nothing, because
+ // `segment_set_summary` also flips the row to `status='summarised'`
+ // — and that flip is the one thing that removes the segment from
+ // the `segments_pending_summary` query a later re-summarisation
+ // pass selects on. Leaving the row `'closed'` with a NULL summary
+ // IS the provenance marker, at no schema cost.
+ //
+ // Nothing is lost by dropping the bookend either: it is derived
+ // from the segment's first and last turn, both of which stay in the
+ // episodic store, so it can be recomputed at any time.
+ //
+ // WARN only when a summariser was actually expected. With none
+ // configured for the workspace at all this is the steady state
+ // rather than a degradation, and warning once per segment close
+ // would bury the case #6156 is about — a summariser that exists
+ // and did not answer — in noise from the case that is working as
+ // intended.
+ if self.summariser_available {
+ tracing::warn!(
+ "[archivist] no LLM recap for segment={} ({} turns) — summary NOT persisted, \
+ NOT embedded, NOT sent to goals enrichment; the segment stays unsummarised \
+ so a later pass can recap it once a summariser answers",
+ segment.segment_id,
+ segment.turn_count,
+ );
+ } else {
+ tracing::debug!(
+ "[archivist] no summariser for this workspace — segment={} ({} turns) left \
+ unsummarised",
+ segment.segment_id,
+ segment.turn_count,
+ );
+ }
}
- // ── Finalize-time embedding ───────────────────────────────────────
- self.embed_segment_recap(&segment.segment_id, &summary, now)
- .await;
-
// ── Heuristic event extraction ────────────────────────────────────
if !segment_text.is_empty() {
let extracted = extract_events_heuristic(&segment_text);
@@ -469,7 +534,13 @@ impl ArchivistHook {
// the user's durable goals list stays fresh. Feed it the fresh recap
// as context. Detached + non-fatal: never blocks segment close.
if let Some(ref cfg) = self.config {
- if cfg.learning.goals_enrichment_enabled && !summary.trim().is_empty() {
+ // #6156: the recap term leads deliberately. Handing the bookend to
+ // the goals agent means an LLM call whose entire context is two
+ // truncated utterances, and it will invent durable goals out of
+ // that noise. Ordering it ahead of the config flag also keeps it
+ // evaluated whenever a config is attached, rather than being
+ // short-circuited away by an unrelated toggle.
+ if recap_is_usable(from_llm, &summary) && cfg.learning.goals_enrichment_enabled {
tracing::debug!(
"[memory_goals] segment closed — spawning goals enrichment \
session={session_id} segment={}",
@@ -499,6 +570,11 @@ impl ArchivistHook {
/// zero entries) and an empty embed input is guaranteed to 400 from
/// the upstream embedding API (#13021). The segment is sealed without
/// an embedding row; subsequent recap edits can re-embed.
+ ///
+ /// Since #6156 the finalize caller also declines to call this at all for a
+ /// heuristic recap, so this guard is no longer the only thing standing
+ /// between a bookend stub and the embedder. It now covers direct callers
+ /// and any future one that has not made that decision for itself.
pub(super) async fn embed_segment_recap(&self, segment_id: &str, summary: &str, now: f64) {
if summary.trim().is_empty() {
tracing::warn!(
@@ -573,3 +649,7 @@ impl ArchivistHook {
}
}
}
+
+#[cfg(test)]
+#[path = "lifecycle_tests.rs"]
+mod tests;
diff --git a/src/openhuman/agent/harness/archivist/lifecycle_tests.rs b/src/openhuman/agent/harness/archivist/lifecycle_tests.rs
new file mode 100644
index 0000000000..76693426ff
--- /dev/null
+++ b/src/openhuman/agent/harness/archivist/lifecycle_tests.rs
@@ -0,0 +1,121 @@
+//! Finalize-path tests for `on_segment_closed` (#6156).
+//!
+//! These drive the hook through the **contract**, not an engine: a
+//! `RecordingProvider` serves every family and records what actually reached
+//! it, so "the write did not happen" is asserted against the driver's call log
+//! rather than inferred from an empty store.
+//!
+//! `ArchivistHook::new` leaves `summariser_available == false`, which is what
+//! makes the heuristic arm of `summarize_entries` deterministic here — no chat
+//! model is built, resolved or called anywhere in these tests.
+
+use super::*;
+use crate::openhuman::memory::guard::test_support::RecordingProvider;
+
+const SESSION: &str = "lifecycle-6156";
+
+fn turn(id: i64, role: &str, content: &str) -> EpisodicTurn {
+ EpisodicTurn {
+ id: Some(id),
+ session_id: SESSION.into(),
+ timestamp: 100.0 + id as f64,
+ role: role.into(),
+ content: content.into(),
+ lesson: None,
+ tool_calls_json: None,
+ cost_microdollars: 0,
+ }
+}
+
+/// A closed segment spanning both turns above.
+///
+/// `start_seq`/`end_seq` are deliberately `None`: the episodic read path builds
+/// its `SessionEntry`s with `sequence: None`, so membership is decided on
+/// `turn.id` against the episodic-id bounds.
+fn segment() -> ConversationSegment {
+ ConversationSegment {
+ segment_id: "seg-6156".into(),
+ session_id: SESSION.into(),
+ namespace: "global".into(),
+ start_episodic_id: 1,
+ end_episodic_id: Some(2),
+ start_timestamp: 100.0,
+ end_timestamp: Some(103.0),
+ turn_count: 2,
+ summary: None,
+ embedding: None,
+ open: false,
+ start_seq: None,
+ end_seq: None,
+ }
+}
+
+fn methods(recording: &RecordingProvider) -> Vec<String> {
+ recording.calls().into_iter().map(|c| c.method).collect()
+}
+
+/// The bug in #6156: a heuristic bookend was persisted as the segment's durable
+/// summary and embedded, both unconditionally.
+///
+/// Asserting `episodic.session_turns` is present matters as much as the
+/// absences — without it the test would also pass if `on_segment_closed` had
+/// bailed out before reaching the recap at all.
+#[tokio::test]
+async fn heuristic_recap_is_not_persisted_or_embedded() {
+ let recording = Arc::new(RecordingProvider::new().with_session_turns(vec![
+ turn(1, "user", "How do I pin a submodule?"),
+ turn(2, "assistant", "Record the gitlink at the commit you want."),
+ ]));
+ let provider: Arc<dyn MemoryProvider> = recording.clone();
+ let hook = ArchivistHook::new(provider, true);
+
+ hook.on_segment_closed(&segment(), SESSION, 200.0).await;
+
+ let methods = methods(&recording);
+ assert!(
+ methods.iter().any(|m| m == "episodic.session_turns"),
+ "the finalize path must have read the segment's turns; got {methods:?}"
+ );
+ for forbidden in [
+ "episodic.set_segment_summary",
+ "scoring.embedder_slug",
+ "scoring.embed_text",
+ "episodic.upsert_segment_embedding",
+ ] {
+ assert!(
+ !methods.iter().any(|m| m == forbidden),
+ "{forbidden} must not run for a heuristic recap; got {methods:?}"
+ );
+ }
+}
+
+/// A segment whose turns are all outside its bounds short-circuits before the
+/// recap — the pre-existing empty-entries exit, not the new heuristic arm.
+///
+/// Pinned so the new branch cannot quietly become the thing that handles an
+/// empty segment.
+#[tokio::test]
+async fn empty_segment_still_short_circuits() {
+ let recording = Arc::new(RecordingProvider::new());
+ let provider: Arc<dyn MemoryProvider> = recording.clone();
+ let hook = ArchivistHook::new(provider, true);
+
+ hook.on_segment_closed(&segment(), SESSION, 200.0).await;
+
+ let methods = methods(&recording);
+ assert!(
+ !methods.iter().any(|m| m == "episodic.set_segment_summary"),
+ "an entryless segment must not be summarised; got {methods:?}"
+ );
+}
+
+/// The predicate both consumers gate on. The emptiness cases cannot be produced
+/// by `summarize_entries` today; they are pinned so a future arm that could
+/// produce one still lands on "not usable".
+#[test]
+fn recap_is_usable_truth_table() {
+ assert!(recap_is_usable(true, "a real recap"));
+ assert!(!recap_is_usable(false, "a heuristic bookend"));
+ assert!(!recap_is_usable(true, ""));
+ assert!(!recap_is_usable(true, " \n\t"));
+}
diff --git a/src/openhuman/agent/harness/archivist/recap.rs b/src/openhuman/agent/harness/archivist/recap.rs
index f23fdd1269..0474e21685 100644
--- a/src/openhuman/agent/harness/archivist/recap.rs
+++ b/src/openhuman/agent/harness/archivist/recap.rs
@@ -194,11 +194,11 @@ impl ArchivistHook {
///
/// Returns `(text, produced_by_llm)`. `produced_by_llm == false` means the
/// LLM was unavailable / failed / returned empty and `text` is the shallow
- /// heuristic `fallback_summary` bookend stub. That stub is an acceptable
- /// durable last-resort on the *finalize* path, but callers driving the
- /// **live prompt** (rolling recap → compaction) must treat
- /// `produced_by_llm == false` as "no real recap" and fall back to their
- /// own strategy — the stub must never become live compaction text.
+ /// heuristic `fallback_summary` bookend stub. Both callers treat that as
+ /// "no real recap" (#6156): the rolling recap keeps it out of the live
+ /// prompt so it can never become compaction text, and the finalize path
+ /// writes nothing at all — no summary row, no embedding, no goals
+ /// enrichment — rather than sealing the segment around a placeholder.
pub(super) async fn summarize_entries(
&self,
entries: &[&EpisodicTurn],
diff --git a/src/openhuman/agent/harness/archivist_tests_part_01_tests.rs b/src/openhuman/agent/harness/archivist_tests_part_01_tests.rs
deleted file mode 100644
index f3949976f9..0000000000
--- a/src/openhuman/agent/harness/archivist_tests_part_01_tests.rs
+++ /dev/null
@@ -1,599 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn archivist_indexes_turn() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = ArchivistHook::new(provider.clone(), true);
-
- let ctx = TurnContext {
- user_message: "What is Rust?".into(),
- assistant_response: "Rust is a systems programming language.".into(),
- tool_calls: vec![],
- turn_duration_ms: 500,
- session_id: Some("test-session".into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 1,
- };
-
- hook.on_turn_complete(&ctx).await.unwrap();
-
- let entries = fts5::episodic_session_entries(&conn, "test-session").unwrap();
- assert_eq!(entries.len(), 2);
- assert_eq!(entries[0].role, "user");
- assert_eq!(entries[1].role, "assistant");
-}
-
-#[tokio::test]
-async fn archivist_creates_segment_on_first_turn() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = ArchivistHook::new(provider.clone(), true);
-
- let ctx = TurnContext {
- user_message: "Hello world".into(),
- assistant_response: "Hi there!".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some("seg-test".into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 1,
- };
-
- hook.on_turn_complete(&ctx).await.unwrap();
-
- let open = seg::open_segment_for_session(&conn, "seg-test").unwrap();
- assert!(open.is_some());
- assert_eq!(open.unwrap().turn_count, 1);
-}
-
-#[tokio::test]
-async fn archivist_detects_topic_change_boundary() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = ArchivistHook::new(provider.clone(), true);
-
- hook.on_turn_complete(&TurnContext {
- user_message: "Tell me about Rust".into(),
- assistant_response: "Rust is great.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some("boundary-test".into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 1,
- })
- .await
- .unwrap();
-
- hook.on_turn_complete(&TurnContext {
- user_message: "How about its memory safety?".into(),
- assistant_response: "It uses ownership.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some("boundary-test".into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 2,
- })
- .await
- .unwrap();
-
- hook.on_turn_complete(&TurnContext {
- user_message: "Switching to a different topic now. I prefer dark mode.".into(),
- assistant_response: "Noted about dark mode.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some("boundary-test".into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 3,
- })
- .await
- .unwrap();
-
- let segments = seg::segments_by_namespace(&conn, "global", 10).unwrap();
- assert!(
- segments.len() >= 2,
- "Expected at least 2 segments, got {}",
- segments.len()
- );
-}
-
-#[tokio::test]
-async fn archivist_extracts_failure_lesson() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = ArchivistHook::new(provider.clone(), true);
-
- let ctx = TurnContext {
- user_message: "Run tests".into(),
- assistant_response: "Tests failed.".into(),
- tool_calls: vec![ToolCallRecord {
- name: "shell".into(),
- arguments: serde_json::json!({"command": "cargo test"}),
- success: false,
- output_summary: "shell: failed (error)".into(),
- duration_ms: 3000,
- }],
- turn_duration_ms: 3500,
- session_id: Some("test-session-2".into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 2,
- };
-
- hook.on_turn_complete(&ctx).await.unwrap();
-
- let entries = fts5::episodic_session_entries(&conn, "test-session-2").unwrap();
- let assistant_entry = entries.iter().find(|e| e.role == "assistant").unwrap();
- assert!(assistant_entry.lesson.as_ref().unwrap().contains("shell"));
-}
-
-#[tokio::test]
-async fn disabled_archivist_is_noop() {
- let hook = ArchivistHook::disabled();
- let ctx = TurnContext {
- user_message: "test".into(),
- assistant_response: "test".into(),
- tool_calls: vec![],
- turn_duration_ms: 0,
- session_id: None,
- agent_id: None,
- entrypoint: None,
- iteration_count: 0,
- };
- hook.on_turn_complete(&ctx).await.unwrap();
-}
-
-#[test]
-fn extract_profile_key_works() {
- let key = extract_profile_key("I prefer dark mode for coding", "preference");
- assert!(key.starts_with("preference_"));
- assert!(key.contains("prefer"));
-}
-
-#[tokio::test]
-async fn archivist_accumulates_turns_in_segment() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = ArchivistHook::new(provider.clone(), true);
-
- let session = "accum-session";
-
- for i in 1..=3 {
- hook.on_turn_complete(&TurnContext {
- user_message: format!("Turn number {i}"),
- assistant_response: format!("Response {i}"),
- tool_calls: vec![],
- turn_duration_ms: 50,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: i,
- })
- .await
- .unwrap();
- }
-
- let open_seg = seg::open_segment_for_session(&conn, session)
- .unwrap()
- .expect("Expected an open segment after 3 turns");
-
- assert_eq!(
- open_seg.turn_count, 3,
- "Segment should have accumulated 3 turns, got {}",
- open_seg.turn_count
- );
-}
-
-#[tokio::test]
-async fn archivist_extracts_preference_event_on_boundary() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = ArchivistHook::new(provider.clone(), true);
-
- let session = "pref-boundary-session";
-
- hook.on_turn_complete(&TurnContext {
- user_message: "Tell me about Rust ownership".into(),
- assistant_response: "Ownership is a key concept in Rust.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 1,
- })
- .await
- .unwrap();
-
- hook.on_turn_complete(&TurnContext {
- user_message: "I prefer dark mode for all my editors".into(),
- assistant_response: "Good to know! Dark mode is easier on the eyes.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 2,
- })
- .await
- .unwrap();
-
- hook.on_turn_complete(&TurnContext {
- user_message: "Switching to a different topic — how does Tokio work?".into(),
- assistant_response: "Tokio is an async runtime.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 3,
- })
- .await
- .unwrap();
-
- let events = ev::events_by_type(&conn, "global", "preference", 20).unwrap();
- assert!(
- !events.is_empty(),
- "Expected at least one preference event after segment close; got 0."
- );
- let has_dark_mode = events
- .iter()
- .any(|e| e.content.to_lowercase().contains("prefer"));
- assert!(
- has_dark_mode,
- "Expected a preference event mentioning 'prefer', found: {:?}",
- events.iter().map(|e| &e.content).collect::<Vec<_>>()
- );
-}
-
-// ── Phase 0: episodic_capture_enabled independent of learning.enabled ────────
-
-/// When `learning.enabled = false` but `episodic_capture_enabled = true`,
-/// the ArchivistHook (constructed directly, as builder.rs would produce)
-/// must still write 2 episodic_log rows (user + assistant) and create/advance
-/// a segment. This verifies the core contract: episodic capture runs
-/// regardless of the learning inference stack toggle.
-#[tokio::test]
-async fn phase0_episodic_rows_and_segment_without_learning_enabled() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- // Simulate what builder.rs does when learning.enabled=false but
- // episodic_capture_enabled=true: construct the hook directly with
- // the SQLite conn, enabled=true. No config attached (no LLM recap
- // or tree ingest — those are gated by learning.enabled / chat_to_tree_enabled).
- let hook = ArchivistHook::new(provider.clone(), true);
-
- let session = "phase0-test-session";
-
- hook.on_turn_complete(&TurnContext {
- user_message: "Hello, what is Rust?".into(),
- assistant_response: "Rust is a systems language.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 1,
- })
- .await
- .unwrap();
-
- // Verify 2 episodic rows were written.
- let entries = fts5::episodic_session_entries(&conn, session).unwrap();
- assert_eq!(
- entries.len(),
- 2,
- "Expected 2 episodic rows (user + assistant), got {}",
- entries.len()
- );
- assert_eq!(entries[0].role, "user");
- assert_eq!(entries[1].role, "assistant");
-
- // Verify a segment was created.
- let open_seg = seg::open_segment_for_session(&conn, session)
- .unwrap()
- .expect("Expected an open segment after first turn");
- assert_eq!(open_seg.turn_count, 1);
-
- // Add a second turn to verify segment advances.
- hook.on_turn_complete(&TurnContext {
- user_message: "Tell me more about ownership.".into(),
- assistant_response: "Ownership prevents data races.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 2,
- })
- .await
- .unwrap();
-
- let entries2 = fts5::episodic_session_entries(&conn, session).unwrap();
- assert_eq!(
- entries2.len(),
- 4,
- "Expected 4 episodic rows after 2 turns, got {}",
- entries2.len()
- );
- let open_seg2 = seg::open_segment_for_session(&conn, session)
- .unwrap()
- .expect("Expected an open segment after 2 turns");
- assert_eq!(
- open_seg2.turn_count, 2,
- "Segment should have 2 turns, got {}",
- open_seg2.turn_count
- );
-}
-
-/// When a segment closes, the LLM chat provider recap is used (verified by
-/// a non-empty segment summary) and an embedding row is written to
-/// `segment_embeddings`.
-#[tokio::test]
-async fn phase1_llm_recap_and_embedding_on_segment_close() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = hook_with_stubs(provider.clone());
-
- let session = "phase1-recap-test";
-
- // Turn 1 — opens first segment.
- hook.on_turn_complete(&TurnContext {
- user_message: "Tell me about Rust ownership".into(),
- assistant_response: "Rust's ownership model prevents data races.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 1,
- })
- .await
- .unwrap();
-
- // Turn 2 — continues same segment.
- hook.on_turn_complete(&TurnContext {
- user_message: "What about the borrow checker?".into(),
- assistant_response: "The borrow checker enforces ownership rules at compile time.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 2,
- })
- .await
- .unwrap();
-
- // Turn 3 — topic change triggers a boundary → closes first segment → recap + embed fire.
- hook.on_turn_complete(&TurnContext {
- user_message: "Completely different topic: what is async/await in Python?".into(),
- assistant_response: "Python asyncio enables concurrent programming.".into(),
- tool_calls: vec![],
- turn_duration_ms: 100,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: 3,
- })
- .await
- .unwrap();
-
- // Verify segments exist.
- let segments = seg::segments_by_namespace(&conn, "global", 10).unwrap();
- assert!(
- segments.len() >= 2,
- "Expected at least 2 segments (closed + open), got {}",
- segments.len()
- );
-
- // Find the closed segment (has a summary).
- let closed = segments
- .iter()
- .find(|s| s.summary.as_ref().map(|s| !s.is_empty()).unwrap_or(false));
- assert!(
- closed.is_some(),
- "Expected at least one closed segment with a non-empty summary"
- );
-
- let closed_seg = closed.unwrap();
- let summary = closed_seg.summary.as_ref().unwrap();
- // The stub provider returns a fixed string — verify it was persisted.
- assert!(
- summary.contains("stub recap"),
- "Expected summary to contain 'stub recap', got: {:?}",
- summary
- );
-}
-
-/// `flush_open_segment` must force-close the trailing open segment and
-/// trigger recap + embedding even without a boundary-triggering turn.
-#[tokio::test]
-async fn phase1_flush_open_segment_finalizes_trailing_segment() {
- let (_tmp, client, provider) = setup_provider();
- let conn = client.profile_conn();
- let hook = hook_with_stubs(provider.clone());
-
- let session = "phase1-flush-test";
-
- // Write 2 turns — stays in one open segment (no topic boundary fires).
- for i in 1..=2 {
- hook.on_turn_complete(&TurnContext {
- user_message: format!("Question about Rust turn {i}"),
- assistant_response: format!("Answer about Rust turn {i}"),
- tool_calls: vec![],
- turn_duration_ms: 50,
- session_id: Some(session.into()),
- agent_id: None,
- entrypoint: None,
- iteration_count: i,
- })
- .await
- .unwrap();
- }
-
- // Confirm the segment is still open (no boundary fired).
- let open_seg_before = seg::open_segment_for_session(&conn, session).unwrap();
- assert!(
- open_seg_before.is_some(),
- "Expected an open segment before flush"
- );
-
- // Flush — should force-close, recap, and embed.
- hook.flush_open_segment(session).await;
-
- // Segment should now be closed (no open segment for this session).
- let open_seg_after = seg::open_segment_for_session(&conn, session).unwrap();
- assert!(
- open_seg_after.is_none(),
- "Expected no open segment after flush_open_segment"
- );
-
- // The formerly-open segment should now have a summary.
- let segments = seg::segments_by_namespace(&conn, "global", 10).unwrap();
- let flushed = segments.iter().find(|s| {
- s.session_id == session && s.summary.as_ref().map(|s| !s.is_empty()).unwrap_or(false)
- });
- assert!(
- flushed.is_some(),
- "Expected flushed segment to have a non-empty summary"
- );
-}
-
-/// After a single turn (no segment boundary), the tree must have ZERO chunks —
-/// the per-turn pipe_turn_to_tree path no longer exists.
-#[tokio::test]
-async fn phase2_no_per_turn_tree_write() {
- with_stub_chat_provider(phase2_no_per_turn_tree_write_inner()).await
-}
-
-/// When a segment closes (boundary triggered), exactly ONE tree ingest fires
-/// for that segment containing all its turns — not one ingest per turn.
-#[tokio::test]
-async fn phase2_exactly_one_tree_ingest_per_segment_close() {
- with_stub_chat_provider(phase2_exactly_one_tree_ingest_per_segment_close_inner()).await
-}
-
-/// The ingested leaf messages must carry the episodic-provenance `source_ref`
-/// in the expected format:
-/// `agent://session/{session_id}/segment/{segment_id}#ep{start}-{end}`.
-///
-/// Also verifies that `source_id` is the constant `"conversations:agent"`.
-#[tokio::test]
-async fn phase2_provenance_stamped_on_leaf_and_source_id_is_constant() {
- with_stub_chat_provider(phase2_provenance_stamped_on_leaf_and_source_id_is_constant_inner())
- .await
-}
-
-/// The ingested content must be the raw prose turns (user + assistant text),
-/// NOT equal to the LLM recap text. The recap lives only in the STM segment
-/// layer; the tree must ingest raw evidence so it can build its own summaries.
-#[tokio::test]
-async fn phase2_ingested_content_is_raw_prose_not_recap() {
- with_stub_chat_provider(phase2_ingested_content_is_raw_prose_not_recap_inner()).await
-}
-
-/// `flush_open_segment` must also trigger the tree ingest for the trailing
-/// open segment (same as on_segment_closed at a topic boundary).
-#[tokio::test]
-async fn phase2_flush_also_triggers_tree_ingest() {
- with_stub_chat_provider(phase2_flush_also_triggers_tree_ingest_inner()).await
-}
-
-// ── #13021 empty/whitespace recap embed-skip guard ───────────────────────────
-//
-// `on_segment_closed` defends against ever passing an empty or whitespace
-// recap into the embedder by calling `embed_segment_recap`, which short-
-// circuits before `Embedder::embed` runs. The skip is unreachable through
-// the current `summarize_entries` call graph today (the heuristic
-// `fallback_summary` always returns non-empty text), so these tests drive
-// `embed_segment_recap` directly to lock the guard against future
-// regressions where `summarize_entries` could return `""`.
-
-/// An empty recap must short-circuit before any scoring call.
-///
-/// Uses `RecordingProvider` so we can assert that `scoring.embed_text` is
-/// absent — confirming the guard fired before the scoring path, not merely
-/// that no row landed in a DB queried with the wrong model_signature key.
-#[tokio::test]
-async fn embed_segment_recap_skips_empty_summary() {
- use crate::openhuman::memory::guard::test_support::RecordingProvider;
- let recording = Arc::new(RecordingProvider::new());
- let provider: Arc<dyn MemoryProvider> = recording.clone();
- let hook = hook_with_stubs(provider);
-
- hook.embed_segment_recap("seg-empty-recap", "", 3.0).await;
-
- let calls = recording.calls();
- let methods: Vec<&str> = calls.iter().map(|c| c.method.as_str()).collect();
- assert!(
- !methods.contains(&"scoring.embed_text"),
- "scoring.embed_text must not be called for an empty recap; got {methods:?}"
- );
-}
-
-/// Whitespace-only recaps (newlines, tabs, spaces) must also short-circuit
-/// — the upstream provider rejects whitespace inputs the same way it
-/// rejects empty inputs (#13021).
-///
-/// Uses `RecordingProvider` so we can assert that `scoring.embed_text` is
-/// absent — confirming the guard fired before the scoring path, not merely
-/// that no row landed in a DB queried with the wrong model_signature key.
-#[tokio::test]
-async fn embed_segment_recap_skips_whitespace_summary() {
- use crate::openhuman::memory::guard::test_support::RecordingProvider;
- let recording = Arc::new(RecordingProvider::new());
- let provider: Arc<dyn MemoryProvider> = recording.clone();
- let hook = hook_with_stubs(provider);
-
- hook.embed_segment_recap("seg-ws-recap", " \n\t ", 3.0)
- .await;
-
- let calls = recording.calls();
- let methods: Vec<&str> = calls.iter().map(|c| c.method.as_str()).collect();
- assert!(
- !methods.contains(&"scoring.embed_text"),
- "scoring.embed_text must not be called for a whitespace-only recap; got {methods:?}"
- );
-}
-
-/// Positive control: a non-empty recap must reach `embedder_slug` then
-/// `embed_text` on the scoring family, in that order, and pass the recap text
-/// verbatim to `embed_text`.
-#[tokio::test]
-async fn embed_segment_recap_reaches_scoring_for_non_empty_summary() {
- use crate::openhuman::memory::guard::test_support::RecordingProvider;
- let recording = Arc::new(RecordingProvider::new());
- let provider: Arc<dyn MemoryProvider> = recording.clone();
- let hook = hook_with_stubs(provider);
-
- hook.embed_segment_recap("seg-ok-recap", "real recap text", 3.0)
- .await;
-
- let calls = recording.calls();
- let methods: Vec<&str> = calls.iter().map(|c| c.method.as_str()).collect();
-
- let slug_pos = methods
- .iter()
- .position(|&m| m == "scoring.embedder_slug")
- .unwrap_or_else(|| panic!("scoring.embedder_slug must be called; got {methods:?}"));
- let embed_pos = methods
- .iter()
- .position(|&m| m == "scoring.embed_text")
- .expect("scoring.embed_text must be called for a non-empty recap");
-
- assert!(
- slug_pos < embed_pos,
- "scoring.embedder_slug ({slug_pos}) must be called before scoring.embed_text ({embed_pos})"
- );
- assert_eq!(
- calls[embed_pos].content.as_deref(),
- Some("real recap text"),
- "embed_text must receive the recap text verbatim"
- );
-}
diff --git a/src/openhuman/memory/guard/test_support_part_01.rs b/src/openhuman/memory/guard/test_support_part_01.rs
index 870e065395..6e43ccd9e5 100644
--- a/src/openhuman/memory/guard/test_support_part_01.rs
+++ b/src/openhuman/memory/guard/test_support_part_01.rs
@@ -22,7 +22,8 @@ use crate::openhuman::memory::api::provider::types::{
};
use crate::openhuman::memory::api::provider::{
AddressBookSeedOutcome, ChunkDetail, ChunkEmbedding, ChunkQuery, CoverWindowQuery, EntityMatch,
- EpisodicEvent, FacetType, FastRetrieveQuery, MemoryChunks, MemoryCodingSessions, MemoryCore,
+ EpisodicEvent, EpisodicTurn, FacetType, FastRetrieveQuery, MemoryChunks, MemoryCodingSessions,
+ MemoryCore,
MemoryDiff, MemoryDocuments, MemoryEntities, MemoryEpisodic, MemoryGoals, MemoryGraph,
MemoryIngest, MemoryMaintenance, MemoryPeople, MemoryPortability, MemoryProfile,
MemoryProvider, MemoryRecall, MemoryRetrieval, MemoryScoring, MemorySourceSink,
@@ -86,6 +87,9 @@ pub struct RecordingProvider {
/// What `namespaces` returns, so a namespace can look populated (Lane B
/// asks for the count before it pays for an embed) without a real store.
namespace_summaries: Mutex<Vec<NamespaceSummary>>,
+ /// What `session_turns` returns, so the archivist's finalize path can be
+ /// driven past its empty-entries early return without an engine behind it.
+ session_turns: Mutex<Vec<EpisodicTurn>>,
}
impl Default for RecordingProvider {
@@ -102,6 +106,7 @@ impl RecordingProvider {
fast_retrieve_result: Mutex::new(RetrievalResponse::default()),
namespace_hits: Mutex::new(Vec::new()),
namespace_summaries: Mutex::new(Vec::new()),
+ session_turns: Mutex::new(Vec::new()),
}
}
@@ -125,6 +130,11 @@ impl RecordingProvider {
self
}
+ pub fn with_session_turns(self, turns: Vec<EpisodicTurn>) -> Self {
+ *self.session_turns.lock().unwrap() = turns;
+ self
+ }
+
fn record(&self, call: Call) {
self.calls.lock().unwrap().push(call);
}
diff --git a/src/openhuman/memory/guard/test_support_part_02.rs b/src/openhuman/memory/guard/test_support_part_02.rs
index 20d024cc10..08240b2506 100644
--- a/src/openhuman/memory/guard/test_support_part_02.rs
+++ b/src/openhuman/memory/guard/test_support_part_02.rs
@@ -247,7 +247,7 @@ impl MemoryEpisodic for RecordingProvider {
) -> Result<Vec<crate::openhuman::memory::api::provider::episodic::EpisodicTurn>, MemoryError>
{
self.record(Call::plain("episodic.session_turns"));
- Ok(vec![])
+ Ok(self.session_turns.lock().unwrap().clone())
}
async fn open_segment(