Skip to content

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

test(memory): drop the integration targets that drive the engine directly\n\nSeven `tests/` targets exist to exercise TinyCortex and tinymemory-core\nthrough a thin host wrapper — the sync pipeline, the chunk and tree stores,\nthe thread and source suites. Between them they import the engine 84 times and\nassert what it stores, filters and summarises. Upstream owns every one of\nthose behaviours and covers them with ~2,800 tests of its own; these are\nengine tests that ended up in the wrong repository.\n\n`install_memory_host_seams` goes from the 25 targets that called it. It\ninstalls an embedder, a chat provider, a config loader, an NLP host, a\nscheduler gate and a shutdown hook into `tinymemory_core`'s process statics.\nWith no in-process engine there is nothing to install into, so the call is not\nmerely unnecessary — after the manifest is cut it will not resolve.\n\nOne test is deleted on its own rather than with a file:\n`golden_fixture_rows_read_back_and_schema_is_stable_after_reopen`. It is worth\nnaming because it is the counter-example to how the rest were classified. It\nimports the engine zero times, so an import census says it is engine-free —\nand it still fails without the seam, because it binds a global memory client\nand asserts the engine's SQLite schema survives a reopen. It reaches the engine\nthrough this crate's own `memory::*` re-exports.\n\n**An import census under-counts.** The remaining sweep has to be driven by what\nfails without the engine, not by what names it. The other five tests in that\nfile pass untouched and stay.\n\nRefs #6161\n

Shanu58aa8a2433ac
diff --git a/tests/agent_harness_e2e.rs b/tests/agent_harness_e2e.rs
index 662539783a..669e13114b 100644
--- a/tests/agent_harness_e2e.rs
+++ b/tests/agent_harness_e2e.rs
@@ -670,9 +670,6 @@ async fn boot_stack() -> Stack {
// The transport-only router does not create a Core runtime context. Install
// the explicit tinymemory host seams before handlers service memory-backed
// agent turns, matching normal startup wiring.
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(std::sync::Arc::new(
- openhuman_core::openhuman::config::Config::default(),
- ));
let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;
let rpc_base = format!("http://{rpc_addr}");
diff --git a/tests/agent_retrieval_e2e.rs b/tests/agent_retrieval_e2e.rs
index 88a2299d03..4cb57d915a 100644
--- a/tests/agent_retrieval_e2e.rs
+++ b/tests/agent_retrieval_e2e.rs
@@ -55,9 +55,6 @@ fn ensure_memory_seams() {
.stack_size(8 * 1024 * 1024)
.spawn(|| {
let config = std::sync::Arc::new(Config::default());
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/agent_turn_overrides_e2e.rs b/tests/agent_turn_overrides_e2e.rs
index df09d6ddad..4d47ff0dcb 100644
--- a/tests/agent_turn_overrides_e2e.rs
+++ b/tests/agent_turn_overrides_e2e.rs
@@ -91,9 +91,6 @@ fn ensure_memory_seams() {
.name("turn-overrides-e2e-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- Config::default(),
- ));
})
.expect("spawn turn-overrides seam installer")
.join()
diff --git a/tests/domain_modules_e2e.rs b/tests/domain_modules_e2e.rs
index d7403a6acf..0ddd1ad8a8 100644
--- a/tests/domain_modules_e2e.rs
+++ b/tests/domain_modules_e2e.rs
@@ -143,9 +143,6 @@ async fn setup() -> TestHarness {
// The HTTP router is intentionally transport-only and does not construct a
// Core runtime context. Memory-backed RPC reads still need the explicit
// tinymemory host seams before they can load their configured provider.
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(std::sync::Arc::new(
- openhuman_core::openhuman::config::Config::default(),
- ));
// Same rule for the modules policy, which became load-bearing when the
// status RPCs started reading diagnostics through the bound driver
// (#5560): resolving a driver refuses outright until boot publishes the
diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rs
index 0a71ca1310..c12f5b6ef4 100644
--- a/tests/json_rpc_e2e.rs
+++ b/tests/json_rpc_e2e.rs
@@ -122,9 +122,6 @@ fn ensure_json_rpc_e2e_memory_seams() {
workspace_dir: json_rpc_e2e_shared_workspace().to_path_buf(),
..openhuman_core::openhuman::config::Config::default()
});
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/memory_fast_retrieve_e2e.rs b/tests/memory_fast_retrieve_e2e.rs
index 86e1c8ab86..a0110b829f 100644
--- a/tests/memory_fast_retrieve_e2e.rs
+++ b/tests/memory_fast_retrieve_e2e.rs
@@ -38,9 +38,6 @@ fn ensure_memory_seams() {
.name("memory-fast-retrieve-e2e-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- Config::default(),
- ));
})
.expect("spawn memory retrieval seam installer")
.join()
diff --git a/tests/memory_golden_fixture_e2e.rs b/tests/memory_golden_fixture_e2e.rs
index 1064755ec8..9df1941344 100644
--- a/tests/memory_golden_fixture_e2e.rs
+++ b/tests/memory_golden_fixture_e2e.rs
@@ -152,9 +152,6 @@ fn ensure_memory_seams(workspace: &Path) {
config_path: workspace.join("config.toml"),
..openhuman_core::openhuman::config::Config::default()
});
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
@@ -262,124 +259,6 @@ async fn fresh_workspace_schema_matches_the_committed_manifest() {
assert_manifest_set_equal(&committed_manifest(), &actual);
}
-/// Gate 3 — the code the current build produces still yields the same schema
-/// the fixture captured.
-///
-/// This is the half that catches a DDL edit: it opens the *fixture copy* with
-/// the current `UnifiedMemory::new` + tinycortex init (both of which run their
-/// `CREATE TABLE IF NOT EXISTS` / `ALTER TABLE` bootstrap on every open), then
-/// re-dumps. A new table, index, or trigger shows up as UNEXPECTED; a renamed
-/// one shows up as both MISSING and UNEXPECTED.
-///
-/// Everything that binds the process-global memory client lives in this one
-/// test, for the reason `memory_golden_parity_e2e` documents: the client is
-/// process-global and binds to its first workspace, so splitting these across
-/// tests makes them pass or fail by scheduling order.
-#[tokio::test]
-async fn golden_fixture_rows_read_back_and_schema_is_stable_after_reopen() {
- let _lock = env_lock();
- let tmp = tempdir().expect("tempdir");
- let _home = EnvVarGuard::set_to_path("HOME", tmp.path());
- let workspace = tmp.path().join("workspace");
- copy_fixture_to(&workspace);
- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace);
- ensure_memory_seams(&workspace);
-
- let before = golden::schema_manifest(&workspace).expect("dump schema before open");
-
- tinymemory_core::global::init(workspace.clone())
- .expect("bind global memory client to the fixture copy");
-
- // ── Row-level read-back through memory::ops ──
- let readback = golden::read_back(&workspace)
- .await
- .expect("read the golden workspace back");
- eprintln!("[golden-fixture] readback: {readback:#?}");
-
- assert_eq!(
- readback.primary_doc_keys,
- vec![golden::DOC_KEY_PRIMARY.to_string()],
- "primary-namespace document lost"
- );
- assert_eq!(
- readback.secondary_doc_keys,
- vec![golden::DOC_KEY_SECONDARY.to_string()],
- "secondary-namespace document lost — namespace scoping is broken"
- );
- assert!(readback.kv_global_present, "global-scope KV value lost");
- assert!(
- readback.kv_namespace_present,
- "namespace-scope KV value lost"
- );
- assert_eq!(readback.graph_hits, 1, "graph triple lost");
- assert_eq!(
- readback.episodic_sessions,
- vec![golden::SESSION_ID.to_string()],
- "episodic row lost"
- );
- assert_eq!(
- readback.segment_ids,
- vec![golden::SEGMENT_ID.to_string()],
- "conversation segment lost"
- );
- assert_eq!(
- readback.event_ids,
- vec![golden::EVENT_ID.to_string()],
- "event row lost"
- );
- assert_eq!(
- readback.profile_keys,
- vec![golden::PROFILE_KEY.to_string()],
- "user_profile facet lost"
- );
- assert_eq!(
- readback.summary_ids,
- vec![golden::SUMMARY_ID.to_string()],
- "summary node lost"
- );
- assert!(
- readback.tree_sealed,
- "summary tree is no longer sealed to its root node"
- );
- assert_eq!(
- readback.chunk_ids.len(),
- 1,
- "expected exactly one seeded leaf chunk, got {:?}",
- readback.chunk_ids
- );
- assert!(
- readback.embeddings_match,
- "at least one embedding tier did not return the exact seeded vector — \
- a vector encoding or column change would strand every existing embedding"
- );
- // Fixed-query recall: the exact set, not a "contains". Retrieval spans
- // documents, KV values and events, so this pins the whole hit assembly —
- // dropping any tier from the recall path changes this list.
- assert_eq!(
- readback.recall_chunks,
- vec![
- "Decided to pin the memory schema with a captured fixture.".to_string(),
- golden::DOC_CONTENT_PRIMARY.to_string(),
- r#"{"fixture":"golden","v":1}"#.to_string(),
- r#"{"fixture":"golden","v":1}"#.to_string(),
- ],
- "fixed-query recall returned a different result set"
- );
-
- // ── Opening the workspace must not mutate its schema ──
- let after = golden::schema_manifest(&workspace).expect("dump schema after open");
- assert_manifest_set_equal(&committed_manifest(), &after);
- assert_manifest_set_equal(&before, &after);
-
- // ── Close and reopen in a SECOND PROCESS ──
- //
- // A fresh process gets a fresh SQLite library state and a cold page cache,
- // so this is what catches WAL / journal-mode surprises that an in-process
- // reopen would hide (the connection pool would just hand back the same
- // warm handle).
- run_second_process_readback(&workspace);
-}
-
/// Spawn this same test binary to run [`second_process_readback`] against
/// `workspace`, and fail loudly with its output if it does not pass.
fn run_second_process_readback(workspace: &Path) {
diff --git a/tests/memory_golden_parity_e2e.rs b/tests/memory_golden_parity_e2e.rs
index 66474d0372..2cd17229bb 100644
--- a/tests/memory_golden_parity_e2e.rs
+++ b/tests/memory_golden_parity_e2e.rs
@@ -125,9 +125,6 @@ fn ensure_memory_seams(workspace: &Path) {
config_path: workspace.join("config.toml"),
..Config::default()
});
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/memory_roundtrip_e2e.rs b/tests/memory_roundtrip_e2e.rs
index 6c7499fce7..7c48ec8b32 100644
--- a/tests/memory_roundtrip_e2e.rs
+++ b/tests/memory_roundtrip_e2e.rs
@@ -81,9 +81,6 @@ fn ensure_memory_seams(workspace: &Path) {
config_path: workspace.join("config.toml"),
..openhuman_core::openhuman::config::Config::default()
});
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/memory_sources_e2e.rs b/tests/memory_sources_e2e.rs
index bea8608fcd..19a032e4db 100644
--- a/tests/memory_sources_e2e.rs
+++ b/tests/memory_sources_e2e.rs
@@ -48,9 +48,6 @@ fn ensure_memory_seams() {
.stack_size(8 * 1024 * 1024)
.spawn(|| {
let config = Arc::new(openhuman_core::openhuman::config::Config::default());
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/memory_sync_pipeline_e2e.rs b/tests/memory_sync_pipeline_e2e.rs
deleted file mode 100644
index ffdb90315a..0000000000
--- a/tests/memory_sync_pipeline_e2e.rs
+++ /dev/null
@@ -1,518 +0,0 @@
-//! End-to-end coverage for the redesigned memory-sync flow shipped in
-//! PR #3113 (issue #3116).
-//!
-//! What this proves, all offline (no network, no live LLM):
-//!
-//! 1. `run_github_sync` against a **local seed git repo** (a bare clone is
-//! pre-staged in the source's git cache dir with a `file://` origin so
-//! the offline `git fetch` succeeds) lands summaries in the source tree.
-//! 2. `ingest_summary` fills the L1 buffer and seals the cascade once the
-//! buffer crosses `SUMMARY_FANOUT`.
-//! 3. `rebuild_tree_from_raw` reads raw `.md` files seeded on disk and
-//! builds the tree from them.
-//! 4. `sync_source` is a no-op on a second concurrent call (per-source
-//! mutex), runs `retry_all_failed`, and writes the audit log.
-//! 5. `check_and_rebuild_tree` auto-detects raw-without-summaries
-//! (`max_level == 0`) and triggers a rebuild.
-//! 6. The Tree-mode graph export builds synthetic source-root nodes, hangs
-//! document leaves off L1 summaries, and links orphan summaries to their
-//! source root.
-//!
-//! ## What is stubbed and why
-//!
-//! The summariser (`memory_tree::summarise::summarise`) makes a real LLM
-//! call. Both `run_github_sync` and `rebuild_tree_from_raw` catch a
-//! summarise error and fall back to `fallback_summary` (a deterministic
-//! concat-and-truncate). With no provider configured in the test `Config`,
-//! the LLM call fails fast and the deterministic fallback runs — so the
-//! ingest/seal/rebuild machinery under test is exercised end-to-end without
-//! any network. The summary *text* is the fallback concat rather than a
-//! real model summary; everything else (file staging, DB rows, buffers,
-//! seal cascade, audit log, graph shape) is the production path.
-//!
-//! GitHub issues/PRs require the GitHub REST API (or `gh`), which is not
-//! reachable offline; the seeded local repo only carries commits. That is
-//! fine — `run_github_sync` treats issue/PR listing failures as non-fatal
-//! as long as commits list successfully, which is the path asserted here.
-
-use std::path::Path;
-use std::process::Command;
-use std::sync::{Arc, OnceLock};
-
-use chrono::Utc;
-use tempfile::TempDir;
-
-use openhuman_core::openhuman::config::Config;
-// The engine's own source pipeline. `memory::sources::sync` is host-side now and
-// carries only `derive_scopes`; `sync_source` stayed upstream because nothing in
-// `src/` calls it any more (#5560).
-use openhuman_core::openhuman::memory::sources::types::{MemorySourceEntry, SourceKind};
-use tinymemory_core::sources::sync::sync_source;
-use tinymemory_core::store::content::raw::{raw_kind_dir, raw_source_dir, RawKind};
-use tinymemory_core::store::trees::store as tree_store;
-use tinymemory_core::store::trees::types::SUMMARY_FANOUT;
-use tinymemory_core::tinycortex::read_audit_log;
-use tinymemory_core::tinycortex::run_github_sync;
-use tinymemory_core::tinycortex::{needs_rebuild, rebuild_tree_from_raw};
-use tinymemory_core::tree::ingest::{ingest_summary, SummaryIngestInput};
-use tinymemory_core::tree_source::get_or_create_source_tree;
-
-// ── Shared harness ────────────────────────────────────────────────────────
-
-static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
-
-fn ensure_memory_seams() {
- MEMORY_SEAMS_INIT.get_or_init(|| {
- std::thread::Builder::new()
- .name("memory-sync-pipeline-e2e-seams".to_string())
- .stack_size(8 * 1024 * 1024)
- .spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- Config::default(),
- ));
- })
- .expect("spawn memory sync pipeline seam installer")
- .join()
- .expect("memory sync pipeline seam installer panicked");
- });
-}
-
-/// Build a `Config` rooted at a temp workspace with no LLM provider and no
-/// embedder, so every test runs fully offline and deterministically.
-fn test_config(tmp: &TempDir) -> Config {
- ensure_memory_seams();
- let workspace_dir = tmp.path().join("workspace");
- std::fs::create_dir_all(&workspace_dir).expect("create workspace dir");
- let mut cfg = Config {
- workspace_dir: workspace_dir.clone(),
- config_path: tmp.path().join("config.toml"),
- ..Config::default()
- };
- // Inert embedder — no Ollama, no network.
- cfg.memory_tree.embedding_endpoint = None;
- cfg.memory_tree.embedding_model = None;
- cfg.memory_tree.embedding_strict = false;
- cfg
-}
-
-/// Build a `SummaryIngestInput` with the given content + token count and
-/// otherwise inert metadata.
-fn summary_input(content: &str, tokens: u32) -> SummaryIngestInput {
- SummaryIngestInput {
- content: content.to_string(),
- token_count: tokens,
- entities: Vec::new(),
- topics: vec!["test".to_string()],
- time_range_start: Utc::now(),
- time_range_end: Utc::now(),
- score: 0.5,
- child_labels: Vec::new(),
- child_basenames: Vec::new(),
- }
-}
-
-fn run_git(args: &[&str], cwd: &Path) {
- let status = Command::new("git")
- // A contributor with `commit.gpgsign = true` set globally otherwise
- // gets a `git commit` here that blocks forever on a pinentry prompt
- // with no tty behind it — the whole file hangs rather than failing.
- .args(["-c", "commit.gpgsign=false"])
- .args(args)
- .current_dir(cwd)
- .env("GIT_AUTHOR_NAME", "Test")
- .env("GIT_AUTHOR_EMAIL", "[email protected]")
- .env("GIT_COMMITTER_NAME", "Test")
- .env("GIT_COMMITTER_EMAIL", "[email protected]")
- .status()
- .unwrap_or_else(|e| panic!("git {args:?} failed to spawn: {e}"));
- assert!(status.success(), "git {args:?} exited {status}");
-}
-
-// ── Test 1: run_github_sync against a seeded local repo ────────────────────
-
-/// Seed a working repo with N commits, make it a bare repo, then bare-clone
-/// it into the source's git cache dir with a `file://` origin so the
-/// offline `git fetch` inside `ensure_bare_clone` succeeds. `run_github_sync`
-/// then lists/read commits via local git and lands a summary in the tree.
-#[tokio::test]
-async fn github_sync_lands_summaries_in_tree() {
- let tmp = TempDir::new().unwrap();
- let cfg = test_config(&tmp);
-
- // 1. Build a seed working repo with a handful of commits.
- let seed = tmp.path().join("seed-work");
- std::fs::create_dir_all(&seed).unwrap();
- run_git(&["init", "--quiet"], &seed);
- run_git(&["checkout", "-q", "-b", "main"], &seed);
- for i in 0..4 {
- std::fs::write(seed.join(format!("file{i}.txt")), format!("content {i}\n")).unwrap();
- run_git(&["add", "."], &seed);
- run_git(
- &[
- "commit",
- "--quiet",
- "-m",
- &format!("feat: change number {i}"),
- ],
- &seed,
- );
- }
-
- // 2. Make a bare mirror of the seed repo to act as the "remote".
- let remote_bare = tmp.path().join("seed-remote.git");
- run_git(
- &[
- "clone",
- "--bare",
- "--quiet",
- seed.to_str().unwrap(),
- remote_bare.to_str().unwrap(),
- ],
- tmp.path(),
- );
-
- // 3. Pre-stage the source's git cache as a bare clone of the local
- // remote, so `ensure_bare_clone` sees HEAD and the offline `git
- // fetch` (against the file:// origin) succeeds.
- let owner = "tinyhumansai";
- let repo = "seedrepo";
- let cache_dir = cfg
- .workspace_dir
- .join("git_cache")
- .join(owner)
- .join(format!("{repo}.git"));
- std::fs::create_dir_all(cache_dir.parent().unwrap()).unwrap();
- run_git(
- &[
- "clone",
- "--bare",
- "--quiet",
- remote_bare.to_str().unwrap(),
- cache_dir.to_str().unwrap(),
- ],
- tmp.path(),
- );
- assert!(
- cache_dir.join("HEAD").exists(),
- "seeded bare clone must have HEAD"
- );
-
- // 4. Run the sync. Commits resolve via local git; issues/PRs fail
- // offline but are non-fatal because commits succeeded.
- let source = MemorySourceEntry {
- id: "gh-seed".to_string(),
- kind: SourceKind::GithubRepo,
- label: "Seed repo".to_string(),
- enabled: true,
- url: Some(format!("https://github.com/{owner}/{repo}")),
- max_commits: Some(50),
- max_issues: Some(0),
- max_prs: Some(0),
- toolkit: None,
- connection_id: None,
- path: None,
- glob: None,
- branch: None,
- paths: Vec::new(),
- query: None,
- since_days: None,
- max_items: None,
- selector: None,
- max_tokens_per_sync: None,
- max_cost_per_sync_usd: None,
- sync_depth_days: None,
- };
-
- let outcome = run_github_sync(&source, &cfg)
- .await
- .expect("run_github_sync should succeed with local commits");
-
- assert!(
- outcome.records_ingested >= 4,
- "expected >= 4 commits ingested, got {}",
- outcome.records_ingested
- );
-
- // The source tree now has an L1 summary buffered.
- let scope = format!("github:{owner}/{repo}");
- let tree = get_or_create_source_tree(&cfg, &scope).unwrap();
- let buf = tree_store::get_buffer(&cfg, &tree.id, 1).unwrap();
- assert!(
- !buf.item_ids.is_empty(),
- "L1 buffer should hold the ingested summary"
- );
-
- // A success audit entry was written for the github sync.
- let audit = read_audit_log(&cfg);
- assert!(
- audit
- .iter()
- .any(|e| e.source_kind == "github_repo" && e.success),
- "github sync should write a successful audit entry; got {audit:?}"
- );
-}
-
-// ── Test 2: ingest_summary fills the buffer and seals at SUMMARY_FANOUT ─────
-
-#[tokio::test]
-async fn ingest_summary_seals_l1_buffer_at_fanout() {
- let tmp = TempDir::new().unwrap();
- let cfg = test_config(&tmp);
- let tree = get_or_create_source_tree(&cfg, "github:org/fanout-repo").unwrap();
-
- // First SUMMARY_FANOUT - 1 ingests should NOT seal.
- for i in 0..(SUMMARY_FANOUT - 1) {
- let outcome = ingest_summary(&cfg, &tree, summary_input(&format!("summary {i}"), 10))
- .await
- .unwrap();
- assert!(
- outcome.sealed_ids.is_empty(),
- "ingest {i} should not seal before reaching fanout"
- );
- }
-
- let buf = tree_store::get_buffer(&cfg, &tree.id, 1).unwrap();
- assert_eq!(
- buf.item_ids.len() as u32,
- SUMMARY_FANOUT - 1,
- "buffer should hold FANOUT-1 items before the sealing ingest"
- );
-
- // The SUMMARY_FANOUT-th ingest crosses the gate and seals the cascade.
- let sealing = ingest_summary(&cfg, &tree, summary_input("the tenth summary", 10))
- .await
- .unwrap();
- assert!(
- !sealing.sealed_ids.is_empty(),
- "ingest at SUMMARY_FANOUT should trigger a seal cascade"
- );
-
- // After sealing, the L1 buffer is drained and the tree grew a level.
- let buf_after = tree_store::get_buffer(&cfg, &tree.id, 1).unwrap();
- assert!(
- (buf_after.item_ids.len() as u32) < SUMMARY_FANOUT,
- "L1 buffer should be drained after the seal cascade, got {}",
- buf_after.item_ids.len()
- );
- let tree_after = get_or_create_source_tree(&cfg, "github:org/fanout-repo").unwrap();
- assert!(
- tree_after.max_level >= 2,
- "tree should have grown to L2 after sealing, max_level={}",
- tree_after.max_level
- );
-}
-
-// ── Test 3: rebuild_tree_from_raw reads seeded raw files ───────────────────
-
-#[tokio::test]
-async fn rebuild_tree_from_raw_builds_from_disk() {
- let tmp = TempDir::new().unwrap();
- let cfg = test_config(&tmp);
- let scope = "gmail:test-at-example-dot-com";
-
- // Seed raw markdown files on disk under raw/<slug>/emails/.
- let content_root = cfg.memory_tree_content_root();
- let emails_dir = raw_kind_dir(&content_root, scope, RawKind::Email);
- std::fs::create_dir_all(&emails_dir).unwrap();
- for i in 0..3 {
- let ts = 1_700_000_000_000i64 + i;
- std::fs::write(
- emails_dir.join(format!("{ts}_msg-{i}.md")),
- format!("# Email {i}\n\nBody of message number {i}.\n"),
- )
- .unwrap();
- }
- // A `_source.md` sidecar that must be skipped by the collector.
- std::fs::write(
- raw_source_dir(&content_root, scope).join("_source.md"),
- "scope: gmail:test-at-example-dot-com\n",
- )
- .unwrap();
-
- // Tree has raw but no summaries yet → max_level 0.
- let before = get_or_create_source_tree(&cfg, scope).unwrap();
- assert_eq!(before.max_level, 0, "fresh tree should be at level 0");
-
- let outcome = rebuild_tree_from_raw(&cfg, scope, scope).await.unwrap();
- assert_eq!(outcome.files_read, 3, "should read the 3 seeded emails");
- assert!(outcome.batches >= 1, "should produce at least one batch");
-
- // The rebuild produced an L1 summary in the buffer.
- let tree = get_or_create_source_tree(&cfg, scope).unwrap();
- let buf = tree_store::get_buffer(&cfg, &tree.id, 1).unwrap();
- assert!(
- !buf.item_ids.is_empty(),
- "rebuild should have ingested at least one L1 summary"
- );
-
- // Rebuild wrote its own audit entry tagged "rebuild".
- let audit = read_audit_log(&cfg);
- assert!(
- audit
- .iter()
- .any(|e| e.source_kind == "rebuild" && e.scope == scope),
- "rebuild should write a rebuild audit entry; got {audit:?}"
- );
-}
-
-// ── Test 4: sync_source mutex no-op, retry_all_failed, audit ───────────────
-
-#[tokio::test]
-async fn sync_source_second_concurrent_call_is_noop_and_audits() {
- ensure_memory_seams();
- let tmp = TempDir::new().unwrap();
- let cfg = test_config(&tmp);
-
- // A Folder source pointed at a small on-disk directory: this exercises
- // the dispatcher's per-item path (no network) so the audit + retry +
- // rebuild branches all run for real.
- let docs = tmp.path().join("docs");
- std::fs::create_dir_all(&docs).unwrap();
- std::fs::write(docs.join("note.md"), "# Note\n\nHello world.\n").unwrap();
-
- let source = MemorySourceEntry {
- id: "folder-1".to_string(),
- kind: SourceKind::Folder,
- label: "Docs".to_string(),
- enabled: true,
- path: Some(docs.to_string_lossy().to_string()),
- glob: Some("**/*.md".to_string()),
- url: None,
- toolkit: None,
- connection_id: None,
- branch: None,
- paths: Vec::new(),
- max_commits: None,
- max_issues: None,
- max_prs: None,
- query: None,
- since_days: None,
- max_items: None,
- selector: None,
- max_tokens_per_sync: None,
- max_cost_per_sync_usd: None,
- sync_depth_days: None,
- };
-
- // First call kicks off the background task and returns Ok immediately.
- sync_source(source.clone(), Arc::new(cfg.clone()))
- .await
- .expect("first sync_source should return Ok");
-
- // While the source id may already be released by the time the spawned
- // task finishes, the contract under test is: a call that observes the
- // id already in ACTIVE_SYNCS no-ops. We verify the public contract by
- // hammering several concurrent calls and asserting none error and the
- // audit log records at most as many runs as calls (mutex dedups
- // overlapping work rather than double-processing).
- let mut handles = Vec::new();
- for _ in 0..5 {
- let s = source.clone();
- let c = Arc::new(cfg.clone());
- handles.push(tokio::spawn(async move { sync_source(s, c).await }));
- }
- for h in handles {
- assert!(
- h.await.unwrap().is_ok(),
- "concurrent sync_source calls must all return Ok (no-op when locked)"
- );
- }
-
- // Disabled sources are rejected outright (separate guard, same fn).
- let mut disabled = source.clone();
- disabled.enabled = false;
- let err = sync_source(disabled, Arc::new(cfg.clone()))
- .await
- .unwrap_err();
- assert!(
- err.contains("disabled"),
- "disabled source should be rejected, got: {err}"
- );
-
- // Let the spawned background tasks finish (ingest + audit write). The
- // dispatcher audits Folder syncs; retry_all_failed runs inside the task
- // (zero failed jobs on a clean workspace, so it's a no-op but covered).
- tokio::time::sleep(std::time::Duration::from_millis(800)).await;
-
- let audit = read_audit_log(&cfg);
- assert!(
- audit.iter().any(|e| e.source_kind == "folder"),
- "folder sync should produce a folder audit entry; got {audit:?}"
- );
- // The mutex must prevent runaway duplicate processing: with 6 calls for
- // the same source id, far fewer than 6 audit entries should exist.
- let folder_runs = audit.iter().filter(|e| e.source_kind == "folder").count();
- assert!(
- folder_runs <= 6,
- "mutex should dedup overlapping syncs, saw {folder_runs} folder runs"
- );
-}
-
-// ── Test 5: check_and_rebuild_tree auto-detect (via needs_rebuild) ─────────
-
-/// `check_and_rebuild_tree` is private to the dispatcher; its decision gate
-/// is the public `needs_rebuild`, and its action is `rebuild_tree_from_raw`.
-/// This test drives the same auto-detect → rebuild path the dispatcher runs:
-/// seed raw with no summaries (max_level 0) → `needs_rebuild` returns true →
-/// rebuild → `needs_rebuild` returns false (tree now has summaries).
-#[tokio::test]
-async fn check_and_rebuild_auto_detects_raw_without_summaries() {
- let tmp = TempDir::new().unwrap();
- let cfg = test_config(&tmp);
- let scope = "gmail:auto-at-example-dot-com";
-
- let content_root = cfg.memory_tree_content_root();
- let emails_dir = raw_kind_dir(&content_root, scope, RawKind::Email);
- std::fs::create_dir_all(&emails_dir).unwrap();
- std::fs::write(
- emails_dir.join("1700000000000_a.md"),
- "# A\n\nFirst email.\n",
- )
- .unwrap();
- std::fs::write(
- emails_dir.join("1700000000001_b.md"),
- "# B\n\nSecond email.\n",
- )
- .unwrap();
-
- // Before: raw exists, tree at level 0 → rebuild needed.
- assert!(
- needs_rebuild(&cfg, scope, scope),
- "needs_rebuild must be true when raw files exist with no coverage"
- );
-
- // Drive the rebuild (what check_and_rebuild_tree calls).
- rebuild_tree_from_raw(&cfg, scope, scope).await.unwrap();
-
- // After: tree now has summaries → no further rebuild needed.
- let tree = get_or_create_source_tree(&cfg, scope).unwrap();
- assert!(
- tree.max_level > 0,
- "tree should have summaries after rebuild, max_level={}",
- tree.max_level
- );
- assert!(
- !needs_rebuild(&cfg, scope, scope),
- "needs_rebuild must be false once every raw file is covered"
- );
-
- // A scope with no raw files on disk never triggers a rebuild.
- assert!(
- !needs_rebuild(
- &cfg,
- "gmail:empty-at-example-dot-com",
- "gmail:empty-at-example-dot-com"
- ),
- "needs_rebuild must be false when no raw directory exists"
- );
-}
-
-// ── Test 6: graph export — source roots, doc leaves, orphan linking ────────
-
-// `graph_export_builds_source_roots_doc_leaves_and_orphan_links` used to sit
-// here. `graph_export_rpc` reads the forest through `summary_forest`, which the
-// memory module serves now (#5560), so the case could only run against a loaded
-// module — and what it actually asserted was the host's own shaping of that
-// forest, not the store underneath it. Those assertions moved to
-// `src/openhuman/memory/read_rpc/graph_tests.rs`, where they are a pure
-// function of a hand-built forest and cover more cases than this one could.
diff --git a/tests/ollama_embeddings_fallback_e2e.rs b/tests/ollama_embeddings_fallback_e2e.rs
index 83f6046451..79fe663c53 100644
--- a/tests/ollama_embeddings_fallback_e2e.rs
+++ b/tests/ollama_embeddings_fallback_e2e.rs
@@ -46,9 +46,6 @@ fn ensure_memory_seams() {
.name("ollama-embeddings-fallback-e2e-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- Config::default(),
- ));
})
.expect("spawn ollama embeddings seam installer")
.join()
diff --git a/tests/raw_coverage/agent_archivist_debug_round21_raw_coverage_e2e.rs b/tests/raw_coverage/agent_archivist_debug_round21_raw_coverage_e2e.rs
index b6698e3696..9bbd587c14 100644
--- a/tests/raw_coverage/agent_archivist_debug_round21_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_archivist_debug_round21_raw_coverage_e2e.rs
@@ -179,9 +179,6 @@ impl Tool for EchoTool {
fn setup_provider() -> (TempDir, Arc<MemoryClient>, Arc<dyn MemoryProvider>) {
// The cfg(test)-only installer is out of reach for an external test
// target; the public boot-shaped seam does the same job here.
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- openhuman_core::openhuman::config::Config::default(),
- ));
let tmp = TempDir::new().expect("tempdir");
let workspace = tmp.path().join("ws");
std::fs::create_dir_all(&workspace).expect("workspace dir");
diff --git a/tests/raw_coverage/agent_orchestration_e2e.rs b/tests/raw_coverage/agent_orchestration_e2e.rs
index 01b26839c9..9348fed4e0 100644
--- a/tests/raw_coverage/agent_orchestration_e2e.rs
+++ b/tests/raw_coverage/agent_orchestration_e2e.rs
@@ -129,9 +129,6 @@ fn ensure_memory_seams() {
workspace_dir: workspace,
..openhuman_core::openhuman::config::Config::default()
});
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- Arc::clone(&config),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
index 4ee2067060..5cfbf9e715 100644
--- a/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
@@ -75,9 +75,6 @@ fn ensure_memory_seams() {
.name("agent-session-turn-raw-coverage-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- Arc::new(Config::default()),
- );
})
.expect("spawn agent session turn raw coverage seam installer")
.join()
diff --git a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs b/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
index 6d9be1bc06..ba886453b8 100644
--- a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs
@@ -39,9 +39,6 @@ fn ensure_memory_seams() {
.name("round19-memory-source-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- Arc::new(Config::default()),
- );
})
.expect("spawn round19 memory source seam installer")
.join()
diff --git a/tests/raw_coverage/channels_web_startup_raw_coverage_e2e.rs b/tests/raw_coverage/channels_web_startup_raw_coverage_e2e.rs
index 7cb7411ce2..26aa01da90 100644
--- a/tests/raw_coverage/channels_web_startup_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/channels_web_startup_raw_coverage_e2e.rs
@@ -28,9 +28,6 @@ fn ensure_memory_seams() {
.name("channels-web-startup-raw-coverage-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- Arc::new(Config::default()),
- );
})
.expect("spawn channels web startup raw coverage seam installer")
.join()
diff --git a/tests/raw_coverage/learning_facets_e2e.rs b/tests/raw_coverage/learning_facets_e2e.rs
index ea07cac16d..33da607427 100644
--- a/tests/raw_coverage/learning_facets_e2e.rs
+++ b/tests/raw_coverage/learning_facets_e2e.rs
@@ -115,9 +115,6 @@ fn ensure_memory_seams() {
.stack_size(8 * 1024 * 1024)
.spawn(|| {
let config = Arc::new(shared_config_at(learning_workspace()));
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/raw_coverage/memory_core_threads_raw_coverage_e2e.rs b/tests/raw_coverage/memory_core_threads_raw_coverage_e2e.rs
deleted file mode 100644
index 21cb28f1a4..0000000000
--- a/tests/raw_coverage/memory_core_threads_raw_coverage_e2e.rs
+++ /dev/null
@@ -1,670 +0,0 @@
-//! Round 16 raw integration coverage for memory-core and threads.
-//!
-//! These tests keep all state under temp workspaces and call public Rust
-//! surfaces directly. Run with `--test-threads=1`; thread ops resolve the
-//! workspace through process environment.
-
-use chrono::{Duration, TimeZone, Utc};
-use serde_json::json;
-use std::ffi::OsString;
-use std::fs;
-use std::path::{Path, PathBuf};
-use tempfile::TempDir;
-
-use openhuman_core::openhuman::agent::progress::AgentProgress;
-use openhuman_core::openhuman::config::Config;
-use openhuman_core::openhuman::memory::conversations::{
- ensure_thread, list_threads, CreateConversationThread,
-};
-use openhuman_core::openhuman::memory::read_rpc::{self, ChunkFilter, GraphMode};
-use openhuman_core::openhuman::memory::{
- AppendConversationMessageRequest, ConversationMessageRecord, ConversationMessagesRequest,
- CreateConversationThreadRequest, DeleteConversationThreadRequest, EmptyRequest,
- GenerateConversationThreadTitleRequest, UpdateConversationMessageRequest,
- UpdateConversationThreadLabelsRequest, UpdateConversationThreadTitleRequest,
-};
-use openhuman_core::openhuman::threads::ops as thread_ops;
-use openhuman_core::openhuman::threads::turn_state::{
- self, ClearTurnStateRequest, GetTurnStateRequest, TurnLifecycle, TurnStateMirror,
- TurnStateStore,
-};
-use openhuman_core::openhuman::threads::welcome_migration::migrate_welcome_agent_artifacts;
-use tinymemory_core::store::chunks::store::{upsert_chunks, with_connection};
-use tinymemory_core::store::chunks::types::{
- approx_token_count, chunk_id, Chunk, Metadata, SourceKind, SourceRef,
-};
-use tinymemory_core::store::content;
-use tinymemory_core::store::trees::store as tree_store;
-use tinymemory_core::store::trees::types::{SummaryNode, TreeKind};
-use tinymemory_core::tree::score::embed::pack_embedding;
-use tinymemory_core::tree::score::extract::EntityKind;
-use tinymemory_core::tree::score::resolver::CanonicalEntity;
-use tinymemory_core::tree::score::signals::ScoreSignals;
-use tinymemory_core::tree::score::store::{index_entity, upsert_score, ScoreRow};
-use tinymemory_core::tree_source::get_or_create_source_tree;
-
-struct EnvGuard {
- key: &'static str,
- old: Option<OsString>,
-}
-
-impl EnvGuard {
- fn set_path(key: &'static str, value: &Path) -> Self {
- let old = std::env::var_os(key);
- unsafe {
- std::env::set_var(key, value);
- }
- Self { key, old }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- unsafe {
- match &self.old {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
-
-fn config_in(tmp: &TempDir) -> Config {
- let mut cfg = Config {
- workspace_dir: tmp.path().to_path_buf(),
- embeddings_provider: Some("none".into()),
- memory_provider: Some("cloud".into()),
- ..Config::default()
- };
- cfg.memory_tree.embedding_endpoint = None;
- cfg.memory_tree.embedding_model = None;
- cfg.memory_tree.embedding_strict = false;
- cfg
-}
-
-fn test_chunk(source_id: &str, seq: u32, content: &str, ts_ms: i64) -> Chunk {
- let ts = Utc.timestamp_millis_opt(ts_ms).single().unwrap();
- let mut metadata = Metadata::point_in_time(SourceKind::Chat, source_id, "owner@example", ts);
- metadata.tags = vec!["round16".into(), format!("seq-{seq}")];
- metadata.source_ref = Some(SourceRef::new(format!("chat://{source_id}/{seq}")));
- Chunk {
- id: chunk_id(SourceKind::Chat, source_id, seq, content),
- content: content.to_string(),
- metadata,
- token_count: approx_token_count(content),
- seq_in_source: seq,
- created_at: ts,
- partial_message: false,
- }
-}
-
-fn seed_content_paths(cfg: &Config, chunks: &[Chunk]) {
- let root = cfg.memory_tree_content_root();
- fs::create_dir_all(&root).unwrap();
- let staged = content::stage_chunks(&root, chunks).unwrap();
- with_connection(cfg, |conn| {
- for staged_chunk in &staged {
- conn.execute(
- "UPDATE mem_tree_chunks
- SET content_path = ?1, content_sha256 = ?2
- WHERE id = ?3",
- rusqlite::params![
- staged_chunk.content_path,
- staged_chunk.content_sha256,
- staged_chunk.chunk.id,
- ],
- )?;
- }
- Ok(())
- })
- .unwrap();
-}
-
-fn insert_summary(cfg: &Config, node: &SummaryNode, content_path: Option<&str>) {
- let embedding = node
- .embedding
- .as_ref()
- .map(|v| pack_embedding(v))
- .unwrap_or_default();
- with_connection(cfg, |conn| {
- conn.execute(
- "INSERT OR REPLACE INTO mem_tree_summaries (
- id, tree_id, tree_kind, level, parent_id, child_ids_json,
- content, token_count, entities_json, topics_json,
- time_range_start_ms, time_range_end_ms, score, sealed_at_ms,
- deleted, embedding, content_path
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)",
- rusqlite::params![
- node.id,
- node.tree_id,
- node.tree_kind.as_str(),
- node.level as i64,
- node.parent_id,
- serde_json::to_string(&node.child_ids)?,
- node.content,
- node.token_count as i64,
- serde_json::to_string(&node.entities)?,
- serde_json::to_string(&node.topics)?,
- node.time_range_start.timestamp_millis(),
- node.time_range_end.timestamp_millis(),
- node.score,
- node.sealed_at.timestamp_millis(),
- i32::from(node.deleted),
- if embedding.is_empty() {
- None
- } else {
- Some(embedding)
- },
- content_path,
- ],
- )?;
- Ok(())
- })
- .unwrap();
-}
-
-fn daily_node(id: &str, tree_id: &str, day: chrono::DateTime<Utc>) -> SummaryNode {
- SummaryNode {
- id: id.into(),
- tree_id: tree_id.into(),
- tree_kind: TreeKind::Global,
- level: 0,
- parent_id: None,
- child_ids: Vec::new(),
- content: format!("Daily digest for {id} with Alice and Phoenix planning."),
- token_count: 64,
- entities: vec!["person:alice".into()],
- topics: vec!["phoenix".into()],
- time_range_start: day,
- time_range_end: day + Duration::hours(1),
- score: 0.7,
- sealed_at: day + Duration::hours(2),
- deleted: false,
- embedding: Some(vec![0.0; 1024]),
- doc_id: None,
- version_ms: None,
- }
-}
-
-// Serialize env mutation against every other aggregated suite via the
-// single crate-wide SHARED_ENV_LOCK (these tests use an `EnvGuard` struct
-// that does not itself hold a lock). Poison is recovered so a panic
-// elsewhere cannot wedge the suite.
-fn __shared_env_lock() -> std::sync::MutexGuard<'static, ()> {
- crate::SHARED_ENV_LOCK
- .get_or_init(|| std::sync::Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-#[tokio::test]
-async fn memory_read_rpc_filters_graphs_scores_reset_and_wipe_seeded_rows() {
- let _env_lock = __shared_env_lock();
- let tmp = TempDir::new().unwrap();
- let cfg = config_in(&tmp);
- // The `read_rpc` listings below go through the bound memory driver, which
- // under the `modules` gate is the loaded tinymemory artifact. That driver
- // resolves its config from the process-wide boot policy, so a test binary
- // has to publish one the way boot does. The policy is first-call-wins and
- // the module takes its `workspace_dir` at load time, so it is built from
- // THIS test's `cfg`: the rows seeded in-process below and the rows the
- // module lists must name the same store. No other case in this aggregated
- // binary routes through the module, so nothing contends for the slot.
- #[cfg(feature = "modules")]
- openhuman_core::openhuman::modules::memory::set_modules_policy(std::sync::Arc::new(
- cfg.clone(),
- ));
- let ts0 = Utc.with_ymd_and_hms(2026, 5, 20, 9, 0, 0).unwrap();
- let chunks = vec![
- test_chunk(
- 0,
- "Alice shared the Phoenix launch checklist and budget.",
- ts0.timestamp_millis(),
- ),
- test_chunk(
- "slack:#ops",
- 1,
- "Bob asked Alice for the deploy window in Phoenix.",
- (ts0 + Duration::hours(1)).timestamp_millis(),
- ),
- ];
- upsert_chunks(&cfg, &chunks).unwrap();
- seed_content_paths(&cfg, &chunks);
-
- let alice = CanonicalEntity {
- canonical_id: "person:alice".into(),
- kind: EntityKind::Person,
- surface: "Alice".into(),
- span_start: 0,
- span_end: 5,
- score: 0.95,
- };
- let topic = CanonicalEntity {
- canonical_id: "topic:phoenix".into(),
- kind: EntityKind::Topic,
- surface: "Phoenix".into(),
- span_start: 0,
- span_end: 7,
- score: 0.8,
- };
- for chunk in &chunks {
- index_entity(
- &cfg,
- &alice,
- &chunk.id,
- "leaf",
- chunk.metadata.timestamp.timestamp_millis(),
- Some("source:chat"),
- )
- .unwrap();
- index_entity(
- &cfg,
- &topic,
- &chunk.id,
- "leaf",
- chunk.metadata.timestamp.timestamp_millis(),
- Some("source:chat"),
- )
- .unwrap();
- }
- upsert_score(
- &cfg,
- &ScoreRow {
- chunk_id: chunks[0].id.clone(),
- total: 4.5,
- signals: ScoreSignals {
- token_count: 0.4,
- unique_words: 0.8,
- metadata_weight: 1.0,
- source_weight: 0.9,
- interaction: 0.7,
- entity_density: 0.6,
- llm_importance: 0.5,
- },
- dropped: false,
- reason: Some("coverage fixture".into()),
- computed_at_ms: ts0.timestamp_millis(),
- llm_importance_reason: Some("important planning".into()),
- },
- )
- .unwrap();
-
- let tree = get_or_create_source_tree(&cfg, "gmail:[email protected]|[email protected]").unwrap();
- let summary = SummaryNode {
- id: "summary:L1:round16".into(),
- tree_id: tree.id.clone(),
- tree_kind: TreeKind::Source,
- level: 1,
- parent_id: None,
- child_ids: chunks.iter().map(|c| c.id.clone()).collect(),
- content: "Alice and Bob discussed Phoenix launch operations.".into(),
- token_count: 80,
- entities: vec!["person:alice".into()],
- topics: vec!["phoenix".into()],
- time_range_start: ts0,
- time_range_end: ts0 + Duration::hours(2),
- score: 0.9,
- sealed_at: ts0 + Duration::hours(3),
- deleted: false,
- embedding: Some(vec![0.0; 1024]),
- doc_id: None,
- version_ms: None,
- };
- insert_summary(
- &cfg,
- &summary,
- Some("wiki/summaries/source/summary-L1-round16.md"),
- );
-
- let listed = read_rpc::list_chunks_rpc(
- &cfg,
- ChunkFilter {
- source_kinds: Some(vec!["chat".into()]),
- entity_ids: Some(vec!["person:alice".into()]),
- query: Some("Phoenix".into()),
- limit: Some(10),
- ..ChunkFilter::default()
- },
- )
- .await
- .unwrap();
- assert_eq!(listed.value.total, 2);
- assert!(listed.value.chunks[0].content_preview.is_some());
-
- let sources = read_rpc::list_sources_rpc(&cfg, Some("[email protected]".into()))
- .await
- .unwrap();
- assert!(sources.value.iter().any(|source| source.source_id
- && source.chunk_count == 1));
-
- assert_eq!(
- read_rpc::search_rpc(&cfg, "deploy".into(), 5)
- .await
- .unwrap()
- .value
- .len(),
- 1
- );
- assert_eq!(
- read_rpc::entity_index_for_rpc(&cfg, chunks[0].id.clone())
- .await
- .unwrap()
- .value
- .len(),
- 2
- );
- assert_eq!(
- read_rpc::chunks_for_entity_rpc(&cfg, "person:alice".into())
- .await
- .unwrap()
- .value
- .len(),
- 2
- );
- assert_eq!(
- read_rpc::top_entities_rpc(&cfg, Some("person".into()), 5)
- .await
- .unwrap()
- .value[0]
- .entity_id,
- "person:alice"
- );
- let score = read_rpc::chunk_score_rpc(&cfg, chunks[0].id.clone())
- .await
- .unwrap()
- .value
- .unwrap();
- assert!(score.kept);
- assert!(
- !score.llm_consulted,
- "TinyCortex does not persist admission-time LLM importance"
- );
-
- let tree_graph = read_rpc::graph_export_rpc(&cfg, GraphMode::Tree)
- .await
- .unwrap();
- assert!(tree_graph
- .value
- .nodes
- .iter()
- .any(|node| node.kind == "summary"));
- let contacts_graph = read_rpc::graph_export_rpc(&cfg, GraphMode::Contacts)
- .await
- .unwrap();
- assert!(contacts_graph.value.edges.len() >= 2);
- assert!(
- !read_rpc::obsidian_vault_status_rpc(&cfg, Some(" ".into()))
- .await
- .unwrap()
- .value
- .registered
- );
-
- let deleted = read_rpc::delete_chunk_rpc(&cfg, chunks[1].id.clone())
- .await
- .unwrap();
- assert!(deleted.value.deleted);
- assert_eq!(deleted.value.entity_index_rows_removed, 2);
- assert!(
- !read_rpc::delete_chunk_rpc(&cfg, "missing-chunk".into())
- .await
- .unwrap()
- .value
- .deleted
- );
-
- // `reset_tree` and `flush_now` are deliberately no longer exercised here.
- // Both read and mutate through the bound memory driver now
- // (`Maintenance::reset_derived_index` / `flush_pending`), and an
- // integration test cannot bind one: with nothing bound the resolve
- // refuses, and with a real module on the path it answers from the
- // module's own store rather than the rows staged above. Their behaviour
- // is pinned where a real store exists — the driver's conformance suite
- // (`resetting_the_derived_index_keeps_the_chunks_it_derives_from`,
- // `flushing_twice_in_a_window_schedules_the_work_once`) — and the host's
- // wire mapping in `read_rpc_tests`.
-
- fs::create_dir_all(cfg.memory_tree_content_root().join("raw")).unwrap();
- fs::write(cfg.memory_tree_content_root().join("raw").join("x.md"), "x").unwrap();
- let wipe = read_rpc::wipe_all_rpc(&cfg).await.unwrap().value;
- assert!(wipe.rows_deleted >= 1);
- assert!(wipe.dirs_removed.iter().any(|dir| dir == "raw"));
-}
-
-#[tokio::test]
-async fn thread_ops_welcome_migration_and_turn_state_cover_error_and_cleanup_paths() {
- let _env_lock = __shared_env_lock();
- let tmp = TempDir::new().unwrap();
- let _env = EnvGuard::set_path("OPENHUMAN_WORKSPACE", tmp.path());
- let workspace = Config::load_or_init().await.unwrap().workspace_dir;
-
- ensure_thread(
- workspace.clone(),
- CreateConversationThread {
- id: "legacy-thread".into(),
- title: "Legacy".into(),
- created_at: "2026-05-01T00:00:00Z".into(),
- parent_thread_id: None,
- labels: Some(vec!["onboarding".into(), "inbox".into()]),
- personality_id: None,
- },
- )
- .unwrap();
- write_welcome_transcript(&workspace, "20260501_welcome", "welcome", "legacy-thread");
- fs::create_dir_all(workspace.join("sessions").join("legacy-thread")).unwrap();
- fs::write(
- workspace
- .join("sessions")
- .join("legacy-thread")
- .join("20260501_welcome.md"),
- "markdown",
- )
- .unwrap();
-
- let migration = migrate_welcome_agent_artifacts(&workspace).unwrap();
- assert_eq!(migration.threads_updated, 1);
- assert_eq!(migration.transcripts_updated, 1);
- assert_eq!(migration.transcript_files_renamed, 1);
- assert!(
- migrate_welcome_agent_artifacts(&workspace)
- .unwrap()
- .already_done
- );
- assert!(list_threads(workspace.clone())
- .unwrap()
- .into_iter()
- .find(|thread| thread.id == "legacy-thread")
- .unwrap()
- .labels
- .iter()
- .all(|label| label != "onboarding"));
-
- let created = thread_ops::thread_create_new(CreateConversationThreadRequest {
- labels: Some(vec!["chat".into()]),
- personality_id: Some("default".into()),
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap();
- let thread_id = created.id;
-
- let msg_id = "msg-round16".to_string();
- let appended = thread_ops::message_append(AppendConversationMessageRequest {
- thread_id: thread_id.clone(),
- message: ConversationMessageRecord {
- id: msg_id.clone(),
- content: "Please summarize the Phoenix budget risks for Alice.".into(),
- message_type: "text".into(),
- extra_metadata: json!({"draft": true}),
- sender: "user".into(),
- created_at: "2026-05-21T10:00:00Z".into(),
- },
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap();
- assert_eq!(appended.id, msg_id);
-
- let generated = thread_ops::thread_generate_title(GenerateConversationThreadTitleRequest {
- thread_id: thread_id.clone(),
- assistant_message: None,
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap();
- assert!(generated.title.contains("Phoenix") || generated.title.contains("budget"));
-
- assert!(
- thread_ops::thread_update_title(UpdateConversationThreadTitleRequest {
- thread_id: thread_id.clone(),
- title: " ".into(),
- })
- .await
- .is_err()
- );
- assert_eq!(
- thread_ops::thread_update_labels(UpdateConversationThreadLabelsRequest {
- thread_id: thread_id.clone(),
- labels: vec!["starred".into(), "archive".into()],
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap()
- .labels,
- vec!["starred", "archive"]
- );
- let updated_msg = thread_ops::message_update(UpdateConversationMessageRequest {
- thread_id: thread_id.clone(),
- message_id: msg_id.clone(),
- extra_metadata: Some(json!({"draft": false, "edited": true})),
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap();
- assert_eq!(updated_msg.extra_metadata["edited"], true);
- assert_eq!(
- thread_ops::messages_list(ConversationMessagesRequest {
- thread_id: thread_id.clone()
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap()
- .count,
- 1
- );
-
- let store = TurnStateStore::new(workspace.clone());
- let mut mirror = TurnStateMirror::new(store, &thread_id, "request-round16");
- assert!(!mirror.observe(&AgentProgress::ToolCallArgsDelta {
- call_id: "call-1".into(),
- tool_name: "memory.search".into(),
- delta: "{\"q\":\"phoenix\"}".into(),
- iteration: 1,
- }));
- assert!(mirror.observe(&AgentProgress::ToolCallStarted {
- call_id: "call-1".into(),
- tool_name: "memory.search".into(),
- arguments: json!({"q": "phoenix"}),
- iteration: 1,
- display_label: None,
- display_detail: None,
- }));
- assert!(mirror.observe(&AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "task-1".into(),
- mode: "typed".into(),
- dedicated_thread: true,
- prompt_chars: 42,
- prompt: String::new(),
- worker_thread_id: None,
- display_name: Some("Researcher".into()),
- }));
- assert!(mirror.observe(&AgentProgress::SubagentCompleted {
- agent_id: "researcher".into(),
- task_id: "task-1".into(),
- elapsed_ms: 50,
- iterations: 2,
- output_chars: 100,
- output: String::new(),
- worktree_path: None,
- changed_files: vec![],
- dirty_status: None,
- }));
- mirror.finish();
-
- let turn_get = thread_ops::turn_state_get(GetTurnStateRequest {
- thread_id: thread_id.clone(),
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap();
- assert_eq!(
- turn_get.turn_state.unwrap().lifecycle,
- TurnLifecycle::Interrupted
- );
- assert!(
- thread_ops::turn_state_clear(ClearTurnStateRequest {
- thread_id: thread_id.clone()
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap()
- .cleared
- );
- assert!(turn_state::store::get(workspace.clone(), &thread_id)
- .unwrap()
- .is_none());
-
- let deleted = thread_ops::thread_delete(DeleteConversationThreadRequest {
- thread_id: thread_id.clone(),
- deleted_at: "2026-05-21T12:00:00Z".into(),
- })
- .await
- .unwrap()
- .value
- .data
- .unwrap();
- assert!(deleted.deleted);
- assert!(
- thread_ops::thread_generate_title(GenerateConversationThreadTitleRequest {
- thread_id,
- assistant_message: Some("unused".into()),
- })
- .await
- .is_err()
- );
-
- let purged = thread_ops::threads_purge(EmptyRequest {}).await.unwrap();
- assert_eq!(purged.value.data.unwrap().agent_threads_deleted, 1);
-}
-
-fn write_welcome_transcript(workspace: &Path, stem: &str, agent: &str, thread_id: &str) -> PathBuf {
- let path = workspace.join("session_raw").join(format!("{stem}.jsonl"));
- fs::create_dir_all(path.parent().unwrap()).unwrap();
- fs::write(
- &path,
- format!(
- "{{\"_meta\":{{\"agent\":\"{agent}\",\"dispatcher\":\"native\",\"created\":\"2026-05-01T00:00:00Z\",\"updated\":\"2026-05-01T00:00:00Z\",\"turn_count\":1,\"input_tokens\":0,\"output_tokens\":0,\"cached_input_tokens\":0,\"charged_amount_usd\":0.0,\"thread_id\":\"{thread_id}\"}}}}\n{{\"role\":\"user\",\"content\":\"hi\"}}\n"
- ),
- )
- .unwrap();
- path
-}
diff --git a/tests/raw_coverage/memory_goals_people_e2e.rs b/tests/raw_coverage/memory_goals_people_e2e.rs
index 00b0f515e4..c87b7979ac 100644
--- a/tests/raw_coverage/memory_goals_people_e2e.rs
+++ b/tests/raw_coverage/memory_goals_people_e2e.rs
@@ -105,9 +105,6 @@ fn ensure_memory_seams() {
.stack_size(8 * 1024 * 1024)
.spawn(|| {
let config = Arc::new(shared_config_at(memory_workspace()));
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- config.clone(),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/raw_coverage/memory_raw_coverage_e2e.rs b/tests/raw_coverage/memory_raw_coverage_e2e.rs
deleted file mode 100644
index 4c66f97f55..0000000000
--- a/tests/raw_coverage/memory_raw_coverage_e2e.rs
+++ /dev/null
@@ -1,685 +0,0 @@
-//! Focused raw integration coverage for memory-family modules.
-//!
-//! These tests avoid network and keep all state in per-test tempdirs. Run with
-//! `--test-threads=1` because several memory surfaces use process-global
-//! stores or cached SQLite connections.
-
-use chrono::{TimeZone, Utc};
-use serde_json::json;
-use tempfile::TempDir;
-
-use openhuman_core::openhuman::config::Config;
-use openhuman_core::openhuman::memory::NamespaceDocumentInput;
-// The engine's own ingest request/config — what `UnifiedMemory::ingest_document`
-// takes. `memory::MemoryIngestion*` are the host's WIRE shapes now
-// (`rpc_models`), distinct types (#5560).
-use tinycortex::memory::ingest::{ExtractionMode, MemoryIngestionConfig, MemoryIngestionRequest};
-// The in-process ingest queue is the engine's and has no bus representation, so
-// `memory::mod` stopped re-exporting it for a consumer that was only ever this
-// test (#5560). Named on the crate directly, exactly as `upsert_chunks` below
-// already is — `tinymemory-core` is a dev-dependency, which this target links.
-use tinymemory_core::ingestion::IngestionState;
-// The engine's per-source SQL read, which is what this suite seeds a store for.
-// `memory::sources::status` is host-side now and asks the bound driver, which an
-// integration test has no module to load (#5560).
-use tinymemory_core::sources::status::{source_status, FreshnessLabel};
-use openhuman_core::openhuman::memory::sources::{MemorySourceEntry, SourceKind};
-use tinymemory_core::store::chunks::store::upsert_chunks;
-use tinymemory_core::store::chunks::types::{
- approx_token_count, chunk_id, Chunk, Metadata, SourceKind as ChunkSourceKind, SourceRef,
-};
-use tinycortex::memory::ingest::canonicalize::chat::{
- canonicalise as canonicalise_chat, ChatBatch, ChatMessage,
-};
-use tinycortex::memory::ingest::canonicalize::document::{
- canonicalise as canonicalise_document, DocumentInput,
-};
-use tinycortex::memory::ingest::canonicalize::email::{
- canonicalise as canonicalise_email, EmailMessage, EmailThread,
-};
-// These scope/catalog helpers moved off `memory::sync::composio::providers`
-// (the deleted engine registry's former home) onto
-// `integrations::composio::providers`, which re-exports them straight from
-// the `tinymemory-api` contract crate — see that module's doc comment.
-use openhuman_core::openhuman::integrations::composio::providers::{
- classify_unknown, find_curated, toolkit_from_slug, CuratedTool, ToolScope,
-};
-use tinycortex::memory::sync::{SyncOutcome, SyncPipelineKind};
-use tinymemory_core::tree::summarise::{
- fallback_summary, SummaryContext, SummaryInput,
-};
-use tinymemory_core::tree::tree_runtime::store as tree_store;
-use openhuman_core::openhuman::memory::tree::tree_runtime::{
- derive_node_ids, estimate_tokens, level_from_node_id, node_id_to_path, NodeLevel, TreeNode,
-};
-use openhuman_core::openhuman::threads::turn_state::{
- SubagentActivity, SubagentToolCall, ToolTimelineEntry, ToolTimelineStatus, TurnLifecycle,
- TurnPhase, TurnState, TurnStateStore,
-};
-
-fn config_in(tmp: &TempDir) -> Config {
- Config {
- workspace_dir: tmp.path().to_path_buf(),
- ..Config::default()
- }
-}
-
-fn source_entry(kind: SourceKind, id: &str) -> MemorySourceEntry {
- MemorySourceEntry {
- id: id.to_string(),
- kind,
- label: format!("{id} label"),
- enabled: true,
- toolkit: None,
- connection_id: None,
- path: None,
- glob: None,
- url: None,
- branch: None,
- paths: Vec::new(),
- query: None,
- since_days: None,
- max_items: None,
- max_commits: None,
- max_issues: None,
- max_prs: None,
- selector: None,
- max_tokens_per_sync: None,
- max_cost_per_sync_usd: None,
- sync_depth_days: None,
- }
-}
-
-fn tree_node(namespace: &str, node_id: &str, summary: &str) -> TreeNode {
- let ts = Utc.with_ymd_and_hms(2026, 5, 29, 12, 30, 0).unwrap();
- TreeNode {
- node_id: node_id.to_string(),
- namespace: namespace.to_string(),
- level: level_from_node_id(node_id),
- parent_id: openhuman_core::openhuman::memory::tree::tree_runtime::derive_parent_id(node_id),
- summary: summary.to_string(),
- token_count: estimate_tokens(summary),
- child_count: 0,
- created_at: ts,
- updated_at: ts,
- metadata: Some(json!({ "test": "memory_raw_coverage", "node": node_id }).to_string()),
- }
-}
-
-fn chunk(source_id: &str, seq: u32, timestamp_ms: i64, embedding_pending: bool) -> Chunk {
- let content = format!("memory raw coverage chunk {source_id} #{seq}");
- let ts = Utc.timestamp_millis_opt(timestamp_ms).unwrap();
- let mut metadata = Metadata::point_in_time(ChunkSourceKind::Document, source_id, "owner", ts);
- metadata.tags = vec!["coverage".into()];
- metadata.source_ref = Some(SourceRef::new(format!("file:///{source_id}/{seq}")));
- let mut chunk = Chunk {
- id: chunk_id(ChunkSourceKind::Document, source_id, seq, &content),
- content,
- metadata,
- token_count: approx_token_count(source_id),
- seq_in_source: seq,
- created_at: ts,
- partial_message: false,
- };
- if !embedding_pending {
- chunk.partial_message = true;
- }
- chunk
-}
-
-#[test]
-fn memory_tree_store_round_trips_nodes_buffers_and_validation_edges() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
- let ns = "raw/coverage:tree";
-
- assert!(tree_store::validate_namespace("personal").is_ok());
- assert!(tree_store::validate_namespace(" ").is_err());
- assert!(tree_store::validate_namespace("../escape").is_err());
- assert!(tree_store::validate_namespace("/absolute").is_err());
- assert!(tree_store::validate_node_id("root").is_ok());
- assert!(tree_store::validate_node_id("2026/05/29/23").is_ok());
- assert!(tree_store::validate_node_id("2026/13").is_err());
- assert!(tree_store::validate_node_id("2026/05/32").is_err());
- assert!(tree_store::validate_node_id("2026/05/29/24").is_err());
- assert!(tree_store::validate_node_id("../root").is_err());
-
- for (node_id, summary) in [
- ("root", "Root summary for the workspace"),
- ("2026", "Year summary"),
- ("2026/05", "Month summary"),
- ("2026/05/29", "Day summary"),
- ("2026/05/29/12", "Hour leaf summary"),
- ] {
- tree_store::write_node(&config, &tree_node(ns, node_id, summary)).expect("write node");
- }
-
- let root = tree_store::read_node(&config, ns, "root")
- .expect("read root")
- .expect("root exists");
- assert_eq!(root.level, NodeLevel::Root);
- assert_eq!(root.parent_id, None);
-
- let root_children = tree_store::read_children(&config, ns, "root").expect("root children");
- assert_eq!(root_children.len(), 1);
- assert_eq!(root_children[0].node_id, "2026");
- let day_children = tree_store::read_children(&config, ns, "2026/05/29").expect("day children");
- assert_eq!(day_children[0].node_id, "2026/05/29/12");
-
- let ancestors = tree_store::read_ancestors(&config, ns, "2026/05/29/12").expect("ancestors");
- assert_eq!(
- ancestors
- .iter()
- .map(|n| n.node_id.as_str())
- .collect::<Vec<_>>(),
- vec!["2026/05/29", "2026/05", "2026", "root"]
- );
-
- let status = tree_store::get_tree_status(&config, ns).expect("status");
- assert_eq!(status.total_nodes, 5);
- assert_eq!(status.depth, 5);
- assert!(status.oldest_entry.is_some());
- assert!(status.newest_entry.is_some());
-
- let ts = Utc.with_ymd_and_hms(2026, 5, 29, 13, 0, 0).unwrap();
- let first =
- tree_store::buffer_write(&config, ns, "plain buffer", &ts, None).expect("buffer write");
- let second = tree_store::buffer_write(
- &config,
- ns,
- "frontmatter buffer",
- &ts,
- Some(&json!({ "source": "test" })),
- )
- .expect("buffer write with metadata");
- assert!(first.exists());
- assert!(second.exists());
-
- let buffered = tree_store::buffer_read(&config, ns).expect("buffer read");
- assert_eq!(buffered.len(), 2);
- assert!(buffered.iter().any(|(_, body)| body == "plain buffer"));
- assert!(buffered
- .iter()
- .any(|(_, body)| body == "frontmatter buffer"));
-
- let drained = tree_store::buffer_drain(&config, ns).expect("buffer drain");
- assert_eq!(drained.len(), 2);
- assert!(tree_store::buffer_read(&config, ns)
- .expect("buffer empty")
- .is_empty());
-
- let collected = tree_store::collect_root_summaries_with_caps(tmp.path(), 10, 12);
- assert_eq!(collected.len(), 1);
- assert!(collected[0].1.contains("Root summa"));
- assert!(collected[0].1.contains("truncated"));
-
- let deleted = tree_store::delete_tree(&config, ns).expect("delete tree");
- assert_eq!(deleted, 5);
- assert_eq!(
- tree_store::delete_tree(&config, ns).expect("delete missing"),
- 0
- );
- assert!(tree_store::read_node(&config, ns, "root")
- .expect("read missing")
- .is_none());
-}
-
-#[test]
-fn memory_tree_types_and_fallback_summary_cover_budget_and_legacy_parse_paths() {
- let ts = Utc.with_ymd_and_hms(2026, 5, 29, 9, 8, 7).unwrap();
- let (hour, day, month, year, root) = derive_node_ids(&ts);
- assert_eq!(root, "root");
- assert_eq!(year, "2026");
- assert_eq!(month, "2026/05");
- assert_eq!(day, "2026/05/29");
- assert_eq!(hour, "2026/05/29/09");
- assert_eq!(node_id_to_path("root").to_string_lossy(), "root.md");
- assert!(node_id_to_path("2026/05/29/09")
- .to_string_lossy()
- .ends_with("2026/05/29/09.md"));
- assert_eq!(NodeLevel::Hour.parent_level(), Some(NodeLevel::Day));
- assert!(NodeLevel::Hour.is_leaf());
- assert_eq!(NodeLevel::Root.max_tokens(), 20_000);
- assert_eq!(NodeLevel::from_str_label("month"), Some(NodeLevel::Month));
- assert_eq!(NodeLevel::from_str_label("bogus"), None);
-
- let legacy = "---\nlevel: hour\nparent_id: \"2026/05/29\"\ntoken_count: 3\n---\n\nlegacy body";
- let parsed = tree_store::parse_node_markdown_pub(legacy, "legacy", "2026/05/29/09")
- .expect("legacy parse");
- assert_eq!(parsed.created_at.timestamp(), 0);
- assert_eq!(parsed.updated_at, parsed.created_at);
- assert_eq!(parsed.summary, "legacy body");
-
- let inputs = vec![
- SummaryInput {
- id: "blank".into(),
- content: " ".into(),
- token_count: 0,
- entities: vec!["ignored".into()],
- topics: vec![],
- time_range_start: ts,
- time_range_end: ts,
- score: 0.1,
- },
- SummaryInput {
- id: "long".into(),
- content: "alpha beta gamma delta epsilon zeta eta theta".repeat(20),
- token_count: 200,
- entities: vec![],
- topics: vec!["planning".into()],
- time_range_start: ts,
- time_range_end: ts,
- score: 0.9,
- },
- ];
- let out = fallback_summary(&inputs, 8);
- assert!(out.content.starts_with("— alpha"));
- assert!(out.token_count <= 9);
- assert!(out.entities.is_empty());
- assert!(out.topics.is_empty());
-
- let ctx = SummaryContext {
- tree_id: "tree-coverage",
- tree_kind: tinymemory_core::store::trees::types::TreeKind::Global,
- target_level: 2,
- token_budget: 128,
- input_token_budget: tinycortex::memory::config::INPUT_TOKEN_BUDGET,
- overhead_reserve_tokens: tinycortex::memory::config::SUMMARY_OVERHEAD_RESERVE_TOKENS,
- ask: None,
- };
- assert_eq!(ctx.tree_id, "tree-coverage");
- assert_eq!(ctx.target_level, 2);
-}
-
-#[tokio::test]
-async fn memory_sources_status_counts_folder_and_composio_prefixes() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
- let folder_source_id = "mem_src:folder-alpha:file-a.md";
- let gmail_source_id = "gmail:conn-1:message-1";
-
- let now = Utc::now().timestamp_millis();
- upsert_chunks(
- &config,
- &[
- chunk(folder_source_id, 0, now - 1_000, true),
- chunk(folder_source_id, 1, now - 400_000, false),
- chunk(gmail_source_id, 0, now - 2_000, true),
- ],
- )
- .expect("upsert chunks");
-
- let mut folder = source_entry(SourceKind::Folder, "folder-alpha");
- folder.path = Some(tmp.path().to_string_lossy().into_owned());
- let folder_status = source_status(&config, &folder)
- .await
- .expect("folder status");
- assert_eq!(folder_status.source_id, "folder-alpha");
- assert_eq!(folder_status.chunks_synced, 2);
- assert_eq!(folder_status.chunks_pending, 2);
- assert_eq!(folder_status.freshness, FreshnessLabel::Active);
-
- let mut composio = source_entry(SourceKind::Composio, "gmail-source");
- composio.toolkit = Some("gmail".into());
- composio.connection_id = Some("conn-1".into());
- let composio_status = source_status(&config, &composio)
- .await
- .expect("composio status");
- assert_eq!(composio_status.chunks_synced, 1);
- assert_eq!(composio_status.freshness, FreshnessLabel::Active);
-
- let mut missing_toolkit = composio.clone();
- missing_toolkit.id = "missing-toolkit".into();
- missing_toolkit.toolkit = None;
- let missing = source_status(&config, &missing_toolkit)
- .await
- .expect("missing toolkit status");
- assert_eq!(missing.chunks_synced, 0);
- assert_eq!(missing.freshness, FreshnessLabel::Idle);
-
- assert_eq!(FreshnessLabel::from_age_ms(None, now), FreshnessLabel::Idle);
- assert_eq!(
- FreshnessLabel::from_age_ms(Some(now - 60_000), now),
- FreshnessLabel::Recent
- );
- assert_eq!(
- FreshnessLabel::from_age_ms(Some(now - 600_000), now),
- FreshnessLabel::Idle
- );
-}
-
-#[test]
-fn memory_sources_validation_and_sync_classification_edges() {
- let mut entry = source_entry(SourceKind::Folder, "src-folder");
- assert_eq!(entry.kind.as_str(), "folder");
- assert!(entry.validate().is_err());
- entry.path = Some("/tmp/notes".into());
- assert!(entry.validate().is_ok());
-
- let mut github = source_entry(SourceKind::GithubRepo, "src-github");
- assert!(github.validate().is_err());
- github.url = Some("https://github.com/tinyhumansai/openhuman".into());
- assert!(github.validate().is_ok());
-
- let mut twitter = source_entry(SourceKind::TwitterQuery, "src-twitter");
- assert!(twitter.validate().is_err());
- twitter.query = Some("openhuman".into());
- assert!(twitter.validate().is_ok());
-
- let mut rss = source_entry(SourceKind::RssFeed, "src-rss");
- rss.url = Some("https://example.com/feed.xml".into());
- assert_eq!(rss.kind.as_str(), "rss_feed");
- assert!(rss.validate().is_ok());
-
- let mut web = source_entry(SourceKind::WebPage, "src-web");
- web.url = Some("https://example.com/page".into());
- assert_eq!(web.kind.as_str(), "web_page");
- assert!(web.validate().is_ok());
-
- let mut composio = source_entry(SourceKind::Composio, "src-composio");
- composio.toolkit = Some("gmail".into());
- assert!(composio.validate().is_err());
- composio.connection_id = Some("conn".into());
- assert!(composio.validate().is_ok());
-
- assert_eq!(classify_unknown("GMAIL_DELETE_DRAFT"), ToolScope::Admin);
- assert_eq!(classify_unknown("NOTION_CREATE_PAGE"), ToolScope::Write);
- assert_eq!(classify_unknown("GMAIL_FETCH_EMAILS"), ToolScope::Read);
- assert_eq!(
- toolkit_from_slug(" MICROSOFT_TEAMS_SEND "),
- Some("microsoft_teams".into())
- );
- assert_eq!(toolkit_from_slug(""), None);
- let catalog = [CuratedTool {
- slug: "GMAIL_SEND_EMAIL",
- scope: ToolScope::Write,
- }];
- assert_eq!(
- find_curated(&catalog, "gmail_send_email").unwrap().scope,
- ToolScope::Write
- );
- assert!(find_curated(&catalog, "GMAIL_DELETE_EMAIL").is_none());
-
- assert_eq!(ToolScope::Admin.as_str(), "admin");
- assert_eq!(SyncPipelineKind::Composio.as_str(), "composio");
- assert_eq!(SyncPipelineKind::Workspace.as_str(), "workspace");
- assert_eq!(SyncPipelineKind::Mcp.as_str(), "mcp");
- let outcome = SyncOutcome {
- records_ingested: 3,
- more_pending: true,
- note: Some("paged".into()),
- ..SyncOutcome::default()
- };
- let encoded = serde_json::to_value(&outcome).expect("sync outcome json");
- assert_eq!(encoded["records_ingested"], 3);
- assert_eq!(encoded["more_pending"], true);
-}
-
-#[test]
-fn memory_sync_canonicalizers_sort_clean_and_preserve_provenance() {
- let t1 = Utc.timestamp_millis_opt(1_700_000_000_000).unwrap();
- let t2 = Utc.timestamp_millis_opt(1_700_000_010_000).unwrap();
-
- assert!(canonicalise_chat(
- "slack:empty",
- "alice",
- &[],
- ChatBatch {
- platform: "slack".into(),
- channel_label: "#empty".into(),
- messages: vec![],
- },
- )
- .expect("empty chat")
- .is_none());
-
- let chat = canonicalise_chat(
- "slack:#eng",
- &["eng".into()],
- ChatBatch {
- platform: "slack".into(),
- channel_label: "#eng".into(),
- messages: vec![
- ChatMessage {
- author: "Bob".into(),
- timestamp: t2,
- text: "second".into(),
- source_ref: Some("slack://second".into()),
- },
- ChatMessage {
- author: "Alice".into(),
- timestamp: t1,
- text: " first ".into(),
- source_ref: Some("slack://first".into()),
- },
- ],
- },
- )
- .expect("chat")
- .expect("chat output");
- assert!(chat.markdown.find("first").unwrap() < chat.markdown.find("second").unwrap());
- assert_eq!(chat.metadata.time_range, (t1, t2));
- assert_eq!(chat.metadata.source_ref.unwrap().value, "slack://first");
-
- let email = canonicalise_email(
- "gmail:thread",
- &["inbox".into()],
- EmailThread {
- provider: "gmail".into(),
- thread_subject: "Launch".into(),
- messages: vec![
- EmailMessage {
- from: "[email protected]".into(),
- to: vec!["[email protected]".into()],
- cc: vec!["[email protected]".into()],
- subject: "Launch".into(),
- sent_at: t2,
- body: "Reply body\n\nUnsubscribe https://example.com".into(),
- source_ref: Some("<[email protected]>".into()),
- list_unsubscribe: Some("<mailto:[email protected]>".into()),
- },
- EmailMessage {
- from: "[email protected]".into(),
- to: vec!["[email protected]".into()],
- cc: vec![],
- subject: "Re: Launch".into(),
- sent_at: t1,
- body: "Original body".into(),
- source_ref: Some(" ".into()),
- list_unsubscribe: None,
- },
- ],
- },
- )
- .expect("email")
- .expect("email output");
- assert!(
- email.markdown.find("Original body").unwrap() < email.markdown.find("Reply body").unwrap()
- );
- assert!(email.markdown.contains("Cc: [email protected]"));
- assert!(email
- .markdown
- .contains("List-Unsubscribe: <mailto:[email protected]>"));
- assert!(!email.markdown.contains("https://example.com"));
- assert!(email.metadata.source_ref.is_none());
-
- assert!(canonicalise_document(
- "doc-empty",
- "alice",
- &[],
- DocumentInput {
- provider: "notion".into(),
- title: " ".into(),
- body: " ".into(),
- modified_at: t1,
- source_ref: None,
- },
- None,
- )
- .expect("empty doc")
- .is_none());
-
- let doc_json = json!({
- "title": "Plan",
- "body": "Plan body",
- "modified_at": "1700000000000",
- "source_ref": "notion://page/1"
- });
- let doc_input: DocumentInput = serde_json::from_value(doc_json).expect("document input");
- assert_eq!(doc_input.provider, "unknown");
- let doc = canonicalise_document("doc-1", "alice", &["plans".into()], doc_input, None)
- .expect("document")
- .expect("document output");
- assert_eq!(doc.metadata.timestamp.timestamp_millis(), 1_700_000_000_000);
- assert_eq!(doc.metadata.source_ref.unwrap().value, "notion://page/1");
- assert_eq!(doc.markdown, "Plan body\n");
-}
-
-#[tokio::test]
-async fn memory_ingestion_state_and_request_models_report_edges() {
- let state = IngestionState::new();
- state.enqueue();
- state.enqueue();
- {
- let _guard = state.acquire().await;
- state.dequeue();
- state.mark_running("doc-1", "Coverage Doc", "coverage-ns");
- let running = state.snapshot();
- assert!(running.running);
- assert_eq!(running.queue_depth, 1);
- assert_eq!(running.current_title.as_deref(), Some("Coverage Doc"));
- }
- state.mark_completed("doc-1", false, 1_700_000_000_000);
- let completed = state.snapshot();
- assert!(!completed.running);
- assert_eq!(completed.last_document_id.as_deref(), Some("doc-1"));
- assert_eq!(completed.last_success, Some(false));
-
- let cfg = MemoryIngestionConfig {
- model_name: "local-model".into(),
- extraction_mode: ExtractionMode::Chunk,
- entity_threshold: 0.42,
- relation_threshold: 0.37,
- adjacency_threshold: 0.51,
- batch_size: 7,
- };
- let req = MemoryIngestionRequest {
- document: NamespaceDocumentInput {
- namespace: "coverage".into(),
- key: "doc-key".into(),
- title: "Coverage Doc".into(),
- content: "Alice collaborates with Bob on OpenHuman memory tests.".into(),
- source_type: "test".into(),
- priority: "medium".into(),
- tags: vec!["coverage".into()],
- metadata: json!({ "kind": "test" }),
- category: "core".into(),
- session_id: Some("session-1".into()),
- document_id: Some("doc-1".into()),
- taint: openhuman_core::openhuman::memory::MemoryTaint::Internal,
- },
- config: cfg.clone(),
- };
- assert_eq!(req.document.document_id.as_deref(), Some("doc-1"));
- assert_eq!(req.config.batch_size, 7);
- assert_eq!(req.config.extraction_mode, cfg.extraction_mode);
-}
-
-#[test]
-fn threads_turn_state_store_skips_corrupt_entries_and_marks_interrupted() {
- let tmp = TempDir::new().expect("tempdir");
- let store = TurnStateStore::new(tmp.path().to_path_buf());
- assert!(store.list().expect("initial list").is_empty());
- assert!(!store.delete("missing").expect("delete missing"));
- assert_eq!(store.clear_all().expect("clear missing"), 0);
-
- let mut first = TurnState::started("thread-a", "req-a", 4, "2026-05-29T12:00:00Z");
- first.lifecycle = TurnLifecycle::Streaming;
- first.iteration = 2;
- first.phase = Some(TurnPhase::ToolUse);
- first.active_tool = Some("memory.search".into());
- first.tool_timeline.push(ToolTimelineEntry {
- id: "tool-1".into(),
- name: "memory.search".into(),
- round: 1,
- status: ToolTimelineStatus::Running,
- failure: None,
- args_buffer: Some("{\"query\":\"coverage\"}".into()),
- display_name: Some("Search Memory".into()),
- detail: None,
- source_tool_name: Some("memory.search".into()),
- subagent: Some(SubagentActivity {
- task_id: "task-1".into(),
- agent_id: "researcher".into(),
- status: Some("running".into()),
- mode: Some("read".into()),
- dedicated_thread: Some(false),
- child_iteration: Some(1),
- child_max_iterations: Some(3),
- iterations: Some(1),
- elapsed_ms: Some(25),
- output_chars: Some(128),
- worker_thread_id: None,
- tool_calls: vec![SubagentToolCall {
- call_id: "call-1".into(),
- tool_name: "memory.search".into(),
- status: ToolTimelineStatus::Success,
- iteration: Some(1),
- elapsed_ms: Some(20),
- output_chars: Some(64),
- display_name: None,
- output: None,
- detail: None,
- args: None,
- failure: None,
- }],
- transcript: vec![],
- }),
- output: None,
- seq: None,
- });
- let second = TurnState::started("thread-b", "req-b", 2, "2026-05-29T12:01:00Z");
- store.put(&first).expect("put first");
- store.put(&second).expect("put second");
-
- let loaded = store
- .get("thread-a")
- .expect("get first")
- .expect("first exists");
- assert_eq!(loaded.active_tool.as_deref(), Some("memory.search"));
- assert_eq!(loaded.tool_timeline[0].status, ToolTimelineStatus::Running);
-
- let dir = tmp
- .path()
- .join("memory")
- .join("conversations")
- .join("turn_states");
- std::fs::write(dir.join("corrupt.json"), "{not-json").expect("write corrupt snapshot");
- let listed = store.list().expect("list skips corrupt");
- assert_eq!(listed.len(), 2);
-
- let interrupted = store
- .mark_all_interrupted("2026-05-29T12:02:00Z")
- .expect("mark interrupted");
- assert_eq!(interrupted, 2);
- let after = store.get("thread-a").expect("get after").expect("exists");
- assert_eq!(after.lifecycle, TurnLifecycle::Interrupted);
- assert!(after.active_tool.is_none());
- assert_eq!(after.updated_at, "2026-05-29T12:02:00Z");
- assert_eq!(
- store
- .mark_all_interrupted("2026-05-29T12:03:00Z")
- .expect("idempotent mark"),
- 0
- );
-
- assert!(store.delete("thread-b").expect("delete thread-b"));
- assert!(store
- .get("thread-b")
- .expect("missing after delete")
- .is_none());
- assert_eq!(store.clear_all().expect("clear all"), 2);
- assert!(store.list().expect("empty after clear").is_empty());
-}
diff --git a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
index 711813396a..aa725f596b 100644
--- a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs
@@ -18,9 +18,6 @@ fn ensure_memory_seams() {
.name("round23-memory-source-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- Arc::new(Config::default()),
- );
})
.expect("spawn round23 memory source seam installer")
.join()
diff --git a/tests/raw_coverage/memory_sync_providers_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_providers_raw_coverage_e2e.rs
index fd4c24da0f..4e8bd2ea96 100644
--- a/tests/raw_coverage/memory_sync_providers_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_sync_providers_raw_coverage_e2e.rs
@@ -84,9 +84,6 @@ fn ensure_memory_seams() {
.name("memory-sync-providers-raw-coverage-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- std::sync::Arc::new(Config::default()),
- );
})
.expect("spawn memory sync provider seam installer")
.join()
diff --git a/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs
index 840e98afd3..ff8451b90a 100644
--- a/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs
@@ -76,9 +76,6 @@ fn ensure_memory_seams() {
.name("memory-sync-round23-raw-coverage-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- std::sync::Arc::new(Config::default()),
- );
})
.expect("spawn round23 memory sync seam installer")
.join()
diff --git a/tests/raw_coverage/memory_sync_slack_bus_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_slack_bus_raw_coverage_e2e.rs
index dfee188fa3..bfdbcbc1d1 100644
--- a/tests/raw_coverage/memory_sync_slack_bus_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_sync_slack_bus_raw_coverage_e2e.rs
@@ -68,9 +68,6 @@ fn ensure_memory_seams(config: Arc<Config>) {
.name("memory-sync-slack-bus-raw-coverage-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(move || {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- Arc::clone(&config),
- );
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/raw_coverage/memory_sync_sources_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_sources_raw_coverage_e2e.rs
index de4f7f9957..1ee975c8b5 100644
--- a/tests/raw_coverage/memory_sync_sources_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/memory_sync_sources_raw_coverage_e2e.rs
@@ -66,9 +66,6 @@ fn ensure_memory_seams() {
.name("memory-sync-sources-raw-coverage-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- Arc::new(Config::default()),
- );
})
.expect("spawn memory sync source seam installer")
.join()
diff --git a/tests/raw_coverage/memory_sync_tree_round21_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_tree_round21_raw_coverage_e2e.rs
deleted file mode 100644
index fe59dd0f63..0000000000
--- a/tests/raw_coverage/memory_sync_tree_round21_raw_coverage_e2e.rs
+++ /dev/null
@@ -1,449 +0,0 @@
-//! Round 21 focused raw coverage for memory_sync + memory_tree gaps.
-//!
-//! Hermetic: temp workspaces, loopback Composio backend where still
-//! applicable, and no real network. Run with `--test-threads=1` because
-//! config/HOME/workspace env vars and the global memory client are
-//! process-global.
-//!
-//! # What changed here
-//!
-//! tinymemory v1.13.4 deleted the ENTIRE in-process Composio provider
-//! registry (`ComposioProvider` trait, `ProviderContext`, the concrete
-//! per-toolkit provider structs including `GmailProvider` and
-//! `LinearProvider`, `register_provider`/`init_default_providers`) — see
-//! `crate::openhuman::integrations::composio::providers`'s module docs for
-//! the full account. None of it has a replacement in this crate: it now
-//! lives in the separately-versioned `tinyconnectors` module, reachable only
-//! via a live loaded module over the bus (a real network download plus a
-//! `dlopen`), which this file's own "no real network" design rules out.
-//!
-//! `gmail_post_process_slims_wrapped_messages_and_honours_raw_flag` and the
-//! provider-internals half of
-//! `linear_provider_profile_tasks_sync_and_periodic_bookkeeping_use_loopback`
-//! (constructing a `GmailProvider`/`LinearProvider` directly and driving it
-//! against a loopback Composio execute API) tested exactly that deleted,
-//! relocated capability — Gmail's nested-payload post-processing, Linear's
-//! profile fetch, task normalization, and cursor-paginated sync. There is
-//! nothing left in this crate to assert that behaviour against; it is
-//! reported as a coverage gap rather than silently dropped. What replaces
-//! them below is the current, real, network-free entry point that stands in
-//! its place: `integrations::composio::ops::{composio_get_user_profile,
-//! composio_sync}`, which — with `modules.enabled = false` — refuse cleanly
-//! and deterministically instead of reaching a provider.
-//! `integrations::composio::periodic::record_sync_success` (moved from
-//! `memory::sync::composio::periodic`, which no longer exists) is still real
-//! and is still exercised directly.
-//!
-//! `slack_sync_status_rpc_reads_mock_connections_and_persisted_state` is
-//! rewritten rather than deleted, onto a genuinely different current
-//! behaviour: `providers::slack::rpc::sync_status_rpc`'s own doc comment
-//! (`src/openhuman/memory/sync/composio/providers/slack/rpc.rs`) explains
-//! that it is now a **deliberately degraded read** — the connector module
-//! keeps its cursor and daily-request budget internally and exposes neither
-//! outside of an actual `Sync` call, so every per-connection detail field
-//! (`per_channel_cursors`, `synced_ids_count`, `requests_used_today`,
-//! `daily_request_limit`) is hardcoded to its zero value rather than read
-//! back from anywhere. Persisting a `SyncState` before calling it (the old
-//! test's approach) no longer has any effect on the response, because
-//! nothing reads it — so this test now asserts the zero-value degraded shape
-//! and the log line that explains it, matching the RPC's own documented
-//! contract instead of a behaviour it no longer has.
-
-use std::collections::HashMap;
-use std::ffi::OsString;
-use std::path::Path;
-use std::sync::{Arc, Mutex, OnceLock};
-
-use axum::routing::get;
-use axum::{Json, Router};
-use chrono::{TimeZone, Utc};
-use serde_json::json;
-use tempfile::TempDir;
-
-use openhuman_core::openhuman::config::Config;
-use openhuman_core::openhuman::integrations::composio::ops::{
- composio_get_user_profile, composio_sync,
-};
-use openhuman_core::openhuman::integrations::composio::periodic::record_sync_success;
-use openhuman_core::openhuman::memory::sync::composio::providers::slack::rpc::{
- sync_status_rpc, SyncStatusRequest,
-};
-use openhuman_core::openhuman::security::credentials::{
- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
-};
-use tinycortex::memory::score::embed::{pack_embedding, EMBEDDING_DIM};
-use tinymemory_core::global as memory_global;
-use tinymemory_core::store::chunks::store::with_connection;
-use tinymemory_core::store::content::atomic::stage_summary;
-use tinymemory_core::store::content::{SummaryComposeInput, SummaryTreeKind};
-use tinymemory_core::store::trees::types::{SummaryNode, Tree, TreeKind};
-use tinymemory_core::tree::retrieval::source::query_source;
-// Engine-direct for the same reason as the other retrieval e2e suites (#5560).
-use tinymemory_core::tree::tree::store as tree_store;
-use tinymemory_core::tree::tree::TreeStatus;
-
-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
-static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
-
-fn ensure_memory_seams() {
- MEMORY_SEAMS_INIT.get_or_init(|| {
- std::thread::Builder::new()
- .name("memory-sync-tree-round21-raw-coverage-seams".to_string())
- .stack_size(8 * 1024 * 1024)
- .spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- Config::default(),
- ));
- })
- .expect("spawn round21 memory tree seam installer")
- .join()
- .expect("round21 memory tree seam installer panicked");
- });
-}
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- ENV_LOCK
- .get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|e| e.into_inner())
-}
-
-struct EnvGuard {
- key: &'static str,
- old: Option<OsString>,
-}
-
-impl EnvGuard {
- fn set_path(key: &'static str, value: impl AsRef<Path>) -> Self {
- let old = std::env::var_os(key);
- unsafe { std::env::set_var(key, value.as_ref()) };
- Self { key, old }
- }
-
- fn unset(key: &'static str) -> Self {
- let old = std::env::var_os(key);
- unsafe { std::env::remove_var(key) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvGuard {
- fn drop(&mut self) {
- unsafe {
- match &self.old {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
-
-fn config_in(tmp: &TempDir) -> Config {
- ensure_memory_seams();
- let mut config = Config {
- config_path: tmp.path().join("config.toml"),
- workspace_dir: tmp.path().join("workspace"),
- action_dir: tmp.path().join("workspace"),
- ..Config::default()
- };
- config.secrets.encrypt = false;
- config.memory_tree.embedding_endpoint = None;
- config.memory_tree.embedding_model = None;
- config.memory_tree.embedding_strict = false;
- config
-}
-
-async fn persist_config(config: &Config) {
- std::fs::create_dir_all(&config.workspace_dir).expect("workspace dir");
- config.save().await.expect("save config");
-}
-
-fn store_session(config: &Config) {
- AuthService::from_config(config)
- .store_provider_token(
- APP_SESSION_PROVIDER,
- DEFAULT_AUTH_PROFILE_NAME,
- "round21-session-token",
- HashMap::new(),
- true,
- )
- .expect("store app session token");
-}
-
-async fn loopback_router(router: Router) -> (String, tokio::task::JoinHandle<()>) {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
- .await
- .expect("bind loopback");
- let addr = listener.local_addr().expect("loopback addr");
- let handle = tokio::spawn(async move {
- axum::serve(listener, router).await.expect("serve loopback");
- });
- (format!("http://{addr}"), handle)
-}
-
-/// What `gmail_post_process_slims_wrapped_messages_and_honours_raw_flag` and
-/// the profile/tasks half of
-/// `linear_provider_profile_tasks_sync_and_periodic_bookkeeping_use_loopback`
-/// used to cover — see the module doc comment for why that coverage cannot
-/// be expressed here any more. `composio_get_user_profile` is the real,
-/// current entry point standing in its place for "fetch a provider's
-/// profile", and it refuses cleanly and deterministically — no network, no
-/// provider — when no connectors module is loaded.
-#[tokio::test]
-async fn composio_get_user_profile_refuses_cleanly_for_gmail_and_linear_without_a_loaded_module() {
- let _guard = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvGuard::set_path("OPENHUMAN_WORKSPACE", tmp.path());
- let _home = EnvGuard::set_path("HOME", tmp.path());
- let _backend = EnvGuard::unset("BACKEND_URL");
-
- let mut config = config_in(&tmp);
- config.modules.enabled = false;
- persist_config(&config).await;
- store_session(&config);
-
- for connection_id in ["conn-gmail-round21", "conn-linear-round21"] {
- let error = composio_get_user_profile(&config, connection_id)
- .await
- .expect_err("profile fetch must refuse without a loaded connectors module");
- assert!(
- error.contains("modules are disabled in configuration"),
- "unexpected error for {connection_id}: {error}"
- );
- }
-
- // `composio_sync` — the entry point standing in for the deleted
- // `LinearProvider::sync` / periodic bookkeeping loop — refuses the same
- // way: the toolkit resolution it needs is itself module-mediated.
- let sync_error = composio_sync(&config, "conn-linear-round21", Some("manual".to_string()))
- .await
- .expect_err("sync must refuse without a loaded connectors module");
- assert!(
- sync_error.contains("modules are disabled in configuration"),
- "unexpected sync error: {sync_error}"
- );
-
- // `record_sync_success` (moved from the deleted `memory::sync::composio::
- // periodic` to `integrations::composio::periodic`) is untouched by the
- // deletion — it is a pure process-local bookkeeping call the periodic
- // scheduler uses to avoid immediately re-firing a sync it just ran. It
- // exposes no public reader, so this — like the original test — only
- // proves it is callable and does not panic.
- record_sync_success("linear", "conn-linear-round21");
- record_sync_success("linear", "conn-linear-round21");
-}
-
-#[tokio::test]
-async fn slack_sync_status_rpc_reports_the_degraded_zero_value_shape() {
- let _guard = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvGuard::set_path("OPENHUMAN_WORKSPACE", tmp.path());
- let _home = EnvGuard::set_path("HOME", tmp.path());
- let _backend = EnvGuard::unset("BACKEND_URL");
- let mut config = config_in(&tmp);
- let router = Router::new().route(
- "/agent-integrations/composio/connections",
- get(|| async {
- Json(json!({
- "success": true,
- "data": {
- "connections": [
- { "id": "conn-slack-round21", "toolkit": "slack", "status": "ACTIVE" },
- { "id": "conn-slack-pending", "toolkit": "slack", "status": "PENDING" },
- { "id": "conn-gmail-round21", "toolkit": "gmail", "status": "ACTIVE" }
- ]
- }
- }))
- }),
- );
- let (base, server) = loopback_router(router).await;
- config.api_url = Some(base);
- persist_config(&config).await;
- store_session(&config);
- memory_global::init(config.workspace_dir.clone()).expect("memory global");
-
- // `list_slack_connections` (what `sync_status_rpc` calls first) still
- // goes through the old backend HTTP client factory, untouched by the
- // tinyconnectors migration — so the loopback connections router above
- // still drives it. What changed is everything after: there is no more
- // per-connection detail to read back (see module doc comment), so this
- // no longer seeds a `SyncState` before calling the RPC — nothing would
- // read it.
- let outcome = sync_status_rpc(&config, SyncStatusRequest::default())
- .await
- .expect("status rpc");
- assert_eq!(
- outcome.value.connections.len(),
- 1,
- "only the active slack connection qualifies"
- );
- let row = &outcome.value.connections[0];
- assert_eq!(row.connection_id, "conn-slack-round21");
- assert_eq!(row.per_channel_cursors, "{}");
- assert_eq!(row.synced_ids_count, 0);
- assert_eq!(row.requests_used_today, 0);
- assert_eq!(row.daily_request_limit, 0);
- assert!(
- outcome
- .logs
- .iter()
- .any(|line| line.contains("connections=1") && line.contains("no longer available")),
- "status log should explain the degraded read: {:?}",
- outcome.logs
- );
-
- server.abort();
-}
-
-#[tokio::test]
-async fn memory_tree_source_query_filters_reranks_and_hydrates_manual_summaries() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
- std::fs::create_dir_all(config.memory_tree_content_root()).expect("content root");
- seed_source_summary(
- &config,
- "slack:#round21",
- "summary-round21-chat",
- "Full chat summary body from disk.",
- 1_780_313_600_000,
- Some(one_hot(0)),
- );
- seed_source_summary(
- &config,
- "summary-round21-email",
- "Full email summary body from disk.",
- 1_780_227_200_000,
- None,
- );
-
- let all = query_source(&config, None, None, None, None, 0)
- .await
- .expect("all source query");
- assert_eq!(all.total, 2);
- assert_eq!(all.hits.len(), 2);
-
- let chat = query_source(
- &config,
- None,
- Some(tinymemory_core::store::chunks::types::SourceKind::Chat),
- None,
- Some("semantic query keeps embedded rows first"),
- 10,
- )
- .await
- .expect("chat query");
- assert_eq!(chat.hits.len(), 1);
- assert_eq!(chat.hits[0].tree_scope, "slack:#round21");
- assert_eq!(chat.hits[0].content, "Full chat summary body from disk.");
-
- let missing = query_source(&config, Some("slack:#missing"), None, None, None, 10)
- .await
- .expect("missing source");
- assert!(missing.hits.is_empty());
-}
-
-fn one_hot(index: usize) -> Vec<f32> {
- let mut values = vec![0.0; EMBEDDING_DIM];
- values[index] = 1.0;
- values
-}
-
-fn seed_source_summary(
- config: &Config,
- scope: &str,
- summary_id: &str,
- body: &str,
- timestamp_ms: i64,
- embedding: Option<Vec<f32>>,
-) {
- let ts = Utc.timestamp_millis_opt(timestamp_ms).unwrap();
- let tree = Tree {
- id: format!("tree:{summary_id}"),
- kind: TreeKind::Source,
- scope: scope.to_string(),
- ask: None,
- root_id: Some(summary_id.to_string()),
- max_level: 1,
- status: TreeStatus::Active,
- created_at: ts,
- last_sealed_at: Some(ts),
- };
- tree_store::insert_tree(config, &tree).expect("insert source tree");
-
- let node = SummaryNode {
- id: summary_id.to_string(),
- tree_id: tree.id.clone(),
- tree_kind: TreeKind::Source,
- level: 1,
- parent_id: None,
- child_ids: vec!["leaf-a".to_string(), "leaf-b".to_string()],
- content: "preview only".to_string(),
- token_count: 64,
- entities: vec!["round21".to_string()],
- topics: vec!["coverage".to_string()],
- time_range_start: ts,
- time_range_end: ts,
- score: 0.75,
- sealed_at: ts,
- deleted: false,
- embedding: embedding.clone(),
- doc_id: None,
- version_ms: None,
- };
- let staged = stage_summary(
- &config.memory_tree_content_root(),
- &SummaryComposeInput {
- summary_id: &node.id,
- tree_kind: SummaryTreeKind::Source,
- tree_id: &node.tree_id,
- tree_scope: &tree.scope,
- level: node.level,
- child_ids: &node.child_ids,
- child_basenames: None,
- child_count: node.child_ids.len(),
- time_range_start: node.time_range_start,
- time_range_end: node.time_range_end,
- sealed_at: node.sealed_at,
- body,
- },
- scope,
- )
- .expect("stage summary body");
- let embedding_blob = embedding.as_ref().map(|values| pack_embedding(values));
-
- with_connection(config, |conn| {
- conn.execute(
- "INSERT INTO mem_tree_summaries (
- id, tree_id, tree_kind, level, parent_id,
- child_ids_json, content, token_count,
- entities_json, topics_json,
- time_range_start_ms, time_range_end_ms,
- score, sealed_at_ms, deleted, embedding,
- content_path, content_sha256
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)",
- rusqlite::params![
- node.id,
- node.tree_id,
- node.tree_kind.as_str(),
- node.level,
- node.parent_id,
- serde_json::to_string(&node.child_ids).unwrap(),
- node.content,
- node.token_count,
- serde_json::to_string(&node.entities).unwrap(),
- serde_json::to_string(&node.topics).unwrap(),
- node.time_range_start.timestamp_millis(),
- node.time_range_end.timestamp_millis(),
- node.score,
- node.sealed_at.timestamp_millis(),
- node.deleted as i64,
- embedding_blob,
- staged.content_path,
- staged.content_sha256,
- ],
- )?;
- Ok(())
- })
- .expect("insert summary row");
-}
diff --git a/tests/raw_coverage/memory_threads_raw_coverage_e2e.rs b/tests/raw_coverage/memory_threads_raw_coverage_e2e.rs
deleted file mode 100644
index 854404c650..0000000000
--- a/tests/raw_coverage/memory_threads_raw_coverage_e2e.rs
+++ /dev/null
@@ -1,4833 +0,0 @@
-//! Raw-line oriented E2E coverage for memory, memory_tree, memory_sync,
-//! memory_sources, and threads.
-//!
-//! The tests call public Rust APIs and localhost-only readers so they stay
-//! hermetic while still exercising production code paths that are awkward to
-//! reach through full JSON-RPC flows.
-
-use axum::http::{HeaderMap, StatusCode};
-use axum::response::{Html, IntoResponse, Response};
-use axum::routing::get;
-use axum::Router;
-use chrono::{TimeZone, Utc};
-use serde_json::json;
-use serde_json::{Map, Value};
-use std::ffi::OsString;
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex, OnceLock};
-use tempfile::TempDir;
-
-use openhuman_core::openhuman::agent::progress::AgentProgress;
-use openhuman_core::openhuman::agent::task_board::{TaskBoard, TaskBoardCard, TaskCardStatus};
-use openhuman_core::openhuman::config::Config;
-use openhuman_core::openhuman::inference::embeddings::NoopEmbedding;
-use openhuman_core::openhuman::memory::api::tool_memory::{
- ToolMemoryPriority as ApiToolMemoryPriority, ToolMemoryRule as ApiToolMemoryRule,
- ToolMemorySource as ApiToolMemorySource,
-};
-use openhuman_core::openhuman::memory::query::{
- MemoryQueryTool, MemoryTreeDrillDownTool, MemoryTreeFetchLeavesTool,
- MemoryTreeIngestDocumentTool, MemoryTreeQuerySourceTool, MemoryTreeSearchEntitiesTool,
-};
-use openhuman_core::openhuman::memory::sources::readers::reader_for;
-use openhuman_core::openhuman::memory::sources::registry;
-use openhuman_core::openhuman::memory::sources::rpc as memory_sources_rpc;
-// The engine's per-source SQL read, which is what this suite seeds a store for.
-// `memory::sources::status` is host-side now and asks the bound driver, which an
-// integration test has no module to load (#5560).
-use tinymemory_core::sources::status::{source_status, FreshnessLabel};
-// The engine's own source pipeline. `memory::sources::sync` is host-side now and
-// carries only `derive_scopes`; `sync_source` stayed upstream because nothing in
-// `src/` calls it any more (#5560).
-use tinymemory_core::sources::sync::sync_source;
-use openhuman_core::openhuman::memory::sources::types::{
- ContentType, MemorySourceEntry, SourceContent, SourceItem, SourceKind,
-};
-use openhuman_core::openhuman::memory::sources::{
- all_memory_sources_controller_schemas, all_memory_sources_registered_controllers,
-};
-use openhuman_core::openhuman::memory::sync::composio;
-use tinymemory_core::queue::types::ReembedBackfillPayload;
-use tinymemory_core::queue::{
- self as memory_queue, AppendBufferPayload, AppendTarget, ExtractChunkPayload,
- FlushStalePayload, JobKind, JobStatus, NewJob, NodeRef, SealPayload, DEFAULT_LOCK_DURATION_MS,
-};
-use tinymemory_core::store::chunks::store::{upsert_chunks, with_connection};
-use tinymemory_core::store::chunks::types::{
- approx_token_count, chunk_id, Chunk, DataSource, Metadata, SourceKind as ChunkSourceKind,
- SourceRef,
-};
-use tinymemory_core::store::trees::types::{
- SummaryNode, Tree, TreeKind, TreeStatus as StoredTreeStatus,
-};
-use tinymemory_core::store::{MemoryClient, NamespaceDocumentInput, UnifiedMemory};
-// `memory::sync::composio::providers::slack::schemas` is this host's own real,
-// current RPC schema module (`openhuman.slack_memory_sync_trigger` /
-// `_status`) — unrelated to the deleted per-action `post_process` (see below).
-use openhuman_core::openhuman::memory::sync::composio::providers::slack::schemas as slack_memory_schemas;
-// Everything below moved off `memory::sync::composio::providers::*` onto
-// `integrations::composio::providers`/`integrations::composio::identity_store`/
-// `integrations::composio::profile_md` (host code) or `tinymemory_api::composio`
-// (contract-crate vocabulary) — see `crate::openhuman::integrations::composio::providers`'s
-// module docs for the full account of what replaced each deleted piece.
-use openhuman_core::openhuman::integrations::composio::identity_store::{
- delete_connected_identity_facets, load_connected_identities,
-};
-use openhuman_core::openhuman::integrations::composio::ops::{
- composio_get_user_profile, composio_sync,
-};
-use openhuman_core::openhuman::integrations::composio::profile_md::{
- block_end, block_start, merge_provider_into_profile_md, remove_provider_from_profile_md,
- replace_managed_block,
-};
-use openhuman_core::openhuman::integrations::composio::providers::{
- agent_ready_toolkits, catalog_for_toolkit, classify_unknown, curated_scope_for, find_curated,
- is_action_visible_with_pref, toolkit_from_slug, toolkit_has_scope, CuratedTool, NormalizedTask,
- ProviderUserProfile, SyncOutcome as ComposioSyncOutcome, SyncReason, TaskFetchFilter,
- ToolScope, UserScopePref,
-};
-use tinymemory_api::composio::{
- canonicalize, extract_item_id, render_connected_identities_section, ConnectedIdentity,
- DailyBudget, IdentityKind, SyncState, DEFAULT_DAILY_REQUEST_LIMIT,
-};
-// The deleted engine's per-toolkit `is_self_identity(prefix, kind, value)` has
-// no replacement anywhere (confirmed by exhaustive grep of vendor/tinymemory) —
-// only the cross-toolkit matcher survived, because the memory tree's entity
-// indexer was never scoped to one toolkit to begin with. Note this is a
-// DIFFERENT (structurally identical) `IdentityKind` than
-// `tinymemory_api::composio::IdentityKind` above.
-use openhuman_core::openhuman::memory::sync::sync_status::{
- rpc as memory_sync_status_rpc, schemas as memory_sync_status_schemas,
-};
-use openhuman_core::openhuman::memory::tool_memory::prompt::{
- render_tool_memory_rules, ToolMemoryRulesSection, TOOL_MEMORY_HEADING,
-};
-use openhuman_core::openhuman::memory::tool_memory::{
- tool_memory_namespace, tool_memory_store, ToolMemoryPriority, ToolMemoryRule, ToolMemorySource,
- TOOL_MEMORY_PROMPT_CAP,
-};
-use openhuman_core::openhuman::memory::tools::tool_memory::{
- MemoryToolsListTool, MemoryToolsPutTool,
-};
-use openhuman_core::openhuman::memory::tools::{
- MemoryForgetTool, MemoryRecallTool, MemoryStoreTool,
-};
-use tinymemory_core::tree::score::embed;
-use tinymemory_core::tree::score::embed::Embedder;
-use tinymemory_core::tree::score::extract::{
- CompositeExtractor, EntityExtractor, EntityKind, ExtractedEntities, ExtractedEntity,
- ExtractedTopic,
-};
-use tinymemory_core::tree::score::resolver::CanonicalEntity;
-use tinymemory_core::tree::score::signals::{
- combine, combine_cheap_only, compute as compute_score_signals, entity_density_score,
- interaction, metadata_weight, source_weight, token_count, unique_words, ScoreSignals,
- SignalWeights,
-};
-use tinymemory_core::tree::score::store as score_store;
-use tinymemory_core::tree::score::{resolver, ScoringConfig};
-use tinymemory_core::tree::summarise::{
- fallback_summary, SummaryContext, SummaryInput,
-};
-use tinymemory_core::tree::tree::bucket_seal::LeafRef;
-use tinymemory_core::tree::tree_runtime::store as tree_runtime_store;
-use openhuman_core::openhuman::memory::tree::tree_runtime::{
- all_tree_summarizer_controller_schemas, all_tree_summarizer_registered_controllers,
- derive_node_ids, derive_parent_id, estimate_tokens, level_from_node_id, node_id_to_path,
- NodeLevel, TreeNode,
-};
-use tinymemory_core::store::identity::is_self_identity_any_toolkit;
-// `retrieval` is the engine module, not the host wrapper: the host stopped
-// re-exporting it in #5560. The `tree::score` / `tree::summarise` /
-// `tree::tree` imports above went engine-direct the same way once their host
-// re-export shims stopped serving production (#5560).
-use openhuman_core::openhuman::memory::{
- all_memory_controller_schemas, all_memory_registered_controllers,
- preferences::{
- load_general_preferences, recall_related_preferences, recall_situational_preferences,
- USER_PREF_GENERAL_NAMESPACE, USER_PREF_SITUATIONAL_NAMESPACE,
- },
- read_rpc as memory_read_rpc,
-};
-// The engine's own ingest request/config — what `UnifiedMemory::
-// ingest_document` and `extract_graph` take. `memory::MemoryIngestion*` are
-// the host's WIRE shapes now (`rpc_models`), distinct types (#5560).
-use tinycortex::memory::ingest::{MemoryIngestionConfig, MemoryIngestionRequest};
-use tinymemory_core::tree::retrieval;
-use tinymemory_core::tree_policy::TreePolicy;
-use tinymemory_core::tree_source;
-// `remember`, `rpc_models`, `traits` and `util` moved into the extracted engine
-// crate with the rest of the memory implementation; the host re-exports some of
-// their contents flat but not the modules themselves.
-// The guard exposes `store` through the contract's mandatory core trait, and
-// stamps provenance from an explicit taint argument.
-use openhuman_core::openhuman::memory::api::provider::MemoryCore;
-use openhuman_core::openhuman::memory::api::types::MemoryTaint;
-// These request/record types are consumed directly by `openhuman_core::openhuman::memory::ops`
-// and `openhuman::threads::ops` handlers below, which take the host's own `rpc_models` types,
-// not the engine crate's same-named ones — so they must come from the host, not `tinymemory_core`.
-use openhuman_core::openhuman::memory::rpc_models::{
- AppendConversationMessageRequest, ConversationMessageRecord, ConversationMessagesRequest,
- CreateConversationThreadRequest, DeleteConversationThreadRequest, DeleteDocumentRequest,
- EmptyRequest, GenerateConversationThreadTitleRequest, ListDocumentsRequest,
- ListMemoryFilesRequest, MemoryInitRequest, ReadMemoryFileRequest,
- UpdateConversationMessageRequest, UpdateConversationThreadLabelsRequest,
- UpdateConversationThreadTitleRequest, UpsertConversationThreadRequest, WriteMemoryFileRequest,
-};
-use openhuman_core::openhuman::security::{AutonomyLevel, SecurityPolicy};
-use openhuman_core::openhuman::threads::ops as thread_ops;
-use openhuman_core::openhuman::threads::title::{
- build_title_prompt, collapse_whitespace, is_auto_generated_thread_title,
- sanitize_generated_title, title_from_user_message, title_log_fingerprint,
-};
-use openhuman_core::openhuman::threads::turn_state::{
- self, ClearTurnStateRequest, GetTurnStateRequest, GetTurnStateResponse, ListTurnStatesResponse,
- SubagentActivity, SubagentToolCall, ToolTimelineEntry, ToolTimelineStatus, TurnLifecycle,
- TurnPhase, TurnState, TurnStateMirror, TurnStateStore,
-};
-use openhuman_core::openhuman::threads::ThreadsError;
-use openhuman_core::openhuman::threads::{
- all_threads_controller_schemas, all_threads_registered_controllers,
-};
-use openhuman_core::openhuman::tools::traits::{PermissionLevel, Tool, ToolCategory};
-use tinycortex::memory::ingest::canonicalize::chat::{
- canonicalise as canonicalise_chat, ChatBatch, ChatMessage,
-};
-use tinycortex::memory::ingest::canonicalize::document::{
- canonicalise as canonicalise_document, DocumentInput,
-};
-use tinycortex::memory::ingest::canonicalize::email::{
- canonicalise as canonicalise_email, EmailMessage, EmailThread,
-};
-use tinycortex::memory::ingest::canonicalize::email_clean;
-use tinycortex::memory::sync::{SyncOutcome as PipelineSyncOutcome, SyncPipelineKind};
-use tinymemory_core::{
- remember::RememberSourceKind,
- rpc_models::{
- ApiEnvelope, ApiError, ApiMeta, PaginationMeta, QueryNamespaceRequest,
- RecallContextRequest, RecallMemoriesRequest,
- },
- traits::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts},
- util::redact::{redact, redact_endpoint},
-};
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<OsString>,
-}
-
-impl EnvVarGuard {
- fn set_to_path(key: &'static str, value: &Path) -> Self {
- let old = std::env::var_os(key);
- unsafe {
- std::env::set_var(key, value.as_os_str());
- }
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- unsafe {
- match &self.old {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
-
-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
-fn ensure_memory_seams() {
- std::thread::Builder::new()
- .name("raw-coverage-memory-seams".to_string())
- .stack_size(8 * 1024 * 1024)
- .spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- Config::default(),
- ));
- })
- .expect("spawn raw coverage memory seam installer")
- .join()
- .expect("raw coverage memory seam installer panicked");
-}
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- ENV_LOCK
- .get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-fn config_in(tmp: &TempDir) -> Config {
- ensure_memory_seams();
- let mut config = Config::default();
- config.workspace_dir = tmp.path().to_path_buf();
- config
-}
-
-/// The one memory workspace every driver-routed case in this module shares.
-///
-/// The module host captures a workspace **once per process**: the boot policy
-/// is first-call-wins and the loaded artifact takes its `workspace_dir` at load,
-/// while each case here used to get its own `TempDir`. Whichever case published
-/// first bound the module to a directory that was deleted when that case
-/// returned, and every later read through the driver answered from the dead
-/// store: 0 rows where the case had just seeded 1. Production never has that
-/// mismatch, because boot publishes the runtime config and module and handlers
-/// name one object. This reproduces that arrangement the way
-/// `tests/json_rpc_e2e.rs` does: one leaked directory, the policy published from
-/// it exactly once, and every driver-routed case pointing its config (and
-/// `OPENHUMAN_WORKSPACE`) here. Cases keep their own `TempDir` for the files they
-/// write; only the memory workspace is shared. The path ends in `workspace` so
-/// `resolve_config_dir_for_workspace` treats it as the workspace itself rather
-/// than appending another segment, and the env var and the config agree exactly.
-fn module_workspace() -> &'static Path {
- static WORKSPACE: OnceLock<PathBuf> = OnceLock::new();
- WORKSPACE.get_or_init(|| {
- let dir = TempDir::new().expect("module workspace tempdir");
- let path = dir.path().join("workspace");
- std::fs::create_dir_all(&path).expect("create module workspace");
- // Leaked on purpose: the module keeps this path for the process lifetime.
- std::mem::forget(dir);
- ensure_memory_seams();
- #[cfg(feature = "modules")]
- openhuman_core::openhuman::modules::memory::set_modules_policy(Arc::new(shared_config_at(
- &path,
- )));
- path
- })
-}
-
-/// A config whose memory workspace **and** source registry are the shared ones.
-///
-/// `config_path` matters as much as `workspace_dir`: the module reads its
-/// source registry from the file the host names there, and `Config::default()`
-/// names the developer's real `~/.openhuman/config.toml`. Pointing it beside
-/// the shared workspace is also where `Config::load_or_init` resolves it from
-/// `OPENHUMAN_WORKSPACE`, so env-driven cases and config-driven cases write and
-/// read one registry. Embeddings are off so no case asks the host to embed.
-fn shared_config_at(workspace: &Path) -> Config {
- let mut config = Config::default();
- config.workspace_dir = workspace.to_path_buf();
- config.config_path = workspace
- .parent()
- .expect("shared workspace has a parent")
- .join("config.toml");
- config.embeddings_provider = Some("none".into());
- config
-}
-
-/// Point `config` at the shared module workspace and registry.
-fn use_module_workspace(config: &mut Config) {
- let shared = shared_config_at(module_workspace());
- config.workspace_dir = shared.workspace_dir;
- config.config_path = shared.config_path;
- config.embeddings_provider = shared.embeddings_provider;
-}
-
-/// Empty the shared chunk store so a case that counts rows sees only its own.
-///
-/// Rows, not the file: the module holds its connection open, so replacing the
-/// file would leave it reading the old inode. Tables a fresh store lacks are
-/// skipped rather than failed.
-fn wipe_shared_store(config: &Config) {
- with_connection(config, |conn| {
- for table in [
- "mem_tree_chunk_embeddings",
- "mem_tree_chunk_reembed_skipped",
- "mem_tree_entity_edges",
- "mem_tree_entity_hotness",
- "mem_tree_entity_index",
- "mem_tree_score",
- "mem_tree_ingested_sources",
- "mem_tree_summary_embeddings",
- "mem_tree_summaries",
- "mem_tree_chunks",
- ] {
- if let Err(error) = conn.execute(&format!("DELETE FROM {table}"), []) {
- let text = error.to_string();
- assert!(text.contains("no such table"), "wipe {table}: {text}");
- }
- }
- Ok(())
- })
- .expect("wipe shared store");
-}
-
-fn source(kind: SourceKind, id: &str) -> MemorySourceEntry {
- MemorySourceEntry {
- id: id.to_string(),
- kind,
- label: format!("{id} label"),
- enabled: true,
- toolkit: None,
- connection_id: None,
- path: None,
- glob: None,
- url: None,
- branch: None,
- paths: Vec::new(),
- query: None,
- since_days: None,
- max_items: None,
- max_commits: None,
- max_issues: None,
- max_prs: None,
- selector: None,
- max_tokens_per_sync: None,
- max_cost_per_sync_usd: None,
- sync_depth_days: None,
- }
-}
-
-fn chunk(source_id: &str, seq: u32, timestamp_ms: i64) -> Chunk {
- let content = format!("chunk {source_id} {seq}");
- let ts = Utc.timestamp_millis_opt(timestamp_ms).unwrap();
- Chunk {
- id: chunk_id(ChunkSourceKind::Document, source_id, seq, &content),
- content,
- metadata: Metadata::point_in_time(ChunkSourceKind::Document, source_id, "owner", ts),
- token_count: approx_token_count(source_id),
- seq_in_source: seq,
- created_at: ts,
- partial_message: false,
- }
-}
-
-fn tree_node(namespace: &str, node_id: &str, summary: &str) -> TreeNode {
- let created_at = Utc.with_ymd_and_hms(2026, 5, 29, 12, 0, 0).unwrap();
- TreeNode {
- node_id: node_id.to_string(),
- namespace: namespace.to_string(),
- level: level_from_node_id(node_id),
- parent_id: derive_parent_id(node_id),
- summary: summary.to_string(),
- token_count: estimate_tokens(summary),
- child_count: 0,
- created_at,
- updated_at: created_at,
- metadata: Some(json!({ "kind": "coverage", "node": node_id }).to_string()),
- }
-}
-
-async fn serve_routes(router: Router) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
- .await
- .expect("bind test server");
- let addr = listener.local_addr().expect("local addr");
- tokio::spawn(async move {
- let _ = axum::serve(listener, router).await;
- });
- format!("http://{addr}")
-}
-
-async fn html_page() -> Html<&'static str> {
- Html(
- "<html><head><title>Raw Page</title></head><body><main><h1>Hello</h1><p>Selected body</p></main><aside>Skip me</aside></body></html>",
- )
-}
-
-async fn large_header() -> Response {
- vec![b'x'; 10 * 1024 * 1024 + 1].into_response()
-}
-
-async fn rss_feed(headers: HeaderMap) -> Response {
- let mode = headers
- .get("x-feed-mode")
- .and_then(|value| value.to_str().ok())
- .unwrap_or("rss");
- if mode == "atom" {
- return Html(
- r#"<feed><entry><id>atom-1</id><title>Atom One</title><content>Atom body</content><link href="https://example.test/atom-1"/><updated>2026-05-29T12:00:00Z</updated></entry></feed>"#,
- )
- .into_response();
- }
- Html(
- r#"<rss><channel><item><guid>rss-1</guid><title>RSS One</title><link>https://example.test/rss-1</link><description><![CDATA[<p>RSS body</p>]]></description><pubDate>Fri, 29 May 2026 12:00:00 +0000</pubDate></item><item><guid>rss-2</guid><title>RSS Two</title><description>Second</description></item></channel></rss>"#,
- )
- .into_response()
-}
-
-#[tokio::test]
-async fn canonicalizers_clean_sort_and_preserve_metadata() {
- let doc_json = json!({
- "title": "Doc",
- "body": " Document body ",
- "modified_at": "2026-05-29T12:00:00Z",
- "source_ref": " file://doc "
- });
- let doc: DocumentInput = serde_json::from_value(doc_json).expect("document input");
- let doc_out = canonicalise_document("doc:1", "alice", &["plans".into()], doc, None)
- .expect("document canonicalise")
- .expect("document output");
- assert_eq!(doc_out.markdown, "Document body\n");
- assert_eq!(doc_out.metadata.source_id, "doc:1");
- assert_eq!(doc_out.metadata.source_ref.unwrap().value, "file://doc");
-
- let empty_doc = DocumentInput {
- provider: "drive".into(),
- title: " ".into(),
- body: "\n ".into(),
- modified_at: Utc.timestamp_millis_opt(1_700_000_000_000).unwrap(),
- source_ref: Some(" ".into()),
- };
- assert!(
- canonicalise_document("doc:empty", "alice", &[], empty_doc, None)
- .unwrap()
- .is_none()
- );
-
- let older = Utc.timestamp_millis_opt(1_700_000_000_000).unwrap();
- let newer = Utc.timestamp_millis_opt(1_700_000_060_000).unwrap();
- let email_out = canonicalise_email(
- "gmail:thread-1",
- &["inbox".into()],
- EmailThread {
- provider: "gmail".into(),
- thread_subject: "Launch".into(),
- messages: vec![
- EmailMessage {
- from: "Bob <[email protected]>".into(),
- to: vec!["[email protected]".into()],
- cc: vec!["[email protected]".into()],
- subject: "Re: Launch".into(),
- sent_at: newer,
- body: "Reply\n\nUnsubscribe here".into(),
- source_ref: Some("<[email protected]>".into()),
- list_unsubscribe: Some("<mailto:[email protected]>".into()),
- },
- EmailMessage {
- from: "[email protected]".into(),
- to: vec!["[email protected]".into()],
- cc: Vec::new(),
- subject: "Launch".into(),
- sent_at: older,
- body: "First\n\n> quoted one\n> quoted two\n> quoted three".into(),
- source_ref: Some("<[email protected]>".into()),
- list_unsubscribe: None,
- },
- ],
- },
- )
- .expect("email canonicalise")
- .expect("email output");
- assert!(email_out.markdown.find("Subject: Launch") < email_out.markdown.find("Re: Launch"));
- assert!(email_out.markdown.contains("List-Unsubscribe:"));
- assert!(!email_out.markdown.contains("quoted three"));
- assert_eq!(email_out.metadata.time_range, (older, newer));
- assert_eq!(
- email_out.metadata.source_ref.as_ref().unwrap().value,
- );
-
- let chat_out = canonicalise_chat(
- "slack:#eng",
- "alice",
- &["eng".into()],
- ChatBatch {
- platform: "slack".into(),
- channel_label: "#eng".into(),
- messages: vec![
- ChatMessage {
- author: "Bob".into(),
- timestamp: newer,
- text: " second ".into(),
- source_ref: Some("slack://2".into()),
- },
- ChatMessage {
- author: "Alice".into(),
- timestamp: older,
- text: "first".into(),
- source_ref: Some("slack://1".into()),
- },
- ],
- },
- )
- .expect("chat canonicalise")
- .expect("chat output");
- assert!(chat_out.markdown.find("Alice") < chat_out.markdown.find("Bob"));
- assert_eq!(chat_out.metadata.source_ref.unwrap().value, "slack://1");
-
- assert_eq!(
- email_clean::drop_footer_noise("Real\n\nView in browser\nFooter"),
- "Real"
- );
- assert_eq!(
- email_clean::parse_message_date(&json!({ "date": "2026-05-29" }))
- .unwrap()
- .date_naive()
- .to_string(),
- "2026-05-29"
- );
- assert_eq!(
- email_clean::extract_email("Name <[email protected]>").as_deref(),
- );
- assert_eq!(email_clean::md_escape("a*b_c|d"), "a\\*b\\_c\\|d");
-}
-
-#[tokio::test]
-async fn memory_ingestion_pipeline_extracts_graph_preferences_and_recall_hits() {
- let tmp = TempDir::new().expect("tempdir");
- let memory = UnifiedMemory::new(tmp.path(), Arc::new(NoopEmbedding), None).expect("memory");
- let content = r#"
-From: Alice Morgan <[email protected]>
-To: Bob Stone <[email protected]>, Cara Park <[email protected]>
-Cc: OpenHuman Core <[email protected]>
-Subject: OpenHuman coverage memory plan
-Date: 2026-05-29
-
-# Project Alpha
-Project name: OpenHuman
-Subproject: memory-coverage
-Owner: Alice Morgan
-Name: Thread raw coverage
-Due date: 2026-06-01
-Target milestone: 2026-06-15
-Preferred embedding model for local experiments: text-embedding-3-small
-Preferred extraction mode to try first: sentence
-
-Alice Morgan owns memory-coverage.
-Bob Stone works_on memory-coverage.
-OpenHuman uses JSON-RPC.
-Cara Park prefers deterministic fixtures.
-Alice Morgan will review the ingestion assertions.
-Bob Stone sent draft notes to Cara Park.
-Kitchen is north of Garden.
-"#;
-
- let result = memory
- .ingest_document(MemoryIngestionRequest {
- document: NamespaceDocumentInput {
- namespace: "memory-raw-ingestion".into(),
- key: "plan-1".into(),
- title: "OpenHuman coverage memory plan".into(),
- content: content.into(),
- source_type: "test".into(),
- priority: "high".into(),
- tags: vec!["seed".into()],
- metadata: json!({ "fixture": "raw-memory-e2e" }),
- category: "core".into(),
- session_id: Some("session-coverage".into()),
- document_id: Some("doc-memory-raw-ingestion".into()),
- taint: openhuman_core::openhuman::memory::MemoryTaint::Internal,
- },
- config: MemoryIngestionConfig::default(),
- })
- .await
- .expect("ingest document");
-
- assert_eq!(result.document_id, "doc-memory-raw-ingestion");
- assert_eq!(result.namespace, "memory-raw-ingestion");
- assert!(result.tags.contains(&"deadline".to_string()));
- assert!(result.tags.contains(&"decision".to_string()));
- assert!(result.tags.contains(&"preference".to_string()));
- assert!(result.entity_count >= 5);
- assert!(result.relation_count >= 8);
- assert!(result.preference_count >= 1);
- assert!(result.decision_count >= 2);
- assert!(result
- .entities
- .iter()
- .any(|entity| entity.name == "ALICE MORGAN"));
- assert!(result
- .relations
- .iter()
- .any(|relation| relation.subject.contains("OPENHUMAN")
- && relation.predicate == "USES"
- && relation.object.contains("TEXT-EMBEDDING")));
-
- let rows = memory
- .graph_query_namespace("memory-raw-ingestion", Some("ALICE MORGAN"), Some("OWNS"))
- .await
- .expect("query graph");
- assert!(rows.iter().any(|row| row["object"] == "MEMORY-COVERAGE"));
-
- let context = memory
- .query_namespace_context_data(
- "memory-raw-ingestion",
- "who owns memory coverage and what uses text embedding",
- 5,
- )
- .await
- .expect("query context");
- assert!(context
- .hits
- .iter()
- .flat_map(|hit| hit.supporting_relations.iter())
- .any(|relation| relation.predicate == "OWNS" || relation.predicate == "USES"));
-
- let recall = memory
- .recall_namespace_memories("memory-raw-ingestion", 5)
- .await
- .expect("recall memories");
- assert!(recall
- .iter()
- .any(|hit| hit.document_id.as_deref() == Some("doc-memory-raw-ingestion")));
-
- let extract_again = memory
- .extract_graph(
- "doc-memory-raw-ingestion",
- &NamespaceDocumentInput {
- namespace: "memory-raw-ingestion".into(),
- key: "plan-1".into(),
- title: "OpenHuman coverage memory plan".into(),
- content: "OpenHuman uses JSON-RPC.\nAlice Morgan prefers small tests.".into(),
- source_type: "test".into(),
- priority: "high".into(),
- tags: Vec::new(),
- metadata: Value::Null,
- category: "core".into(),
- session_id: None,
- document_id: Some("doc-memory-raw-ingestion".into()),
- taint: openhuman_core::openhuman::memory::MemoryTaint::Internal,
- },
- &MemoryIngestionConfig {
- extraction_mode: tinycortex::memory::ingest::ExtractionMode::Chunk,
- ..Default::default()
- },
- )
- .await
- .expect("extract graph again");
- assert_eq!(extract_again.extraction_mode, "chunk");
- assert!(extract_again.preference_count >= 1);
-}
-
-#[tokio::test]
-async fn memory_source_readers_validate_and_use_local_inputs_only() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
-
- let mut folder = source(SourceKind::Folder, "src_folder");
- folder.path = Some(tmp.path().to_string_lossy().to_string());
- folder.glob = Some("**/*".into());
- std::fs::write(tmp.path().join("note.md"), "# Note").expect("write note");
- std::fs::write(tmp.path().join("page.html"), "<p>Body</p>").expect("write html");
- std::fs::write(tmp.path().join("plain.txt"), "Plain").expect("write txt");
- std::fs::create_dir_all(tmp.path().join("nested")).expect("nested dir");
-
- let folder_reader = reader_for(&SourceKind::Folder);
- assert_eq!(folder_reader.kind(), SourceKind::Folder);
- let items = folder_reader
- .list_items(&folder, &config)
- .await
- .expect("folder list");
- assert!(items.iter().any(|item| item.id == "note.md"));
- assert!(items.iter().any(|item| item.id == "page.html"));
- let html = folder_reader
- .read_item(&folder, "page.html", &config)
- .await
- .expect("folder read html");
- assert_eq!(html.content_type, ContentType::Html);
- let traversal = folder_reader
- .read_item(&folder, "../outside.md", &config)
- .await
- .unwrap_err();
- assert!(traversal.contains("not found") || traversal.contains("traversal"));
-
- let mut page = source(SourceKind::WebPage, "src_web");
- page.url = Some("http://127.0.0.1:9/page".into());
- page.selector = Some("main.content".into());
- let web_reader = reader_for(&SourceKind::WebPage);
- let page_error = web_reader
- .read_item(&page, "http://127.0.0.1:9/page", &config)
- .await
- .expect_err("private web host rejected before fetch");
- assert!(page_error.contains("public host"));
- page.url = Some("file:///etc/passwd".into());
- let bad_scheme = web_reader
- .read_item(&page, "relative-id", &config)
- .await
- .unwrap_err();
- assert!(bad_scheme.contains("http(s)"));
- let mut rss = source(SourceKind::RssFeed, "src_rss");
- rss.url = Some("http://127.0.0.1:9/feed".into());
- rss.max_items = Some(1);
- let rss_reader = reader_for(&SourceKind::RssFeed);
- let rss_error = rss_reader
- .list_items(&rss, &config)
- .await
- .expect_err("private RSS host rejected before fetch");
- assert!(rss_error.contains("public host"));
-
- let mut twitter = source(SourceKind::TwitterQuery, "src_tw");
- twitter.query = Some("AI safety".into());
- assert!(reader_for(&SourceKind::TwitterQuery)
- .list_items(&twitter, &config)
- .await
- .unwrap_err()
- .contains("not yet configured"));
-
- let mut composio = source(SourceKind::Composio, "src_cmp");
- composio.toolkit = Some("gmail".into());
- composio.connection_id = Some("conn-1".into());
- let composio_reader = reader_for(&SourceKind::Composio);
- assert_eq!(
- composio_reader
- .list_items(&composio, &config)
- .await
- .expect("composio list")[0]
- .title,
- "gmail connection"
- );
- assert!(composio_reader
- .read_item(&composio, "conn-1", &config)
- .await
- .expect("composio read")
- .body
- .contains("provider sync pipeline"));
-
- for (kind, expected) in [
- (SourceKind::Composio, "composio"),
- (SourceKind::Folder, "folder"),
- (SourceKind::GithubRepo, "github_repo"),
- (SourceKind::TwitterQuery, "twitter_query"),
- (SourceKind::RssFeed, "rss_feed"),
- (SourceKind::WebPage, "web_page"),
- ] {
- assert_eq!(kind.as_str(), expected);
- }
- assert!(source(SourceKind::GithubRepo, "bad")
- .validate()
- .unwrap_err()
- .contains("url"));
- assert!(source(SourceKind::TwitterQuery, "bad")
- .validate()
- .unwrap_err()
- .contains("query"));
-
- let mut github = source(SourceKind::GithubRepo, "src_github");
- github.url = Some("https://github.com/tinyhumansai/openhuman".into());
- let github_reader = reader_for(&SourceKind::GithubRepo);
- assert_eq!(github_reader.kind(), SourceKind::GithubRepo);
- assert!(github_reader
- .read_item(&github, "unknown:123", &config)
- .await
- .unwrap_err()
- .contains("invalid item id"));
- assert!(github_reader
- .read_item(&github, "issue:not-a-number", &config)
- .await
- .unwrap_err()
- .contains("invalid issue number"));
- assert!(github_reader
- .read_item(&github, "pr:not-a-number", &config)
- .await
- .unwrap_err()
- .contains("invalid PR number"));
- github.url = Some("https://github.com/tinyhumansai/openhuman/tree/main".into());
- assert!(github_reader
- .list_items(&github, &config)
- .await
- .unwrap_err()
- .contains("expected https://github.com/<owner>/<repo>"));
-}
-
-#[tokio::test]
-async fn memory_source_status_counts_reader_and_composio_prefixes() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
- let now = Utc::now().timestamp_millis();
- let chunks = vec![
- chunk("mem_src:src_folder:note-1", 0, now - 1_000),
- chunk("mem_src:src_folder:note-2", 1, now - 60_000),
- chunk("gmail:acct:msg-1", 0, now - 600_000),
- ];
- upsert_chunks(&config, &chunks).expect("upsert chunks");
- with_connection(&config, |conn| {
- // Mark the chunk embedded the way the status query now READS it.
- // Setting `mem_tree_chunks.embedding` no longer means anything: that
- // legacy column is never written by the engine, which is why the
- // status query used to report every chunk pending forever
- // (tinymemory#59 item 2). It counts against the live
- // `mem_tree_chunk_embeddings` sidecar now, so the fixture writes
- // there.
- conn.execute(
- "INSERT INTO mem_tree_chunk_embeddings \
- (chunk_id, model_signature, vector, dim, created_at) \
- SELECT id, 'test-model', X'00010203', 4, 0.0 \
- FROM mem_tree_chunks WHERE source_id = ?1",
- ["mem_src:src_folder:note-1"],
- )?;
- Ok(())
- })
- .expect("mark one embedded");
-
- let mut folder = source(SourceKind::Folder, "src_folder");
- folder.path = Some(tmp.path().to_string_lossy().to_string());
- let folder_status = source_status(&config, &folder)
- .await
- .expect("folder status");
- assert_eq!(folder_status.source_id, "src_folder");
- assert_eq!(folder_status.chunks_synced, 2);
- assert_eq!(folder_status.chunks_pending, 1);
- assert_eq!(folder_status.freshness, FreshnessLabel::Active);
-
- let mut composio = source(SourceKind::Composio, "src_cmp");
- composio.toolkit = Some("gmail".into());
- composio.connection_id = Some("acct".into());
- let composio_status = source_status(&config, &composio)
- .await
- .expect("composio status");
- assert_eq!(composio_status.chunks_synced, 1);
- assert_eq!(composio_status.chunks_pending, 1);
- assert_eq!(composio_status.freshness, FreshnessLabel::Idle);
-}
-
-#[tokio::test]
-async fn memory_thread_tree_and_sync_controller_schemas_execute_public_handlers() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", module_workspace());
- let config = Config::load_or_init().await.expect("init isolated config");
- wipe_shared_store(&config);
-
- let thread_schemas = all_threads_controller_schemas();
- let thread_controllers = all_threads_registered_controllers();
- assert_eq!(thread_schemas.len(), thread_controllers.len());
- assert_eq!(
- openhuman_core::openhuman::threads::schemas::schemas("missing").function,
- "unknown"
- );
- let expected_thread_functions = [
- "list",
- "upsert",
- "create_new",
- "messages_list",
- "message_append",
- "generate_title",
- "update_labels",
- "update_title",
- "message_update",
- "delete",
- "purge",
- "turn_state_get",
- "turn_state_list",
- "turn_state_history",
- "turn_state_get_turn",
- "turn_state_clear",
- "task_board_get",
- "task_board_put",
- "token_usage",
- ];
- assert!(
- thread_schemas.len() >= expected_thread_functions.len(),
- "expected at least {} thread controller schemas, got {}",
- expected_thread_functions.len(),
- thread_schemas.len()
- );
- for function in expected_thread_functions {
- assert!(thread_schemas
- .iter()
- .any(|schema| schema.namespace == "threads" && schema.function == function));
- }
-
- let thread_upsert = thread_controllers
- .iter()
- .find(|controller| controller.schema.function == "upsert")
- .expect("threads upsert controller");
- assert!((thread_upsert.handler)(Map::new())
- .await
- .unwrap_err()
- .contains("invalid params"));
-
- let task_board_put = thread_controllers
- .iter()
- .find(|controller| controller.schema.function == "task_board_put")
- .expect("task board put controller");
- let task_board_get = thread_controllers
- .iter()
- .find(|controller| controller.schema.function == "task_board_get")
- .expect("task board get controller");
- let mut put_params = Map::new();
- put_params.insert("thread_id".into(), json!("thread/schema-handlers"));
- put_params.insert(
- "cards".into(),
- json!([
- {
- "id": "card-1",
- "title": "Cover controller schemas",
- "status": "todo",
- "plan": ["inspect", "assert"],
- "order": 1,
- "updatedAt": "2026-05-29T12:00:00Z"
- }
- ]),
- );
- let put_json = (task_board_put.handler)(put_params)
- .await
- .expect("put task board");
- assert_eq!(put_json["taskBoard"]["cards"][0]["id"], "card-1");
-
- let mut get_params = Map::new();
- get_params.insert("thread_id".into(), json!("thread/schema-handlers"));
- let get_json = (task_board_get.handler)(get_params)
- .await
- .expect("get task board");
- assert_eq!(
- get_json["taskBoard"]["cards"][0]["title"],
- "Cover controller schemas"
- );
-
- let tree_schemas = all_tree_summarizer_controller_schemas();
- let tree_controllers = all_tree_summarizer_registered_controllers();
- assert_eq!(tree_schemas.len(), 5);
- assert_eq!(tree_schemas.len(), tree_controllers.len());
- let ingest_schema = tree_schemas
- .iter()
- .find(|schema| schema.function == "ingest")
- .expect("ingest schema");
- assert!(ingest_schema
- .inputs
- .iter()
- .any(|field| field.name == "metadata" && !field.required));
-
- let tree_status = tree_controllers
- .iter()
- .find(|controller| controller.schema.function == "status")
- .expect("tree status controller");
- let mut tree_params = Map::new();
- tree_params.insert("namespace".into(), json!("schema_handlers"));
- let status_json = (tree_status.handler)(tree_params)
- .await
- .expect("tree status");
- assert_eq!(status_json["result"]["total_nodes"], 0);
- let tree_ingest = tree_controllers
- .iter()
- .find(|controller| controller.schema.function == "ingest")
- .expect("tree ingest controller");
- let mut bad_ingest = Map::new();
- bad_ingest.insert("namespace".into(), json!("schema_handlers"));
- bad_ingest.insert("content".into(), json!("content"));
- bad_ingest.insert("timestamp".into(), json!(123));
- assert!((tree_ingest.handler)(bad_ingest)
- .await
- .unwrap_err()
- .contains("expected string"));
-
- let sync_schemas = memory_sync_status_schemas::all_controller_schemas();
- let sync_controllers = memory_sync_status_schemas::all_registered_controllers();
- assert_eq!(sync_schemas.len(), 1);
- assert_eq!(sync_controllers.len(), 1);
- assert_eq!(sync_schemas[0].function, "status_list");
-
- let now = Utc::now().timestamp_millis();
- let mut first = chunk("slack:team:message-1", 0, now - 1_000);
- first.id = "sync-status-covered-1".into();
- let mut second = chunk("slack:team:message-2", 1, now - 2_000);
- second.id = "sync-status-covered-2".into();
- upsert_chunks(&config, &[first, second]).expect("upsert sync status chunks");
- with_connection(&config, |conn| {
- conn.execute(
- "INSERT INTO mem_tree_chunk_embeddings \
- (chunk_id, model_signature, vector, dim, created_at) \
- VALUES ('sync-status-covered-1', 'test-sig', X'00000000', 1, 0.0)",
- [],
- )?;
- Ok(())
- })
- .expect("insert embedding sidecar");
-
- let status = memory_sync_status_rpc::status_list_rpc(&config)
- .await
- .expect("sync status rpc")
- .value;
- let slack = status
- .statuses
- .iter()
- .find(|status| status.provider == "slack")
- .expect("slack sync status");
- assert_eq!(slack.chunks_synced, 2);
- assert_eq!(slack.chunks_pending, 1);
- assert_eq!(slack.batch_total, 2);
- assert_eq!(slack.batch_processed, 1);
-
- let status_json = (sync_controllers[0].handler)(Map::new())
- .await
- .expect("sync status controller");
- assert!(status_json["statuses"]
- .as_array()
- .unwrap()
- .iter()
- .any(|row| row["provider"] == "slack"));
-
- let slack_schemas = slack_memory_schemas::all_slack_memory_controller_schemas();
- let slack_controllers = slack_memory_schemas::all_slack_memory_registered_controllers();
- assert_eq!(slack_schemas.len(), 2);
- assert_eq!(slack_schemas.len(), slack_controllers.len());
- assert_eq!(slack_memory_schemas::schemas("unknown").function, "unknown");
- let trigger = slack_controllers
- .iter()
- .find(|controller| controller.schema.function == "sync_trigger")
- .expect("slack sync trigger controller");
- let mut bad_trigger = Map::new();
- bad_trigger.insert("connection_id".into(), json!(123));
- assert!((trigger.handler)(bad_trigger)
- .await
- .unwrap_err()
- .contains("invalid params"));
-}
-
-#[test]
-fn memory_schema_registries_and_query_tool_metadata_cover_public_surfaces() {
- let memory_schemas = all_memory_controller_schemas();
- let memory_controllers = all_memory_registered_controllers();
- // 35 → 37 with #5932: memory.scheduler_override (the gate's manual
- // window) and memory.namespace_summaries (the sync-verification counts).
- assert_eq!(memory_schemas.len(), 37);
- assert_eq!(memory_schemas.len(), memory_controllers.len());
- for function in [
- "init",
- "list_documents",
- "list_namespaces",
- "delete_document",
- "query_namespace",
- "recall_context",
- "recall_memories",
- "namespace_list",
- "doc_put",
- "doc_ingest",
- "doc_list",
- "doc_delete",
- "context_query",
- "context_recall",
- "clear_namespace",
- "list_files",
- "read_file",
- "write_file",
- "kv_set",
- "kv_get",
- "kv_delete",
- "kv_list_namespace",
- "graph_upsert",
- "graph_query",
- "sync_channel",
- "sync_all",
- "ingestion_status",
- "learn_all",
- "tool_rule_put",
- "tool_rule_get",
- "tool_rule_list",
- "tool_rule_delete",
- "tool_rules_for_prompt",
- "tool_rules_json",
- ] {
- let schema = openhuman_core::openhuman::memory::schemas::schemas(function);
- assert_eq!(schema.namespace, "memory");
- assert_eq!(schema.function, function);
- assert!(memory_schemas
- .iter()
- .any(|candidate| candidate.function == function));
- }
- assert_eq!(
- openhuman_core::openhuman::memory::schemas::schemas("missing").function,
- "unknown"
- );
-
- let legacy_tree_schemas = openhuman_core::openhuman::memory::schema::all_controller_schemas();
- let legacy_tree_controllers =
- openhuman_core::openhuman::memory::schema::all_registered_controllers();
- assert!(
- legacy_tree_schemas.len() >= 19,
- "expected at least 19 memory controller schemas, got {}",
- legacy_tree_schemas.len()
- );
- assert_eq!(legacy_tree_schemas.len(), legacy_tree_controllers.len());
- for function in [
- "ingest",
- "list_chunks",
- "get_chunk",
- "memory_backfill_status",
- "list_sources",
- "search",
- "recall",
- "entity_index_for",
- "chunks_for_entity",
- "top_entities",
- "chunk_score",
- "delete_chunk",
- "graph_export",
- "obsidian_vault_status",
- "flush_now",
- "wipe_all",
- "reset_tree",
- "pipeline_status",
- "set_enabled",
- ] {
- let schema = openhuman_core::openhuman::memory::schema::schemas(function);
- assert_eq!(schema.namespace, "memory_tree");
- assert_eq!(schema.function, function);
- assert!(legacy_tree_schemas
- .iter()
- .any(|candidate| candidate.function == function));
- }
- assert_eq!(
- openhuman_core::openhuman::memory::schema::schemas("missing").function,
- "unknown"
- );
-
- let consolidated = MemoryQueryTool;
- let schema = consolidated.parameters_schema();
- assert_eq!(consolidated.name(), "memory_tree");
- assert_eq!(consolidated.category(), ToolCategory::System);
- assert_eq!(consolidated.permission_level(), PermissionLevel::ReadOnly);
- assert!(schema["properties"]["mode"]["enum"]
- .as_array()
- .unwrap()
- .iter()
- .any(|mode| mode == "walk"));
-
- for tool in [
- &MemoryTreeSearchEntitiesTool as &dyn Tool,
- &MemoryTreeQuerySourceTool,
- &MemoryTreeDrillDownTool,
- &MemoryTreeFetchLeavesTool,
- &MemoryTreeIngestDocumentTool,
- ] {
- assert!(!tool.name().is_empty());
- assert!(!tool.description().is_empty());
- assert_eq!(tool.category(), ToolCategory::System);
- assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);
- assert_eq!(tool.parameters_schema()["type"], "object");
- let _ = tool.is_concurrency_safe(&json!({}));
- }
-}
-
-#[test]
-fn memory_tree_policy_and_source_registry_write_metadata_mirror() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
- let policy = TreePolicy::topic();
- let now = 1_700_000_000_000_i64;
- assert_eq!(TreePolicy::global(), TreePolicy::Global);
- assert_eq!(TreePolicy::source(), TreePolicy::Source);
- assert!(policy.topic_creation_threshold() > policy.topic_archive_threshold());
- assert_eq!(policy.topic_recency_decay(None, now), 0.0);
- assert_eq!(policy.topic_recency_decay(Some(now + 60_000), now), 1.0);
- assert_eq!(
- policy.topic_recency_decay(Some(now - 60 * 86_400_000), now),
- 0.0
- );
-
- let stats = tinymemory_core::store::trees::types::EntityIndexStats {
- mention_count_30d: 9,
- distinct_sources: 4,
- last_seen_ms: Some(now - 4 * 86_400_000),
- query_hits_30d: 2,
- graph_centrality: Some(0.75),
- };
- assert!(policy.topic_hotness("[email protected]", &stats, now) > 0.0);
-
- let first = tree_source::get_or_create_source_tree(&config, "gmail:[email protected]")
- .expect("create source tree");
- let second = tree_source::get_or_create_source_tree(&config, "gmail:[email protected]")
- .expect("reuse source tree");
- assert_eq!(first.id, second.id);
-
- let mirror = tree_source::file::source_file_path(&config, &first.scope);
- let body = std::fs::read_to_string(&mirror)
- .unwrap_or_else(|err| panic!("read {}: {err}", mirror.display()));
- assert!(body.starts_with("---\n"));
- assert!(body.contains("kind: source"));
- assert!(body.contains("scope: \"gmail:[email protected]\""));
- assert!(body.contains("last_sealed_at: null"));
-}
-
-#[test]
-fn thread_title_error_and_turn_state_helpers_cover_wire_shapes() {
- assert!(is_auto_generated_thread_title("Chat Jan 1 1:23 AM"));
- assert!(!is_auto_generated_thread_title("Chat Jan 1 1:2 AM"));
- assert!(!is_auto_generated_thread_title("Planning the launch"));
- assert_eq!(collapse_whitespace(" a\tb\n c "), "a b c");
- assert_eq!(
- sanitize_generated_title("\n`Deploy review!`\nsecond").as_deref(),
- Some("Deploy review")
- );
- assert!(sanitize_generated_title("\"\"").is_none());
- assert_eq!(
- title_from_user_message("/briefing Morning update. Then email").as_deref(),
- Some("briefing Morning update")
- );
- assert_ne!(
- title_log_fingerprint("alpha"),
- title_log_fingerprint("beta")
- );
- let prompt = build_title_prompt("hello", "hi");
- assert!(prompt.contains("First user message:\nhello"));
- assert!(prompt.contains("Assistant reply:\nhi"));
-
- let not_found: String = ThreadsError::not_found("thread-1").into();
- assert!(not_found.contains("ThreadNotFound"));
- let scoped = ThreadsError::from_thread_scoped_store_error(
- "thread-1",
- "thread thread-2 not found".to_string(),
- );
- assert!(matches!(scoped, ThreadsError::Message(_)));
-
- let mut state = TurnState::started("thread-1", "request-1", 6, "2026-05-29T12:00:00Z");
- state.lifecycle = TurnLifecycle::Streaming;
- state.phase = Some(TurnPhase::ToolUse);
- state.active_tool = Some("memory.search".into());
- state.tool_timeline.push(ToolTimelineEntry {
- id: "tool-1".into(),
- name: "memory.search".into(),
- round: 1,
- status: ToolTimelineStatus::Success,
- failure: None,
- args_buffer: Some("{\"q\":\"coverage\"}".into()),
- display_name: Some("Memory Search".into()),
- detail: Some("2 results".into()),
- source_tool_name: Some("memory.search".into()),
- subagent: None,
- output: None,
- seq: None,
- });
- let wire = serde_json::to_value(GetTurnStateResponse {
- turn_state: Some(state.clone()),
- })
- .expect("turn state json");
- assert_eq!(wire["turnState"]["threadId"], "thread-1");
- assert_eq!(wire["turnState"]["phase"], "tool_use");
- let decoded: GetTurnStateResponse = serde_json::from_value(wire).expect("decode turn state");
- assert_eq!(decoded.turn_state.unwrap(), state);
-}
-
-#[test]
-fn memory_sync_composio_catalog_scope_and_state_helpers_cover_edge_cases() {
- assert_eq!(SyncReason::ConnectionCreated.as_str(), "connection_created");
- assert_eq!(SyncReason::Periodic.as_str(), "periodic");
- assert_eq!(SyncReason::Manual.as_str(), "manual");
-
- let mut outcome = ComposioSyncOutcome {
- toolkit: "gmail".into(),
- connection_id: Some("conn-1".into()),
- reason: SyncReason::Manual.as_str().into(),
- items_ingested: 3,
- started_at_ms: 200,
- finished_at_ms: 150,
- summary: "done".into(),
- details: json!({ "pages": 1 }),
- };
- assert_eq!(outcome.elapsed_ms(), 0);
- outcome.finished_at_ms = 275;
- assert_eq!(outcome.elapsed_ms(), 75);
-
- assert_eq!(TaskFetchFilter::default().effective_max(), 25);
- assert_eq!(
- TaskFetchFilter {
- max: 7,
- ..Default::default()
- }
- .effective_max(),
- 7
- );
- let task_json = json!({
- "externalId": "issue-1",
- "provider": "github",
- "title": "Fix coverage",
- "labels": ["test"],
- "raw": { "number": 1 }
- });
- let task: NormalizedTask = serde_json::from_value(task_json).expect("task");
- assert_eq!(task.external_id, "issue-1");
- assert_eq!(task.source_id, "");
- assert_eq!(task.labels, vec!["test"]);
-
- let profile = ProviderUserProfile {
- toolkit: "github".into(),
- email: Some("[email protected]".into()),
- extras: json!({ "login": "dev" }),
- ..Default::default()
- };
- assert_eq!(
- serde_json::to_value(profile).unwrap()["extras"]["login"],
- "dev"
- );
-
- assert_eq!(ToolScope::Read.as_str(), "read");
- assert_eq!(ToolScope::Write.as_str(), "write");
- assert_eq!(ToolScope::Admin.as_str(), "admin");
- assert_eq!(classify_unknown("GMAIL_DELETE_DRAFT"), ToolScope::Admin);
- assert_eq!(classify_unknown("NOTION_CREATE_PAGE"), ToolScope::Write);
- assert_eq!(classify_unknown("GMAIL_FETCH_EMAILS"), ToolScope::Read);
- assert_eq!(
- toolkit_from_slug(" MICROSOFT_TEAMS_SEND_MESSAGE "),
- Some("microsoft_teams".into())
- );
- assert_eq!(toolkit_from_slug(""), None);
- let catalog = &[CuratedTool {
- slug: "GMAIL_SEND_EMAIL",
- scope: ToolScope::Write,
- }];
- assert_eq!(
- find_curated(catalog, "gmail_send_email").map(|tool| tool.scope),
- Some(ToolScope::Write)
- );
- assert!(find_curated(catalog, "GMAIL_DELETE_EMAIL").is_none());
-
- let read_only = UserScopePref {
- read: true,
- write: false,
- admin: false,
- };
- assert!(is_action_visible_with_pref(
- "GMAIL_FETCH_EMAILS",
- &read_only
- ));
- assert!(!is_action_visible_with_pref("GMAIL_SEND_EMAIL", &read_only));
- assert_eq!(
- curated_scope_for("GMAIL_DELETE_MESSAGE"),
- Some(ToolScope::Admin)
- );
- assert!(toolkit_has_scope("gmail", ToolScope::Admin));
- assert!(catalog_for_toolkit("google_calendar").is_some());
- assert!(agent_ready_toolkits()
- .windows(2)
- .all(|pair| pair[0] <= pair[1]));
-
- // `capability_matrix()` — the host-side static function this used to
- // build from the curated catalogs — is itself gone, not just relocated:
- // `composio_list_capabilities` (`integrations::composio::ops::toolkits`)
- // now answers directly from the connector module's live
- // `ListCapabilities` reply, with no host-side matrix or conversion left
- // to call statically. Confirmed by that op's own doc comment. Genuine,
- // unrecoverable coverage gap for this specific assertion; the
- // `has_native_provider`/`catalog_for_toolkit` checks above already cover
- // the same per-toolkit facts this matrix used to expose.
-
- let sync_target = composio::SyncTarget {
- toolkit: "gmail".into(),
- connection_id: "conn-1".into(),
- };
- assert_eq!(sync_target.toolkit, "gmail");
-
- let mut budget = DailyBudget {
- date: "2000-01-01".into(),
- requests_used: DEFAULT_DAILY_REQUEST_LIMIT,
- limit: DEFAULT_DAILY_REQUEST_LIMIT,
- };
- assert_eq!(budget.remaining(), DEFAULT_DAILY_REQUEST_LIMIT);
- budget.record_request();
- assert_eq!(budget.requests_used, 1);
- budget.record_requests(DEFAULT_DAILY_REQUEST_LIMIT + 10);
- assert!(budget.is_exhausted());
-
- let mut state = SyncState::new("gmail", "conn-1");
- assert_eq!(state.budget_remaining(), DEFAULT_DAILY_REQUEST_LIMIT);
- assert!(!state.budget_exhausted());
- state.record_requests(2);
- state.mark_synced("msg-1");
- state.advance_cursor("cursor-1");
- state.set_last_seen_id("msg-2");
- state.set_last_sync_at_ms(123);
- assert!(state.is_synced("msg-1"));
- assert!(!state.is_synced("msg-2"));
- assert_eq!(state.cursor.as_deref(), Some("cursor-1"));
- assert_eq!(state.last_seen_id.as_deref(), Some("msg-2"));
- assert_eq!(state.last_sync_at_ms, Some(123));
-
- let item = json!({
- "id": " ",
- "message": { "id": " msg-99 " },
- "nested": { "empty": "" }
- });
- assert_eq!(
- extract_item_id(&item, &["missing", "nested.empty", "message.id"]),
- Some("msg-99".into())
- );
- assert_eq!(extract_item_id(&item, &["missing"]), None);
-}
-
-/// The `slack_memory` RPC schema assertions below are unchanged real
-/// coverage — `memory::sync::composio::providers::slack::schemas` is this
-/// host's own current RPC surface, not part of the deletion.
-///
-/// The rest of this test's original name is no longer accurate: it also
-/// drove the deleted engine's per-action Slack response reshaping
-/// (`providers::slack::post_process` — history/channel/search-result
-/// normalization, empty-text filtering, non-object passthrough). That moved
-/// into the separately-versioned `tinyconnectors` module with nothing left
-/// in this crate to assert against — see
-/// `memory_sync_providers_raw_coverage_e2e.rs`'s module doc comment for the
-/// fuller account of this same gap. Reported rather than silently dropped;
-/// not recoverable from here.
-#[test]
-fn slack_memory_schemas_cover_public_surfaces() {
- let schemas = slack_memory_schemas::all_slack_memory_controller_schemas();
- assert_eq!(schemas.len(), 2);
- assert_eq!(schemas[0].namespace, "slack_memory");
- assert!(schemas
- .iter()
- .any(|schema| schema.function == "sync_status" && schema.inputs.is_empty()));
-}
-
-#[test]
-fn memory_tree_scoring_signal_helpers_cover_boundaries_and_serialization() {
- assert_eq!(EntityKind::parse("email").unwrap(), EntityKind::Email);
- assert!(EntityKind::Email.is_mechanical());
- assert!(!EntityKind::Person.is_mechanical());
- assert!(EntityKind::parse("unknown").is_err());
-
- let regex_entities = tinymemory_core::tree::score::extract::regex::extract(
- "Alice emailed [email protected] from https://example.test and mentioned #coverage.",
- );
- assert!(regex_entities
- .entities
- .iter()
- .any(|entity| entity.kind == EntityKind::Email && entity.text == "[email protected]"));
- let canonical = resolver::canonicalise(&regex_entities);
- assert!(canonical
- .iter()
- .any(|entity| entity.canonical_id == "email:[email protected]"));
- assert_eq!(
- resolver::canonical_id_for(EntityKind::Url, "https://Example.test/path/"),
- "url:https://Example.test/path/"
- );
- assert_eq!(
- resolver::canonical_id_for(EntityKind::Hashtag, "#Coverage"),
- "hashtag:coverage"
- );
- let scoring_config = ScoringConfig::default_regex_only();
- assert!(scoring_config.definite_keep_threshold > scoring_config.definite_drop_threshold);
- assert!(scoring_config.llm_extractor.is_none());
- let regex_only = CompositeExtractor::regex_only();
- assert_eq!(regex_only.name(), "composite");
-
- let mut extracted = ExtractedEntities {
- entities: vec![ExtractedEntity {
- kind: EntityKind::Person,
- text: "Alice".into(),
- span_start: 0,
- span_end: 5,
- score: 0.9,
- }],
- topics: vec![ExtractedTopic {
- label: "phoenix".into(),
- score: 0.8,
- }],
- llm_importance: Some(0.3),
- llm_importance_reason: Some("initial".into()),
- };
- assert!(!extracted.is_empty());
- extracted.merge(ExtractedEntities {
- entities: vec![
- ExtractedEntity {
- kind: EntityKind::Person,
- text: "alice".into(),
- span_start: 0,
- span_end: 5,
- score: 1.0,
- },
- ExtractedEntity {
- kind: EntityKind::Organization,
- text: "OpenHuman".into(),
- span_start: 10,
- span_end: 19,
- score: 0.7,
- },
- ],
- topics: vec![
- ExtractedTopic {
- label: "phoenix".into(),
- score: 0.9,
- },
- ExtractedTopic {
- label: "coverage".into(),
- score: 0.6,
- },
- ],
- llm_importance: Some(0.8),
- llm_importance_reason: Some("higher".into()),
- });
- assert_eq!(extracted.entities.len(), 2);
- assert_eq!(extracted.topics.len(), 2);
- assert_eq!(extracted.unique_entity_count(), 2);
- assert_eq!(extracted.llm_importance, Some(0.8));
- assert_eq!(extracted.llm_importance_reason.as_deref(), Some("higher"));
-
- assert_eq!(token_count::score(0), 0.0);
- assert_eq!(token_count::score(30), 1.0);
- assert_eq!(token_count::score(9_000), 0.5);
- assert_eq!(unique_words::score("hi bob"), 0.5);
- assert!(unique_words::score("repeat repeat repeat repeat repeat repeat") < 0.1);
- assert!(unique_words::score("alpha beta gamma delta epsilon zeta eta") > 0.9);
-
- let mut meta = Metadata::point_in_time(ChunkSourceKind::Chat, "thread-1", "owner", Utc::now());
- assert_eq!(interaction::score(&meta), 0.5);
- meta.tags = vec![
- "sent".into(),
- "reply".into(),
- "mention".into(),
- "provider:whatsapp".into(),
- ];
- assert_eq!(interaction::score(&meta), 1.0);
- assert_eq!(
- source_weight::infer_data_source(&meta),
- Some(DataSource::Whatsapp)
- );
- assert!(source_weight::score(&meta) > 0.7);
- assert_eq!(metadata_weight::score(&meta), 0.5);
-
- let email_meta = Metadata::point_in_time(ChunkSourceKind::Email, "mail", "owner", Utc::now());
- let doc_meta = Metadata::point_in_time(ChunkSourceKind::Document, "doc", "owner", Utc::now());
- assert!(metadata_weight::score(&doc_meta) > metadata_weight::score(&email_meta));
- assert_eq!(source_weight::score(&email_meta), 0.75);
-
- let computed = compute_score_signals(
- &meta,
- "Alice from OpenHuman mentioned Phoenix migration on Friday",
- 120,
- &extracted,
- );
- assert!(computed.token_count > 0.0);
- assert!(computed.unique_words > 0.0);
- assert_eq!(computed.llm_importance, 0.8);
- assert_eq!(entity_density_score(0, &extracted), 0.0);
- assert!(entity_density_score(120, &extracted) > 0.0);
-
- let weights = SignalWeights::with_llm_enabled();
- let total = combine(&computed, &weights);
- let cheap_total = combine_cheap_only(&computed, &weights);
- assert!((0.0..=1.0).contains(&total));
- assert!((0.0..=1.0).contains(&cheap_total));
- assert_eq!(
- combine(&ScoreSignals::default(), &SignalWeights::default()),
- 0.0
- );
-
- for data_source in DataSource::all() {
- assert_eq!(
- DataSource::parse(data_source.as_str()).unwrap(),
- *data_source
- );
- assert_eq!(
- data_source.kind(),
- DataSource::parse(data_source.as_str()).unwrap().kind()
- );
- }
- assert!(DataSource::parse("missing").is_err());
-}
-
-#[test]
-fn memory_tree_runtime_store_buffers_and_retrieval_wire_helpers() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
- let namespace = "slack:#eng";
- let root = tree_node(namespace, "root", "Workspace root summary");
- let year = tree_node(namespace, "2026", "Year summary");
- let month = tree_node(namespace, "2026/05", "Month summary");
- let day = tree_node(namespace, "2026/05/29", "Day summary");
- let hour = tree_node(namespace, "2026/05/29/12", "Hour leaf body");
-
- for node in [&root, &year, &month, &day, &hour] {
- tree_runtime_store::write_node(&config, node).expect("write tree node");
- }
-
- assert_eq!(
- tree_runtime_store::read_node(&config, namespace, "root")
- .unwrap()
- .unwrap()
- .summary,
- "Workspace root summary"
- );
- assert!(tree_runtime_store::read_node(&config, namespace, "missing")
- .unwrap()
- .is_none());
- assert_eq!(
- tree_runtime_store::read_children(&config, namespace, "root")
- .unwrap()
- .into_iter()
- .map(|node| node.node_id)
- .collect::<Vec<_>>(),
- vec!["2026"]
- );
- assert_eq!(
- tree_runtime_store::read_children(&config, namespace, "2026/05/29")
- .unwrap()
- .into_iter()
- .map(|node| node.node_id)
- .collect::<Vec<_>>(),
- vec!["2026/05/29/12"]
- );
- assert_eq!(
- tree_runtime_store::read_ancestors(&config, namespace, "2026/05/29/12")
- .unwrap()
- .len(),
- 4
- );
- assert_eq!(
- tree_runtime_store::count_nodes(&config, namespace).unwrap(),
- 5
- );
- let status = tree_runtime_store::get_tree_status(&config, namespace).unwrap();
- assert_eq!(status.total_nodes, 5);
- assert_eq!(status.depth, 5);
- assert_eq!(
- status.oldest_entry.unwrap().to_rfc3339(),
- "2026-05-29T12:00:00+00:00"
- );
-
- let summaries = tree_runtime_store::collect_root_summaries_with_caps(tmp.path(), 10, 12);
- assert_eq!(summaries.len(), 1);
- let stored_namespace = tree_runtime_store::tree_dir(&config, namespace)
- .parent()
- .and_then(std::path::Path::file_name)
- .and_then(std::ffi::OsStr::to_str)
- .expect("sanitized namespace directory")
- .to_string();
- assert!(stored_namespace.starts_with("slack_#eng-"));
- assert_eq!(summaries[0].0, stored_namespace);
- assert!(summaries[0].1.contains("[... truncated]"));
- assert_eq!(
- tree_runtime_store::list_namespaces_with_root(&config).unwrap(),
- vec![stored_namespace]
- );
-
- let ts = Utc.with_ymd_and_hms(2026, 5, 29, 13, 0, 0).unwrap();
- let first_buffer = tree_runtime_store::buffer_write(
- &config,
- namespace,
- "first buffered body",
- &ts,
- Some(&json!({ "source": "test" })),
- )
- .expect("buffer write");
- let second_buffer =
- tree_runtime_store::buffer_write(&config, namespace, "second buffered body", &ts, None)
- .expect("buffer write second");
- let buffered = tree_runtime_store::buffer_read(&config, namespace).expect("buffer read");
- assert_eq!(buffered.len(), 2);
- assert!(buffered
- .iter()
- .any(|(_, body)| body == "first buffered body"));
- tree_runtime_store::buffer_delete(
- &config,
- namespace,
- &[first_buffer
- .file_name()
- .unwrap()
- .to_string_lossy()
- .to_string()],
- )
- .expect("buffer delete");
- assert!(!first_buffer.exists());
- assert!(second_buffer.exists());
- let drained = tree_runtime_store::buffer_drain(&config, namespace).expect("buffer drain");
- assert_eq!(drained.len(), 1);
- assert!(tree_runtime_store::buffer_read(&config, namespace)
- .unwrap()
- .is_empty());
-
- assert_eq!(NodeLevel::Hour.max_tokens(), 1_000);
- assert_eq!(NodeLevel::Month.parent_level(), Some(NodeLevel::Year));
- assert_eq!(NodeLevel::from_str_label("DAY"), Some(NodeLevel::Day));
- assert_eq!(
- derive_parent_id("2026/05/29/12").as_deref(),
- Some("2026/05/29")
- );
- assert_eq!(
- derive_node_ids(&ts),
- (
- "2026/05/29/13".to_string(),
- "2026/05/29".to_string(),
- "2026/05".to_string(),
- "2026".to_string(),
- "root".to_string()
- )
- );
- assert_eq!(node_id_to_path("root").to_string_lossy(), "root.md");
- assert!(tree_runtime_store::validate_namespace("team").is_ok());
- assert!(tree_runtime_store::validate_namespace("../bad").is_err());
- assert!(tree_runtime_store::validate_node_id("2026/05/29/23").is_ok());
- assert!(tree_runtime_store::validate_node_id("2026/13").is_err());
-
- let legacy = tree_runtime_store::parse_node_markdown_pub("legacy body", namespace, "2026")
- .expect("parse legacy");
- assert_eq!(legacy.level, NodeLevel::Year);
- assert_eq!(legacy.created_at, chrono::DateTime::<Utc>::UNIX_EPOCH);
- assert_eq!(
- tree_runtime_store::delete_tree(&config, namespace).unwrap(),
- 5
- );
- assert_eq!(
- tree_runtime_store::delete_tree(&config, namespace).unwrap(),
- 0
- );
-
- let source_factory = tinymemory_core::tree::tree::TreeFactory::source(
- );
- assert_eq!(
- source_factory.profile(),
- tinymemory_core::tree::tree::TreeProfile::Source
- );
- assert_eq!(
- source_factory.scope_slug(),
- "alice-example-com-bob-example-com"
- );
- let source_tree = source_factory
- .get_or_create(&config)
- .expect("source tree from factory");
- assert_eq!(
- tinymemory_core::tree::tree::TreeFactory::from_tree(&source_tree).kind(),
- TreeKind::Source
- );
- let topic_factory = tinymemory_core::tree::tree::TreeFactory::topic(
- );
- assert!(matches!(
- topic_factory.summary_tree_kind(),
- tinymemory_core::store::content::SummaryTreeKind::Topic
- ));
- let topic_tree = topic_factory
- .get_or_create(&config)
- .expect("topic tree from factory");
- assert_ne!(source_tree.id, topic_tree.id);
- assert!(
- tinymemory_core::tree::tree::new_tree_id(TreeKind::Global)
- .starts_with("global:")
- );
- assert!(tinymemory_core::tree::tree::new_summary_id(2).contains(":L2-"));
- assert!(
- tinymemory_core::tree::tree::registry::is_unique_violation(
- &anyhow::anyhow!("UNIQUE constraint failed: mem_trees.kind, mem_trees.scope")
- )
- );
- source_factory
- .archive(&config)
- .expect("archive source tree");
- assert_eq!(
- tinymemory_core::tree::tree::store::get_tree_by_scope(
- &config,
- TreeKind::Source,
- )
- .unwrap()
- .unwrap()
- .status,
- StoredTreeStatus::Archived
- );
-}
-
-#[tokio::test]
-async fn memory_read_rpc_score_index_and_summary_helpers_cover_dashboard_paths() {
- // Serialised with every other case on the shared module store: a parallel
- // run of this target would otherwise let another case's `wipe_shared_store`
- // empty the rows seeded below before the reads assert on them.
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let mut config = config_in(&tmp);
- use_module_workspace(&mut config);
- wipe_shared_store(&config);
-
- let now = Utc.with_ymd_and_hms(2026, 5, 29, 14, 0, 0).unwrap();
- let mut gmail = chunk(
- 0,
- now.timestamp_millis(),
- );
- gmail.id = "read-rpc-gmail-1".into();
- gmail.content =
- "Alice and Bob discussed coverage, entity indexing, and dashboard recall.".into();
- gmail.token_count = approx_token_count(&gmail.content);
- gmail.metadata.source_kind = ChunkSourceKind::Email;
- gmail.metadata.tags = vec!["sent".into(), "provider:gmail".into()];
- let mut slack = chunk("slack:#eng", 1, now.timestamp_millis() - 60_000);
- slack.id = "read-rpc-slack-1".into();
- slack.content = "Engineering channel mentioned coverage dashboards.".into();
- slack.token_count = approx_token_count(&slack.content);
- slack.metadata.source_kind = ChunkSourceKind::Chat;
- slack.metadata.tags = vec!["reply".into(), "provider:slack".into()];
- upsert_chunks(&config, &[gmail.clone(), slack.clone()]).expect("upsert read rpc chunks");
- // `has_embedding` is a row in the embeddings table, not the legacy column.
- with_connection(&config, |conn| {
- conn.execute(
- "UPDATE mem_tree_chunks SET tags_json = ?2 WHERE id = ?1",
- (&gmail.id, json!(["sent", "provider:gmail"]).to_string()),
- )?;
- conn.execute(
- "INSERT INTO mem_tree_chunk_embeddings \
- (chunk_id, model_signature, vector, dim, created_at) \
- VALUES (?1, 'test-sig', X'00010203', 1, 0.0)",
- [&gmail.id],
- )?;
- Ok(())
- })
- .expect("mark embedded and tags");
-
- let entity = CanonicalEntity {
- canonical_id: "email:[email protected]".into(),
- kind: EntityKind::Email,
- surface: "[email protected]".into(),
- span_start: 0,
- span_end: 15,
- score: 0.9,
- };
- score_store::index_entity(
- &config,
- &entity,
- &gmail.id,
- "leaf",
- now.timestamp_millis(),
- None,
- )
- .expect("index entity");
- assert_eq!(
- score_store::index_entities(&config, &[], "unused", "leaf", now.timestamp_millis(), None)
- .expect("empty index"),
- 0
- );
- let score_row = score_store::ScoreRow {
- chunk_id: gmail.id.clone(),
- total: 0.82,
- signals: ScoreSignals {
- token_count: 1.0,
- unique_words: 0.8,
- metadata_weight: 0.7,
- source_weight: 0.75,
- interaction: 0.5,
- entity_density: 0.4,
- llm_importance: 0.6,
- },
- dropped: false,
- reason: Some("kept for coverage".into()),
- computed_at_ms: now.timestamp_millis(),
- llm_importance_reason: Some("explicit project signal".into()),
- };
- score_store::upsert_score(&config, &score_row).expect("upsert score");
- assert_eq!(score_store::count_scores(&config).unwrap(), 1);
- assert_eq!(score_store::count_entity_index(&config).unwrap(), 1);
- assert_eq!(
- score_store::list_entity_ids_for_node(&config, &gmail.id).unwrap(),
- vec!["email:[email protected]".to_string()]
- );
- assert_eq!(
- score_store::lookup_entity(&config, "email:[email protected]", Some(10)).unwrap()[0].node_id,
- gmail.id
- );
-
- let listed = memory_read_rpc::list_chunks_rpc(
- &config,
- memory_read_rpc::ChunkFilter {
- source_kinds: Some(vec!["email".into()]),
- entity_ids: Some(vec!["email:[email protected]".into()]),
- query: Some("coverage".into()),
- limit: Some(10),
- ..Default::default()
- },
- )
- .await
- .expect("list chunks")
- .value;
- assert_eq!(listed.total, 1);
- assert_eq!(listed.chunks[0].id, gmail.id);
- assert!(listed.chunks[0].has_embedding);
- assert_eq!(listed.chunks[0].tags, vec!["sent", "provider:gmail"]);
-
- let sources = memory_read_rpc::list_sources_rpc(&config, Some("[email protected]".into()))
- .await
- .expect("list sources")
- .value;
- let gmail_source = sources
- .iter()
- .find(|source| source.source_id == "gmail:[email protected]|[email protected]")
- .expect("gmail source");
- assert_eq!(gmail_source.display_name, "[email protected]");
-
- let search = memory_read_rpc::search_rpc(&config, "dashboards".into(), 5)
- .await
- .expect("search")
- .value;
- assert_eq!(search.len(), 1);
- assert_eq!(search[0].source_id, "slack:#eng");
-
- let indexed = memory_read_rpc::entity_index_for_rpc(&config, gmail.id.clone())
- .await
- .expect("entity index")
- .value;
- assert_eq!(indexed[0].entity_id, "email:[email protected]");
- let chunk_ids = memory_read_rpc::chunks_for_entity_rpc(&config, "email:[email protected]".into())
- .await
- .expect("chunks for entity")
- .value;
- assert_eq!(chunk_ids, vec![gmail.id.clone()]);
- let top_entities = memory_read_rpc::top_entities_rpc(&config, Some("email".into()), 3)
- .await
- .expect("top entities")
- .value;
- assert_eq!(top_entities[0].surface, "[email protected]");
-
- let breakdown = memory_read_rpc::chunk_score_rpc(&config, gmail.id.clone())
- .await
- .expect("chunk score")
- .value
- .expect("score breakdown");
- assert!(breakdown.kept);
- assert!(!breakdown.llm_consulted);
- assert!(!breakdown
- .signals
- .iter()
- .any(|signal| signal.name == "llm_importance" && signal.weight == 2.0));
- assert!(memory_read_rpc::chunk_score_rpc(&config, "missing".into())
- .await
- .expect("missing chunk score")
- .value
- .is_none());
-
- let missing_delete = memory_read_rpc::delete_chunk_rpc(&config, "missing".into())
- .await
- .expect("delete missing")
- .value;
- assert!(!missing_delete.deleted);
- let deleted = memory_read_rpc::delete_chunk_rpc(&config, gmail.id.clone())
- .await
- .expect("delete chunk")
- .value;
- assert!(deleted.deleted);
- assert_eq!(deleted.score_rows_removed, 1);
- assert_eq!(deleted.entity_index_rows_removed, 1);
- assert_eq!(score_store::count_scores(&config).unwrap(), 0);
- assert_eq!(score_store::count_entity_index(&config).unwrap(), 0);
-
- let summary_input = SummaryInput {
- id: "input-1".into(),
- content: " The team shipped deterministic coverage tests. ".into(),
- token_count: 12,
- entities: vec!["email:[email protected]".into()],
- topics: vec!["coverage".into()],
- time_range_start: now,
- time_range_end: now,
- score: 0.9,
- };
- let fallback = fallback_summary(&[summary_input.clone()], 4);
- assert!(fallback.content.starts_with("— The"));
- assert!(fallback.token_count <= 4);
- assert!(fallback.entities.is_empty());
- let empty_ctx = SummaryContext {
- tree_id: "tree-empty",
- tree_kind: TreeKind::Global,
- target_level: 1,
- token_budget: 100,
- input_token_budget: tinycortex::memory::config::INPUT_TOKEN_BUDGET,
- overhead_reserve_tokens: tinycortex::memory::config::SUMMARY_OVERHEAD_RESERVE_TOKENS,
- ask: None,
- };
- let empty =
- tinymemory_core::tree::summarise::summarise(&config, &[], &empty_ctx)
- .await
- .expect("empty summarise avoids provider");
- assert_eq!(empty.token_count, 0);
-
- let embedder =
- tinymemory_core::tree::score::embed::factory::build_embedder_from_config(
- &config,
- )
- .expect("inert embedder");
- assert_eq!(embedder.name(), "inert");
-}
-
-#[test]
-fn memory_retrieval_embedding_and_rpc_model_helpers_round_trip() {
- assert_eq!(retrieval::types::NodeKind::Leaf.as_str(), "leaf");
- assert_eq!(retrieval::types::NodeKind::Summary.as_str(), "summary");
- assert!(retrieval::types::QueryResponse::empty().hits.is_empty());
-
- let now = Utc.with_ymd_and_hms(2026, 5, 29, 12, 0, 0).unwrap();
- let summary = SummaryNode {
- id: "sum-1".into(),
- tree_id: "tree-1".into(),
- tree_kind: TreeKind::Topic,
- level: 2,
- parent_id: Some("root".into()),
- child_ids: vec!["child-1".into(), "child-2".into()],
- content: "Topic summary".into(),
- token_count: 3,
- entities: vec!["person:alice".into()],
- topics: vec!["coverage".into()],
- time_range_start: now,
- time_range_end: now,
- score: 0.8,
- sealed_at: now,
- deleted: false,
- embedding: None,
- doc_id: None,
- version_ms: None,
- };
- let tree = Tree {
- id: "tree-1".into(),
- kind: TreeKind::Topic,
- scope: "topic:coverage".into(),
- ask: None,
- root_id: Some("sum-1".into()),
- max_level: 2,
- status: StoredTreeStatus::Active,
- created_at: now,
- last_sealed_at: Some(now),
- };
- let summary_hit = retrieval::types::hit_from_summary_with_tree(&summary, &tree);
- assert_eq!(summary_hit.node_kind, retrieval::types::NodeKind::Summary);
- assert_eq!(summary_hit.tree_scope, "topic:coverage");
- assert_eq!(summary_hit.child_ids, vec!["child-1", "child-2"]);
-
- let mut leaf_chunk = chunk("gmail:acct:msg-1", 0, now.timestamp_millis());
- leaf_chunk.metadata.source_ref = Some(SourceRef::new("<[email protected]>"));
- let leaf_hit = retrieval::types::hit_from_chunk(&leaf_chunk, "tree-2", "gmail:acct", 0.4);
- assert_eq!(leaf_hit.node_kind, retrieval::types::NodeKind::Leaf);
- assert_eq!(leaf_hit.tree_kind, TreeKind::Source);
- assert_eq!(leaf_hit.source_ref.as_deref(), Some("<[email protected]>"));
- let response = retrieval::types::QueryResponse::new(vec![leaf_hit], 2);
- assert!(response.truncated);
- assert_eq!(
- retrieval::types::leaf_tree_placeholder(ChunkSourceKind::Email),
- TreeKind::Source
- );
-
- assert_eq!(
- TreeKind::parse(TreeKind::Global.as_str()).unwrap(),
- TreeKind::Global
- );
- assert!(TreeKind::parse("missing").is_err());
- assert_eq!(
- StoredTreeStatus::parse(StoredTreeStatus::Archived.as_str()).unwrap(),
- StoredTreeStatus::Archived
- );
- assert!(StoredTreeStatus::parse("missing").is_err());
-
- let packed = embed::pack_checked(&vec![0.25; embed::EMBEDDING_DIM]).expect("pack checked");
- let unpacked = embed::unpack_embedding(&packed).expect("unpack");
- assert_eq!(unpacked.len(), embed::EMBEDDING_DIM);
- assert!(embed::pack_checked(&[1.0, 2.0]).is_err());
- assert!(embed::unpack_embedding(&[0, 1, 2]).is_err());
- assert!(embed::decode_optional_blob(None, "none").unwrap().is_none());
- assert!(embed::decode_optional_blob(Some(vec![0; 16]), "bad row").is_err());
- assert_eq!(embed::cosine_similarity(&[1.0, 0.0], &[0.0, 1.0]), 0.0);
- assert_eq!(embed::InertEmbedder::new().name(), "inert");
-
- let query = QueryNamespaceRequest {
- namespace: "default".into(),
- query: "coverage".into(),
- include_references: Some(true),
- document_ids: Some(vec!["doc-1".into()]),
- limit: Some(4),
- max_chunks: Some(6),
- };
- assert_eq!(query.resolved_limit(), 6);
- let recall_context = RecallContextRequest {
- namespace: "default".into(),
- include_references: None,
- limit: Some(3),
- max_chunks: None,
- };
- assert_eq!(recall_context.resolved_limit(), 3);
- let recall_memories = RecallMemoriesRequest {
- namespace: "default".into(),
- min_retention: Some(0.2),
- as_of: Some(1.0),
- limit: Some(3),
- max_chunks: Some(7),
- top_k: Some(9),
- };
- assert_eq!(recall_memories.resolved_limit(), 9);
-
- let envelope = ApiEnvelope {
- data: Some(json!({ "ok": true })),
- error: Some(ApiError {
- code: "coverage".into(),
- message: "covered".into(),
- details: Some(json!({ "line": true })),
- }),
- meta: ApiMeta {
- request_id: "req-1".into(),
- latency_seconds: Some(0.01),
- cached: Some(false),
- counts: None,
- pagination: Some(PaginationMeta {
- limit: 10,
- offset: 0,
- count: 1,
- }),
- },
- };
- let encoded = serde_json::to_value(envelope).expect("api envelope json");
- assert_eq!(encoded["meta"]["pagination"]["count"], 1);
-
- let entry = MemoryEntry {
- id: "mem-1".into(),
- key: "preference".into(),
- content: "Use deterministic tests".into(),
- namespace: Some("default".into()),
- category: MemoryCategory::Custom("testing".into()),
- timestamp: now.to_rfc3339(),
- session_id: Some("session-1".into()),
- score: Some(0.9),
- taint: Default::default(),
- };
- assert_eq!(entry.category.to_string(), "custom:testing");
- let opts = RecallOpts {
- namespace: Some("default"),
- category: Some(MemoryCategory::Conversation),
- session_id: Some("session-2"),
- min_score: Some(0.5),
- // Self-echo exclusion is a separate concern from this coverage test's
- // namespace/category/session assertions below; `None` means "exclude
- // nothing", matching this literal's pre-existing behavior before the
- // field was added.
- exclude_session_id: None,
- cross_session: true,
- };
- assert!(opts.cross_session);
- assert_eq!(opts.category.unwrap().to_string(), "conversation");
- let summary = NamespaceSummary {
- namespace: "default".into(),
- count: 1,
- last_updated: Some(now.to_rfc3339()),
- };
- assert_eq!(serde_json::to_value(summary).unwrap()["count"], 1);
-}
-
-#[tokio::test]
-async fn memory_preferences_remember_redaction_and_pipeline_traits_cover_public_edges() {
- // The preference readers take a `MemoryGuard` since the module port: they
- // are host policy over a driver, not engine calls. `guarded_in_memory`
- // gives a real guard over a real store, so this still exercises the
- // decorator production uses rather than reaching past it.
- let (_provider, memory) =
- openhuman_core::openhuman::memory::guard::in_memory::guarded_in_memory();
-
- memory
- .store(
- USER_PREF_GENERAL_NAMESPACE,
- "tone",
- "Prefer concise responses.",
- openhuman_core::openhuman::memory::api::types::MemoryCategory::Core,
- None,
- MemoryTaint::Internal,
- )
- .await
- .expect("store general preference");
- memory
- .store(
- USER_PREF_GENERAL_NAMESPACE,
- "empty",
- " ",
- openhuman_core::openhuman::memory::api::types::MemoryCategory::Core,
- None,
- MemoryTaint::Internal,
- )
- .await
- .expect("store empty general preference");
- memory
- .store(
- USER_PREF_SITUATIONAL_NAMESPACE,
- "rust-tests",
- "When changing Rust code, run targeted tests first.",
- openhuman_core::openhuman::memory::api::types::MemoryCategory::Core,
- None,
- MemoryTaint::Internal,
- )
- .await
- .expect("store situational preference");
-
- let general = load_general_preferences(&memory, 10).await;
- assert_eq!(general, vec!["Prefer concise responses."]);
- assert!(load_general_preferences(&memory, 0).await.is_empty());
- assert!(recall_situational_preferences(&memory, " ")
- .await
- .is_empty());
- assert!(recall_related_preferences(&memory, " ", "tone", 3)
- .await
- .is_empty());
- assert!(
- recall_related_preferences(&memory, "Prefer concise responses.", "tone", 0)
- .await
- .is_empty()
- );
-
- for (kind, label) in [
- (RememberSourceKind::ChatHistory, "chat_history"),
- (RememberSourceKind::UploadedData, "uploaded_data"),
- (RememberSourceKind::LlmThought, "llm_thought"),
- ] {
- assert_eq!(kind.as_str(), label);
- assert_eq!(serde_json::to_value(kind).unwrap(), json!(label));
- }
-
- assert_eq!(redact("[email protected]").len(), 8);
- assert_eq!(
- redact_endpoint("https://user:p@[email protected]:8443/[email protected]#frag"),
- "example.com:8443"
- );
- assert_eq!(
- redact_endpoint("localhost:11434/api/chat"),
- "localhost:11434"
- );
-
- let outcome = PipelineSyncOutcome {
- records_ingested: 2,
- more_pending: false,
- note: Some("covered".into()),
- ..PipelineSyncOutcome::default()
- };
- assert_eq!(outcome.records_ingested, 2);
- assert_eq!(serde_json::to_value(outcome).unwrap()["note"], "covered");
- assert_eq!(PipelineSyncOutcome::default().records_ingested, 0);
- assert_eq!(SyncPipelineKind::Composio.as_str(), "composio");
- assert_eq!(SyncPipelineKind::Mcp.as_str(), "mcp");
-}
-
-#[tokio::test]
-async fn memory_tools_and_user_scope_prefs_cover_public_execution_paths() {
- let tmp = TempDir::new().expect("tempdir");
- let security = Arc::new(SecurityPolicy {
- autonomy: AutonomyLevel::Full,
- ..SecurityPolicy::default()
- });
-
- let store_tool = MemoryStoreTool::new(security.clone());
- assert_eq!(store_tool.name(), "memory_store");
- assert!(store_tool.parameters_schema()["required"]
- .as_array()
- .unwrap()
- .iter()
- .any(|field| field == "content"));
- let stored = store_tool
- .execute(json!({
- "namespace": "coverage-tools",
- "key": "rust",
- "content": "Use deterministic memory coverage tests",
- "category": "daily"
- }))
- .await
- .expect("store tool");
- assert!(!stored.is_error);
- assert!(stored.output().contains("coverage-tools/rust"));
-
- let custom = store_tool
- .execute(json!({
- "namespace": "coverage-tools",
- "key": "custom",
- "content": "Custom categories survive tool writes",
- "category": "testing"
- }))
- .await
- .expect("store custom category");
- assert!(!custom.is_error);
- assert!(
- store_tool
- .execute(json!({
- "namespace": " ",
- "key": "blank",
- "content": "not written"
- }))
- .await
- .expect("blank namespace")
- .is_error
- );
- assert!(
- store_tool
- .execute(json!({
- "namespace": "coverage-tools",
- "key": "secret",
- "content": "OPENAI_API_KEY=sk-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- }))
- .await
- .expect("secret rejected")
- .is_error
- );
-
- let recall_tool = MemoryRecallTool::new();
- assert_eq!(recall_tool.name(), "memory_recall");
- let recalled = recall_tool
- .execute(json!({
- "namespace": "coverage-tools",
- "query": "deterministic",
- "limit": 3
- }))
- .await
- .expect("recall tool");
- assert!(!recalled.is_error);
- assert!(recalled.output().contains("rust"));
- assert!(recall_tool
- .execute(json!({ "namespace": "coverage-tools", "query": " " }))
- .await
- .unwrap_err()
- .to_string()
- .contains("query cannot be empty"));
-
- let forget_tool = MemoryForgetTool::new(security);
- assert_eq!(forget_tool.name(), "memory_forget");
- let missing = forget_tool
- .execute(json!({
- "namespace": "coverage-tools",
- "key": "missing"
- }))
- .await
- .expect("forget missing");
- assert!(!missing.is_error);
- assert!(missing.output().contains("No memory found"));
- let forgot = forget_tool
- .execute(json!({
- "namespace": "coverage-tools",
- "key": "rust"
- }))
- .await
- .expect("forget existing");
- assert!(!forgot.is_error);
- assert!(forgot.output().contains("Forgot memory"));
-
- // The engine's `tinymemory_core::sync::composio::providers::user_scopes`
- // module this used to drive (`load`/`save`/`load_or_default` against a
- // `&MemoryClientRef`) is deleted with the rest of the in-process
- // Composio pipeline — confirmed by an exhaustive grep of
- // vendor/tinymemory, nothing under that name survives anywhere. Its
- // host-side replacement, `integrations::composio::ops::user_scopes`, is
- // real but `pub(crate)` (reached only via the `composio.get_user_scopes`
- // / `composio.set_user_scopes` JSON-RPC handlers, which this file does
- // not run a server for) and so is not reachable from an integration
- // test in this crate. Genuine, unrecoverable coverage gap — reported
- // rather than silently dropped. `UserScopePref` itself (the pure type)
- // is still exercised elsewhere in this file via
- // `memory_sync_composio_catalog_scope_and_state_helpers_cover_edge_cases`.
-}
-
-#[tokio::test]
-async fn memory_queue_and_tool_memory_public_stores_cover_persistence_edges() {
- let tmp = TempDir::new().expect("tempdir");
- let config = config_in(&tmp);
-
- memory_queue::set_backfill_in_progress(false);
- assert!(!memory_queue::backfill_in_progress());
- memory_queue::set_backfill_in_progress(true);
- assert!(memory_queue::backfill_in_progress());
- memory_queue::set_backfill_in_progress(false);
-
- for kind in [
- JobKind::ExtractChunk,
- JobKind::AppendBuffer,
- JobKind::Seal,
- JobKind::FlushStale,
- JobKind::ReembedBackfill,
- ] {
- assert_eq!(JobKind::parse(kind.as_str()).unwrap(), kind);
- }
- assert!(JobKind::parse("missing").is_err());
- assert!(JobKind::Seal.is_llm_bound());
- assert!(!JobKind::AppendBuffer.is_llm_bound());
- assert!(JobStatus::parse("cancelled").unwrap().is_terminal());
- assert!(JobStatus::parse("missing").is_err());
-
- let leaf = NodeRef::Leaf {
- chunk_id: "chunk-tool-memory".into(),
- };
- let summary = NodeRef::Summary {
- summary_id: "summary-tool-memory".into(),
- };
- assert_eq!(leaf.dedupe_fragment(), "leaf:chunk-tool-memory");
- assert_eq!(summary.dedupe_fragment(), "summary:summary-tool-memory");
-
- let extract = ExtractChunkPayload {
- chunk_id: "chunk-tool-memory".into(),
- };
- let source_append = AppendBufferPayload {
- node: leaf.clone(),
- target: AppendTarget::Source {
- source_id: "slack:#raw".into(),
- },
- };
- let topic_append = AppendBufferPayload {
- node: summary.clone(),
- target: AppendTarget::Topic {
- tree_id: "topic:raw".into(),
- },
- };
- assert_eq!(extract.dedupe_key(), "extract:chunk-tool-memory");
- assert!(source_append
- .dedupe_key()
- .contains("append:source:slack:#raw:leaf:chunk-tool-memory"));
- assert!(topic_append
- .dedupe_key()
- .contains("append:topic:topic:raw:summary:summary-tool-memory"));
- assert_eq!(
- SealPayload {
- tree_id: "tree-1".into(),
- level: 2,
- force_now_ms: Some(1),
- }
- .dedupe_key(),
- "seal:tree-1:2"
- );
- assert_eq!(
- FlushStalePayload {
- max_age_secs: Some(60)
- }
- .dedupe_key("2026-05-29", 4),
- "flush_stale:2026-05-29-h4"
- );
- assert_eq!(
- ReembedBackfillPayload {
- signature: "sig:v1".into()
- }
- .dedupe_key(),
- "reembed_backfill:sig:v1"
- );
-
- let first_job = NewJob::append_buffer(&source_append).expect("append job");
- let first_id = memory_queue::enqueue(&config, &first_job)
- .expect("enqueue")
- .expect("inserted");
- assert!(memory_queue::enqueue(&config, &first_job)
- .expect("dedupe enqueue")
- .is_none());
- assert_eq!(memory_queue::count_total(&config).unwrap(), 1);
- assert_eq!(
- memory_queue::count_by_status(&config, JobStatus::Ready).unwrap(),
- 1
- );
- let claimed = memory_queue::claim_next(&config, DEFAULT_LOCK_DURATION_MS)
- .expect("claim")
- .expect("claimed");
- assert_eq!(claimed.id, first_id);
- assert_eq!(claimed.status, JobStatus::Running);
- assert_eq!(claimed.attempts, 1);
- let wake_at = Utc::now().timestamp_millis() - 1;
- memory_queue::mark_deferred(&config, &claimed, wake_at, "retry later with token=secret")
- .expect("defer");
- let deferred = memory_queue::get_job(&config, &first_id)
- .expect("get deferred")
- .expect("deferred row");
- assert_eq!(deferred.status, JobStatus::Ready);
- assert_eq!(deferred.attempts, 0);
- assert_eq!(
- deferred.last_error.as_deref(),
- Some("retry later with token=secret")
- );
- let retry_claim = memory_queue::claim_next(&config, DEFAULT_LOCK_DURATION_MS)
- .expect("claim retry")
- .expect("retry claimed");
- memory_queue::mark_done(&config, &retry_claim).expect("done");
- assert_eq!(
- memory_queue::get_job(&config, &first_id)
- .unwrap()
- .unwrap()
- .status,
- JobStatus::Done
- );
-
- let mut failing_job = NewJob::extract_chunk(&extract).expect("extract job");
- failing_job.max_attempts = Some(1);
- let failed_id = memory_queue::enqueue(&config, &failing_job)
- .expect("enqueue failing")
- .expect("failing inserted");
- let failed_claim = memory_queue::claim_next(&config, DEFAULT_LOCK_DURATION_MS)
- .expect("claim failing")
- .expect("failing claimed");
- memory_queue::mark_failed(&config, &failed_claim, "fatal Bearer abc.def").expect("mark failed");
- let failed = memory_queue::get_job(&config, &failed_id)
- .expect("get failed")
- .expect("failed row");
- assert_eq!(failed.status, JobStatus::Failed);
- assert_eq!(failed.last_error.as_deref(), Some("fatal Bearer abc.def"));
- assert_eq!(
- memory_queue::recover_stale_locks(&config).expect("recover"),
- 0
- );
-
- let tool_memory_dir = tmp.path().join("tool-memory");
- let memory: Arc<dyn Memory> = Arc::new(
- UnifiedMemory::new(&tool_memory_dir, Arc::new(NoopEmbedding), None)
- .expect("tool memory backend"),
- );
- let store = tool_memory_store(memory.clone());
- assert_eq!(tool_memory_namespace(" Shell "), "tool-shell");
- assert!(ToolMemoryPriority::Critical.is_eager());
- assert!(ToolMemoryPriority::High.is_eager());
- assert!(!ToolMemoryPriority::Normal.is_eager());
- assert_eq!(ToolMemorySource::default(), ToolMemorySource::Programmatic);
- assert!(store
- .record(
- " ",
- "blank tool rejected",
- ToolMemoryPriority::High,
- ToolMemorySource::UserExplicit,
- Vec::new(),
- )
- .await
- .unwrap_err()
- .contains("tool_name"));
- assert!(store
- .record(
- "shell",
- " ",
- ToolMemoryPriority::High,
- ToolMemorySource::UserExplicit,
- Vec::new(),
- )
- .await
- .unwrap_err()
- .contains("rule body"));
-
- let critical = store
- .record(
- "shell",
- "Never run destructive commands without confirmation.",
- ToolMemoryPriority::Critical,
- ToolMemorySource::UserExplicit,
- vec!["safety".into()],
- )
- .await
- .expect("record critical");
- let high = store
- .record(
- "web_search",
- "Prefer primary sources.",
- ToolMemoryPriority::High,
- ToolMemorySource::PostTurn,
- Vec::new(),
- )
- .await
- .expect("record high");
- let normal = store
- .record(
- "shell",
- "Use rg before slower search commands.",
- ToolMemoryPriority::Normal,
- ToolMemorySource::Programmatic,
- Vec::new(),
- )
- .await
- .expect("record normal");
- assert_eq!(
- store
- .get_rule("shell", &critical.id)
- .await
- .expect("get critical")
- .unwrap()
- .created_at,
- critical.created_at
- );
- let mut updated = critical.clone();
- updated.rule = "Never run destructive commands without explicit confirmation.".into();
- let updated = store.put_rule(updated).await.expect("update critical");
- assert_eq!(updated.created_at, critical.created_at);
- assert_ne!(updated.updated_at, "");
-
- let listed = store.list_rules("shell").await.expect("list shell");
- assert_eq!(listed[0].priority, ToolMemoryPriority::Critical);
- assert!(listed.iter().any(|rule| rule.id == normal.id));
- let listed_json = store
- .list_rules_json("shell")
- .await
- .expect("list rules json");
- assert!(listed_json.as_array().unwrap().len() >= 2);
- let tool_names = store.list_tool_names().await.expect("list tool names");
- assert!(tool_names.contains(&"shell".to_string()));
- assert!(tool_names.contains(&"web_search".to_string()));
- let prompt_rules = store
- .rules_for_prompt(&[])
- .await
- .expect("prompt rules from namespaces");
- assert!(prompt_rules["shell"]
- .iter()
- .all(|rule| rule.priority.is_eager()));
- assert_eq!(TOOL_MEMORY_PROMPT_CAP, 30);
- let render_rules: Vec<ApiToolMemoryRule> = [normal.clone(), updated.clone(), high.clone()]
- .into_iter()
- .map(|rule| {
- serde_json::from_value(serde_json::to_value(rule).expect("serialize tool rule"))
- .expect("convert tool rule to host API")
- })
- .collect();
- let rendered = render_tool_memory_rules(&render_rules);
- assert!(rendered.starts_with(TOOL_MEMORY_HEADING));
- assert!(rendered.find("**[critical]**") < rendered.find("**[high]**"));
- assert!(rendered.contains("### `shell`"));
- assert!(ToolMemoryRulesSection::empty().is_empty());
- assert!(!ToolMemoryRulesSection::new(vec![updated.clone()]).is_empty());
- assert!(store
- .delete_rule("shell", &normal.id)
- .await
- .expect("delete normal"));
- assert!(!store
- .delete_rule("shell", &normal.id)
- .await
- .expect("delete missing"));
- assert!(store
- .get_rule("shell", &normal.id)
- .await
- .expect("missing normal")
- .is_none());
-
- let put_tool = MemoryToolsPutTool;
- assert_eq!(put_tool.name(), "memory_tools_put");
- assert_eq!(put_tool.category(), ToolCategory::System);
- assert!(put_tool.parameters_schema()["required"]
- .as_array()
- .unwrap()
- .iter()
- .any(|field| field == "rule"));
- assert!(put_tool
- .execute(json!({ "tool_name": "shell" }))
- .await
- .unwrap_err()
- .to_string()
- .contains("invalid arguments for memory_tools_put"));
- let list_tool = MemoryToolsListTool;
- assert_eq!(list_tool.name(), "memory_tools_list");
- assert_eq!(list_tool.permission_level(), PermissionLevel::ReadOnly);
- assert!(list_tool
- .execute(json!({}))
- .await
- .unwrap_err()
- .to_string()
- .contains("invalid arguments for memory_tools_list"));
- assert_eq!(
- ToolMemoryRule::storage_key(&updated.id),
- format!("rule/{}", updated.id)
- );
-}
-
-#[tokio::test]
-async fn memory_source_sync_entrypoint_rejects_disabled_and_ingests_folder_items() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _env_workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", module_workspace());
- let mut config = config_in(&tmp);
- use_module_workspace(&mut config);
- wipe_shared_store(&config);
- // Folder kinds run in-process through `run_source_pipeline_core`, which
- // takes its memory client from the process global; bind that to the shared
- // workspace too, or the rows land wherever an earlier case left it.
- tinymemory_core::global::init(config.workspace_dir.clone()).expect("bind global memory client");
- std::fs::write(
- tmp.path().join("sync-note.md"),
- "# Sync note\n\nAlice documents deterministic source sync coverage.",
- )
- .expect("write sync note");
-
- let mut disabled = source(SourceKind::Folder, "src_disabled");
- disabled.path = Some(tmp.path().to_string_lossy().to_string());
- disabled.enabled = false;
- let disabled_entry = disabled.clone();
- tinymemory_core::sources::registry::replace_sources_in(&config, &[disabled_entry.clone()])
- .expect("register the disabled source the driver will look up");
- assert!(sync_source(disabled, Arc::new(config.clone()))
- .await
- .unwrap_err()
- .contains("disabled"));
-
- let mut folder = source(SourceKind::Folder, "src_sync");
- folder.path = Some(tmp.path().to_string_lossy().to_string());
- folder.glob = Some("sync-note.md".into());
- // The sync runs inside the bound driver, which resolves the source by id
- // from the shared registry rather than from the entry handed in here.
- tinymemory_core::sources::registry::replace_sources_in(
- &config,
- &[disabled_entry, folder.clone()],
- )
- .expect("register the sources the driver will look up");
- sync_source(folder, Arc::new(config.clone()))
- .await
- .expect("queue folder sync");
-
- let composite_source_id = "mem_src:src_sync:sync-note.md";
- let mut synced_rows = 0_i64;
- for _ in 0..40 {
- synced_rows = with_connection(&config, |conn| {
- Ok(conn.query_row(
- "SELECT COUNT(*) FROM mem_tree_chunks WHERE source_id = ?1",
- [composite_source_id],
- |row| row.get::<_, i64>(0),
- )?)
- })
- .expect("count synced chunks");
- if synced_rows > 0 {
- break;
- }
- tokio::time::sleep(std::time::Duration::from_millis(50)).await;
- }
- let seen: Vec<String> = with_connection(&config, |conn| {
- let mut stmt = conn.prepare("SELECT DISTINCT source_id FROM mem_tree_chunks")?;
- let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
- Ok(rows.collect::<Result<Vec<_>, _>>()?)
- })
- .expect("list source ids");
- assert!(
- synced_rows > 0,
- "folder sync should ingest at least one chunk; store holds source_ids={seen:?}"
- );
-
- let mut twitter = source(SourceKind::TwitterQuery, "src_twitter_sync");
- twitter.query = Some("openhuman".into());
- sync_source(twitter, Arc::new(config))
- .await
- .expect("twitter placeholder queues and reports failure asynchronously");
- tokio::time::sleep(std::time::Duration::from_millis(50)).await;
-}
-
-#[test]
-fn memory_tree_io_contract_types_round_trip_leaf_read_and_write_shapes() {
- let now = Utc.with_ymd_and_hms(2026, 5, 29, 16, 0, 0).unwrap();
- let payload = tinycortex::memory::tree::TreeLeafPayload {
- chunk_id: "chunk-contract-1".into(),
- token_count: 42,
- timestamp: now,
- content: "Leaf content for a canonical write request".into(),
- entities: vec!["person:alice".into(), "email:[email protected]".into()],
- topics: vec!["coverage".into()],
- score: 0.77,
- };
- let leaf_ref = LeafRef::from(&payload);
- assert_eq!(leaf_ref.chunk_id, payload.chunk_id);
- assert_eq!(leaf_ref.entities, payload.entities);
- let round_trip =
- tinycortex::memory::tree::TreeLeafPayload::from(leaf_ref.clone());
- assert_eq!(round_trip.content, payload.content);
- assert_eq!(round_trip.score, payload.score);
-
- let write_default_json =
- serde_json::to_value(tinycortex::memory::tree::TreeWriteRequest {
- tree_id: "tree-contract".into(),
- tree_kind: TreeKind::Source,
- leaf: round_trip.clone(),
- label_strategy: Default::default(),
- deferred: false,
- })
- .expect("write request json");
- assert_eq!(write_default_json["label_strategy"], "inherit");
- assert_eq!(write_default_json["deferred"], false);
-
- let decoded_write: tinycortex::memory::tree::TreeWriteRequest =
- serde_json::from_value(json!({
- "tree_id": "tree-contract",
- "tree_kind": "global",
- "leaf": {
- "chunk_id": "chunk-contract-2",
- "token_count": 5,
- "timestamp": now,
- "content": "minimal leaf"
- },
- "label_strategy": "empty",
- "deferred": true
- }))
- .expect("decode write request");
- assert_eq!(decoded_write.tree_kind, TreeKind::Global);
- assert_eq!(
- decoded_write.label_strategy,
- tinycortex::memory::tree::TreeLabelStrategy::Empty
- );
- assert!(decoded_write.leaf.entities.is_empty());
- assert!(decoded_write.deferred);
-
- let outcome = tinycortex::memory::tree::TreeWriteOutcome {
- new_summary_ids: vec!["summary-1".into()],
- seal_pending: true,
- };
- let outcome_json = serde_json::to_value(outcome).expect("outcome json");
- assert_eq!(outcome_json["new_summary_ids"][0], "summary-1");
- assert_eq!(outcome_json["seal_pending"], true);
-
- let read_request: tinycortex::memory::tree::TreeReadRequest =
- serde_json::from_value(json!({
- "tree_id": "tree-contract",
- "max_depth": 2,
- "query": "coverage",
- "limit": 3
- }))
- .expect("decode read request defaults");
- assert_eq!(read_request.start_node_id, None);
- assert_eq!(read_request.max_depth, 2);
- assert_eq!(read_request.limit, Some(3));
-
- let hit = tinycortex::memory::tree::TreeReadHit {
- node_id: "summary-1".into(),
- node_kind: "summary".into(),
- level: 1,
- content: "Summary text".into(),
- score: 0.42,
- };
- let result = tinycortex::memory::tree::TreeReadResult {
- hits: vec![hit],
- total: 4,
- tree_id: "tree-contract".into(),
- };
- let result_json = serde_json::to_value(result).expect("read result json");
- assert_eq!(result_json["hits"][0]["node_kind"], "summary");
- assert_eq!(result_json["total"], 4);
-
- let tree = Tree {
- id: "empty-tree".into(),
- kind: TreeKind::Source,
- scope: "source:contract".into(),
- ask: None,
- root_id: None,
- max_level: 0,
- status: StoredTreeStatus::Active,
- created_at: now,
- last_sealed_at: None,
- };
- let empty = tinycortex::memory::tree::TreeReadResult::empty(&tree);
- assert_eq!(empty.tree_id, "empty-tree");
- assert!(empty.hits.is_empty());
-}
-
-// The deleted engine's per-toolkit `is_self_identity(prefix, kind, value)`
-// has no replacement anywhere in `tinymemory-core` (confirmed by exhaustive
-// grep) — only the cross-toolkit `is_self_identity_any_toolkit` survived, and
-// it takes tinymemory-core's own `IdentityKind`, a distinct (structurally
-// identical) type from the contract crate's `IdentityKind` this test uses
-// everywhere else. Bridged here by name rather than imported directly at the
-// top of the file, so the two enums are never confused at a call site.
-fn to_core_identity_kind(kind: IdentityKind) -> tinymemory_core::store::identity::IdentityKind {
- tinymemory_core::store::identity::IdentityKind::parse(kind.as_str())
- .expect("every contract IdentityKind variant name parses on the core side too")
-}
-
-#[tokio::test]
-async fn memory_sync_profile_identity_helpers_cover_public_no_client_paths_and_rendering() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _env_workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", module_workspace());
- let mut config = config_in(&tmp);
- use_module_workspace(&mut config);
- wipe_shared_store(&config);
- tinymemory_core::global::init(config.workspace_dir.clone()).expect("bind global memory client");
-
- assert_eq!(IdentityKind::parse("email"), Some(IdentityKind::Email));
- assert_eq!(IdentityKind::parse("missing"), None);
- assert!(IdentityKind::Email.is_matchable());
- assert!(!IdentityKind::AvatarUrl.is_matchable());
- assert!(IdentityKind::UserId.confidence() > IdentityKind::DisplayName.confidence());
-
- assert_eq!(
- canonicalize(IdentityKind::Email, " [email protected] "),
- Some("[email protected]".into())
- );
- assert_eq!(
- canonicalize(IdentityKind::Handle, " @Alice "),
- Some("alice".into())
- );
- assert_eq!(
- canonicalize(IdentityKind::Phone, " +1 (555) 123-4567 "),
- Some("+15551234567".into())
- );
- assert_eq!(
- canonicalize(IdentityKind::DisplayName, " Alice\n Example "),
- Some("Alice Example".into())
- );
- assert_eq!(canonicalize(IdentityKind::Email, " "), None);
-
- assert!(load_connected_identities(&config)
- .await
- .expect("load connected identities")
- .is_empty());
- // `is_self_identity("gmail", ...)` (per-toolkit) is the genuine gap noted
- // above — no assertion here replaces it. `is_self_identity_any_toolkit`
- // survives and is exercised with nothing persisted yet, same as before.
- assert!(!is_self_identity_any_toolkit(
- to_core_identity_kind(IdentityKind::Email),
- ));
- assert_eq!(
- delete_connected_identity_facets(&config, "gmail", "conn-1")
- .await
- .expect("delete connected identity facets"),
- 0
- );
-
- let rendered = render_connected_identities_section(&[
- ConnectedIdentity {
- source: "gmail".into(),
- identifier: "conn:1".into(),
- display_name: Some("Alice\nExample".into()),
- email: Some("[email protected]".into()),
- handle: None,
- phone: None,
- user_id: Some("U123".into()),
- avatar_url: None,
- profile_url: Some("https://example.test/alice|profile".into()),
- },
- ConnectedIdentity {
- source: "slack".into(),
- identifier: "workspace".into(),
- display_name: None,
- email: None,
- handle: Some("alice".into()),
- phone: None,
- user_id: None,
- avatar_url: None,
- profile_url: None,
- },
- ]);
- assert!(rendered.starts_with("## Connected Identities"));
- assert!(rendered.contains("Gmail (conn:1): Alice Example | [email protected]"));
- assert!(rendered.contains("Slack (workspace): @alice"));
- assert!(!rendered.contains("U123"));
- assert_eq!(
- render_connected_identities_section(&[ConnectedIdentity {
- source: "empty".into(),
- identifier: "id".into(),
- ..Default::default()
- }]),
- ""
- );
-}
-
-/// The deleted engine's `ComposioProvider` trait, its per-toolkit structs
-/// (`GmailProvider` among them), `ProviderContext`, and the whole in-process
-/// registry (`register_provider`/`get_provider`/`all_providers`/
-/// `init_default_providers`) are genuinely gone with nothing in this crate to
-/// exercise them against — see
-/// `crate::openhuman::integrations::composio::providers`'s module docs and
-/// `memory_sync_providers_raw_coverage_e2e.rs`, which documents this same gap
-/// in detail for the sibling suite that covered these types most directly.
-///
-/// This test used to cover two things through that registry:
-/// Gmail's `post_process_action_result` (nested-payload flattening, raw-HTML
-/// opt-out, non-container passthrough) and the registry's own CRUD
-/// (register/get/list, empty-slug and duplicate-slug handling) plus the
-/// `ComposioProvider` trait's default method bodies (`sync_interval_secs`,
-/// `curated_tools`, `fetch_tasks`'s "no task-fetch surface" default,
-/// `on_trigger`'s no-op default, `identity_set`, `on_connection_created`
-/// writing `PROFILE.md`). None of it moved anywhere reachable from this
-/// crate — it now lives entirely inside the separately-versioned
-/// `tinyconnectors` module, reachable only via a live loaded module (real
-/// network + `dlopen`), which this suite's local-only design rules out. What
-/// remains honestly testable of "fetch a provider's profile" / "sync a
-/// connection" is `composio_get_user_profile` / `composio_sync`
-/// (`integrations::composio::ops`), which refuse cleanly, deterministically
-/// and without touching the network when no connectors module is loaded.
-#[tokio::test]
-async fn composio_get_user_profile_and_sync_refuse_cleanly_without_a_loaded_module() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let mut config = config_in(&tmp);
- config.modules.enabled = false;
-
- let error = composio_get_user_profile(&config, "conn-raw-coverage")
- .await
- .expect_err("profile fetch must refuse without a loaded connectors module");
- assert!(
- error.contains("modules are disabled in configuration"),
- "unexpected error: {error}"
- );
-
- let outcome = composio_sync(&config, "conn-raw-coverage", None).await;
- assert!(
- outcome.is_err(),
- "sync must refuse to resolve toolkit for an unregistered connection"
- );
-}
-
-#[test]
-fn turn_state_mirror_persists_progress_edges_from_public_events() {
- let tmp = TempDir::new().expect("tempdir");
- let store = TurnStateStore::new(tmp.path().to_path_buf());
- let mut mirror = TurnStateMirror::new(store.clone(), "thread/mirror", "request-mirror");
- assert!(store
- .get("thread/mirror")
- .expect("initial snapshot")
- .is_some());
-
- assert!(mirror.observe(&AgentProgress::TurnStarted));
- assert!(mirror.observe(&AgentProgress::IterationStarted {
- iteration: 2,
- max_iterations: 5,
- }));
- assert!(!mirror.observe(&AgentProgress::ThinkingDelta {
- delta: "thinking ".into(),
- iteration: 2,
- }));
- assert!(!mirror.observe(&AgentProgress::TextDelta {
- delta: "visible".into(),
- iteration: 2,
- }));
- assert!(!mirror.observe(&AgentProgress::ToolCallArgsDelta {
- call_id: "call-1".into(),
- tool_name: "memory.search".into(),
- delta: "{\"q\":\"coverage\"}".into(),
- iteration: 2,
- }));
- assert!(mirror.observe(&AgentProgress::ToolCallStarted {
- call_id: "call-1".into(),
- tool_name: "memory.search".into(),
- arguments: json!({ "q": "coverage" }),
- iteration: 2,
- display_label: None,
- display_detail: None,
- }));
- assert!(mirror.observe(&AgentProgress::ToolCallCompleted {
- call_id: "call-1".into(),
- tool_name: "memory.search".into(),
- success: false,
- output_chars: 0,
- output: String::new(),
- arguments: None,
- elapsed_ms: 11,
- iteration: 2,
- failure: None,
- }));
- assert!(!mirror.observe(&AgentProgress::TurnCostUpdated {
- model: "coverage-model".into(),
- iteration: 2,
- input_tokens: 10,
- output_tokens: 3,
- cached_input_tokens: 2,
- total_usd: 0.001,
- }));
-
- assert!(mirror.observe(&AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "task-1".into(),
- mode: "typed".into(),
- dedicated_thread: true,
- prompt_chars: 99,
- prompt: String::new(),
- worker_thread_id: None,
- display_name: Some("Researcher".into()),
- }));
- assert!(!mirror.observe(&AgentProgress::SubagentIterationStarted {
- agent_id: "researcher".into(),
- task_id: "task-1".into(),
- iteration: 1,
- max_iterations: 3,
- extended_policy: false,
- }));
- // Sub-agent tool boundaries now FLUSH (return `true`): while a sub-agent
- // runs, the parent is blocked on its long-lived `spawn_subagent` tool, so
- // the parent's own iteration/tool flushes don't fire. Flushing on the
- // child's tool start/complete is what lets the sub-agent's streamed thoughts
- // reach disk mid-run (survives tab-switch / reload).
- assert!(mirror.observe(&AgentProgress::SubagentToolCallStarted {
- agent_id: "researcher".into(),
- task_id: "task-1".into(),
- call_id: "child-call".into(),
- tool_name: "memory.read".into(),
- arguments: serde_json::Value::Null,
- iteration: 1,
- display_label: None,
- display_detail: None,
- }));
- assert!(mirror.observe(&AgentProgress::SubagentToolCallCompleted {
- agent_id: "researcher".into(),
- task_id: "task-1".into(),
- call_id: "child-call".into(),
- tool_name: "memory.read".into(),
- success: true,
- output_chars: 44,
- output: "child tool output".into(),
- arguments: None,
- elapsed_ms: 22,
- iteration: 1,
- failure: None,
- }));
- assert!(mirror.observe(&AgentProgress::SubagentFailed {
- agent_id: "researcher".into(),
- task_id: "task-1".into(),
- error: "child failed".into(),
- }));
-
- let board = TaskBoard {
- thread_id: "thread/mirror".into(),
- cards: vec![TaskBoardCard {
- id: "card-1".into(),
- title: "Mirror coverage".into(),
- status: TaskCardStatus::Todo,
- objective: None,
- plan: vec!["exercise public events".into()],
- assigned_agent: None,
- allowed_tools: Vec::new(),
- approval_mode: None,
- acceptance_criteria: Vec::new(),
- evidence: Vec::new(),
- notes: None,
- session_thread_id: None,
- blocker: None,
- source_metadata: None,
- order: 0,
- updated_at: "2026-05-29T16:00:00Z".into(),
- }],
- updated_at: "2026-05-29T16:00:00Z".into(),
- };
- assert!(mirror.observe(&AgentProgress::TaskBoardUpdated {
- board: board.clone()
- }));
-
- let snapshot = store
- .get("thread/mirror")
- .expect("read mirror snapshot")
- .expect("snapshot");
- assert_eq!(snapshot.lifecycle, TurnLifecycle::Streaming);
- assert_eq!(snapshot.phase, Some(TurnPhase::Thinking));
- assert!(snapshot.active_tool.is_none());
- assert!(snapshot.active_subagent.is_none());
- assert_eq!(snapshot.streaming_text, "visible");
- assert_eq!(snapshot.thinking, "thinking ");
- assert_eq!(snapshot.task_board, Some(board));
- assert!(snapshot
- .tool_timeline
- .iter()
- .any(|entry| entry.id == "call-1" && entry.status == ToolTimelineStatus::Error));
- assert!(snapshot.tool_timeline.iter().any(|entry| {
- entry.id == "subagent:task-1"
- && entry.status == ToolTimelineStatus::Error
- && entry
- .subagent
- .as_ref()
- .is_some_and(|activity| activity.tool_calls.len() == 1)
- }));
-
- mirror.finish();
- let interrupted = store
- .get("thread/mirror")
- .expect("read interrupted snapshot")
- .expect("interrupted snapshot");
- assert_eq!(interrupted.lifecycle, TurnLifecycle::Interrupted);
-
- let mut complete = TurnStateMirror::new(store.clone(), "thread/completed", "request-complete");
- assert!(complete.observe(&AgentProgress::TurnCompleted { iterations: 2 }));
- complete.finish();
- // A completed turn's snapshot is now RETAINED (lifecycle `Completed`) rather
- // than deleted, so the "View processing" panel can replay a finished turn
- // after reload. `finish()`/mark-all-interrupted skips `Completed` snapshots.
- let completed = store
- .get("thread/completed")
- .expect("completed snapshot lookup")
- .expect("completed snapshot retained for replay");
- assert_eq!(completed.lifecycle, TurnLifecycle::Completed);
-}
-
-#[test]
-fn memory_sync_profile_markdown_and_status_helpers_are_idempotent() {
- let tmp = TempDir::new().expect("tempdir");
- let mut profile = ProviderUserProfile {
- toolkit: "gmail".into(),
- connection_id: Some("conn-1".into()),
- display_name: Some("Jane\nDoe".into()),
- email: Some("[email protected]".into()),
- username: Some("jane\tdoe".into()),
- avatar_url: None,
- profile_url: Some("https://example.test/jane|profile".into()),
- extras: json!({ "source": "coverage" }),
- };
-
- merge_provider_into_profile_md(tmp.path(), &profile).expect("merge profile");
- profile.display_name = Some("Jane D.".into());
- merge_provider_into_profile_md(tmp.path(), &profile).expect("merge profile update");
- let profile_path = tmp.path().join("PROFILE.md");
- let body = std::fs::read_to_string(&profile_path).expect("read profile");
- assert!(body.contains(&block_start("connected-accounts")));
- assert!(body.contains("Jane D."));
- assert!(!body.contains("Jane\nDoe"));
- assert_eq!(body.matches("acct:gmail:conn-1").count(), 1);
-
- replace_managed_block(
- tmp.path(),
- "style",
- "## Style",
- "Use plain language.".into(),
- )
- .expect("replace style");
- replace_managed_block(tmp.path(), "goals", "## Goals", String::new()).expect("replace goals");
- let body = std::fs::read_to_string(&profile_path).expect("read profile after blocks");
- assert!(body.contains(&block_start("style")));
- assert!(body.contains("Use plain language."));
- assert!(body.contains("*(no entries yet)*"));
- assert!(body.contains(&block_end("goals")));
-
- remove_provider_from_profile_md(tmp.path(), "gmail", "conn-1").expect("remove provider");
- let body = std::fs::read_to_string(&profile_path).expect("read profile after remove");
- assert!(!body.contains("acct:gmail:conn-1"));
-
- let skipped = TempDir::new().expect("tempdir");
- let skipped_profile = ProviderUserProfile {
- toolkit: "gmail".into(),
- connection_id: None,
- display_name: Some("Skipped".into()),
- email: None,
- username: None,
- avatar_url: None,
- profile_url: None,
- extras: serde_json::Value::Null,
- };
- merge_provider_into_profile_md(skipped.path(), &skipped_profile).expect("skip profile");
- assert!(!skipped.path().join("PROFILE.md").exists());
- remove_provider_from_profile_md(skipped.path(), "", "").expect("remove missing no-op");
-
- let now = 1_700_000_000_000_i64;
- assert_eq!(
- openhuman_core::openhuman::memory::sync::sync_status::FreshnessLabel::from_age_ms(
- Some(now - 30_000),
- now
- ),
- openhuman_core::openhuman::memory::sync::sync_status::FreshnessLabel::Active
- );
- assert_eq!(
- openhuman_core::openhuman::memory::sync::sync_status::FreshnessLabel::from_age_ms(
- Some(now - 30_001),
- now
- ),
- openhuman_core::openhuman::memory::sync::sync_status::FreshnessLabel::Recent
- );
- assert_eq!(
- openhuman_core::openhuman::memory::sync::sync_status::FreshnessLabel::from_age_ms(
- None, now
- ),
- openhuman_core::openhuman::memory::sync::sync_status::FreshnessLabel::Idle
- );
-}
-
-#[test]
-fn memory_source_types_and_freshness_cover_validation_matrix() {
- let kinds = [
- SourceKind::Composio,
- SourceKind::Folder,
- SourceKind::GithubRepo,
- SourceKind::TwitterQuery,
- SourceKind::RssFeed,
- SourceKind::WebPage,
- ];
- for kind in kinds {
- let encoded = serde_json::to_string(&kind).expect("kind json");
- let decoded: SourceKind = serde_json::from_str(&encoded).expect("kind decode");
- assert_eq!(decoded, kind);
- }
-
- let now = 1_700_000_000_000_i64;
- assert_eq!(FreshnessLabel::from_age_ms(None, now), FreshnessLabel::Idle);
- assert_eq!(
- FreshnessLabel::from_age_ms(Some(now - 30_000), now),
- FreshnessLabel::Active
- );
- assert_eq!(
- FreshnessLabel::from_age_ms(Some(now - 30_001), now),
- FreshnessLabel::Recent
- );
- assert_eq!(
- FreshnessLabel::from_age_ms(Some(now - 5 * 60_000 - 1), now),
- FreshnessLabel::Idle
- );
-
- let mut composio_source = source(SourceKind::Composio, "cmp");
- assert!(composio_source.validate().unwrap_err().contains("toolkit"));
- composio_source.toolkit = Some("gmail".into());
- assert!(composio_source
- .validate()
- .unwrap_err()
- .contains("connection_id"));
- composio_source.connection_id = Some("conn-1".into());
- assert!(composio_source.validate().is_ok());
-
- let mut folder = source(SourceKind::Folder, "folder");
- assert!(folder.validate().unwrap_err().contains("path"));
- folder.path = Some("/tmp".into());
- assert!(folder.validate().is_ok());
-
- let mut github = source(SourceKind::GithubRepo, "github");
- assert!(github.validate().unwrap_err().contains("url"));
- github.url = Some("https://github.com/tinyhumansai/openhuman".into());
- assert!(github.validate().is_ok());
-
- let item = SourceItem {
- id: "item-1".into(),
- title: "Item".into(),
- updated_at_ms: Some(now),
- };
- assert_eq!(serde_json::to_value(item).unwrap()["updated_at_ms"], now);
- let content = SourceContent {
- id: "item-1".into(),
- title: "Item".into(),
- body: "Body".into(),
- content_type: ContentType::Markdown,
- metadata: json!({ "source": "test" }),
- };
- assert_eq!(
- serde_json::to_value(content).unwrap()["content_type"],
- "markdown"
- );
-}
-
-#[test]
-fn turn_state_store_persists_lists_marks_and_clears_snapshots() {
- let tmp = TempDir::new().expect("tempdir");
- let workspace = tmp.path().to_path_buf();
- let mut first = TurnState::started("thread/a", "request-1", 4, "2026-05-29T12:00:00Z");
- first.lifecycle = TurnLifecycle::Streaming;
- first.phase = Some(TurnPhase::Subagent);
- first.active_subagent = Some("research".into());
- first.tool_timeline.push(ToolTimelineEntry {
- id: "subagent-1".into(),
- name: "subagent:research".into(),
- round: 2,
- status: ToolTimelineStatus::Running,
- failure: None,
- args_buffer: None,
- display_name: Some("Research".into()),
- detail: None,
- source_tool_name: None,
- subagent: Some(SubagentActivity {
- task_id: "task-1".into(),
- agent_id: "agent-1".into(),
- status: Some("running".into()),
- mode: Some("focused".into()),
- dedicated_thread: Some(true),
- child_iteration: Some(1),
- child_max_iterations: Some(3),
- iterations: Some(1),
- elapsed_ms: Some(250),
- output_chars: Some(42),
- worker_thread_id: None,
- tool_calls: vec![SubagentToolCall {
- call_id: "call-1".into(),
- tool_name: "memory.search".into(),
- status: ToolTimelineStatus::Success,
- iteration: Some(1),
- elapsed_ms: Some(100),
- output_chars: Some(10),
- display_name: None,
- output: None,
- detail: None,
- args: None,
- failure: None,
- }],
- transcript: vec![],
- }),
- output: None,
- seq: None,
- });
- let second = TurnState::started("thread/b", "request-2", 2, "2026-05-29T12:01:00Z");
-
- turn_state::store::put(workspace.clone(), &first).expect("put first");
- turn_state::store::put(workspace.clone(), &second).expect("put second");
- assert_eq!(
- turn_state::store::get(workspace.clone(), "thread/a")
- .unwrap()
- .unwrap()
- .active_subagent
- .as_deref(),
- Some("research")
- );
- assert!(turn_state::store::get(workspace.clone(), "missing")
- .unwrap()
- .is_none());
-
- let mut listed = turn_state::store::list(workspace.clone()).expect("list states");
- listed.sort_by(|a, b| a.thread_id.cmp(&b.thread_id));
- assert_eq!(listed.len(), 2);
- let wire = serde_json::to_value(ListTurnStatesResponse {
- turn_states: listed.clone(),
- count: listed.len(),
- })
- .expect("list response json");
- assert_eq!(wire["count"], 2);
- assert_eq!(wire["turnStates"][0]["threadId"], "thread/a");
-
- let marked = turn_state::store::mark_all_interrupted(workspace.clone(), "2026-05-29T12:02:00Z")
- .expect("mark interrupted");
- assert_eq!(marked, 2);
- let marked_again =
- turn_state::store::mark_all_interrupted(workspace.clone(), "2026-05-29T12:03:00Z")
- .expect("mark interrupted again");
- assert_eq!(marked_again, 0);
- let interrupted = turn_state::store::get(workspace.clone(), "thread/a")
- .unwrap()
- .unwrap();
- assert_eq!(interrupted.lifecycle, TurnLifecycle::Interrupted);
- assert!(interrupted.active_subagent.is_none());
- assert_eq!(interrupted.updated_at, "2026-05-29T12:02:00Z");
-
- assert!(turn_state::store::delete(workspace.clone(), "thread/a").expect("delete one"));
- assert!(!turn_state::store::delete(workspace.clone(), "thread/a").expect("delete missing"));
- let removed = turn_state::store::clear_all(workspace.clone()).expect("clear all");
- assert_eq!(removed, 1);
- assert!(turn_state::store::list(workspace).unwrap().is_empty());
-}
-
-#[tokio::test]
-async fn threads_rpc_ops_cover_crud_title_fallback_and_turn_state_cleanup() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", tmp.path());
- let config = Config::load_or_init().await.expect("init isolated config");
- let workspace_dir = config.workspace_dir.clone();
-
- let thread = thread_ops::thread_upsert(UpsertConversationThreadRequest {
- id: "thread/raw-crud".into(),
- title: "Chat Jan 1 1:00 AM".into(),
- created_at: "2026-05-29T12:00:00Z".into(),
- parent_thread_id: Some("parent-thread".into()),
- labels: Some(vec!["work".into(), "coverage".into()]),
- personality_id: Some("personality-1".into()),
- })
- .await
- .expect("upsert thread")
- .value
- .data
- .expect("thread summary");
- assert_eq!(thread.id, "thread/raw-crud");
- assert_eq!(thread.parent_thread_id.as_deref(), Some("parent-thread"));
-
- let created = thread_ops::thread_create_new(CreateConversationThreadRequest {
- labels: Some(vec!["scratch".into()]),
- personality_id: None,
- })
- .await
- .expect("create new thread")
- .value
- .data
- .expect("created thread");
- assert!(created.id.starts_with("thread-"));
- assert_eq!(created.labels, vec!["scratch"]);
-
- let message = ConversationMessageRecord {
- id: "msg-1".into(),
- content: "Please summarize launch blockers. Then inspect follow ups.".into(),
- message_type: "text".into(),
- extra_metadata: json!({ "before": true }),
- sender: "user".into(),
- created_at: "2026-05-29T12:01:00Z".into(),
- };
- let appended = thread_ops::message_append(AppendConversationMessageRequest {
- thread_id: "thread/raw-crud".into(),
- message: message.clone(),
- })
- .await
- .expect("append message")
- .value
- .data
- .expect("appended message");
- assert_eq!(appended.id, "msg-1");
- assert!(
- thread_ops::message_append(AppendConversationMessageRequest {
- thread_id: "missing-thread".into(),
- message,
- })
- .await
- .is_err()
- );
-
- let listed_messages = thread_ops::messages_list(ConversationMessagesRequest {
- thread_id: "thread/raw-crud".into(),
- })
- .await
- .expect("list messages")
- .value
- .data
- .expect("messages");
- assert_eq!(listed_messages.count, 1);
-
- let fallback_title =
- thread_ops::thread_generate_title(GenerateConversationThreadTitleRequest {
- thread_id: "thread/raw-crud".into(),
- assistant_message: Some(" ".into()),
- })
- .await
- .expect("fallback title")
- .value
- .data
- .expect("fallback summary");
- assert_eq!(fallback_title.title, "summarize launch blockers");
-
- assert!(
- thread_ops::thread_update_title(UpdateConversationThreadTitleRequest {
- thread_id: "thread/raw-crud".into(),
- title: " ".into(),
- })
- .await
- .unwrap_err()
- .contains("title must not be empty")
- );
- let renamed = thread_ops::thread_update_title(UpdateConversationThreadTitleRequest {
- thread_id: "thread/raw-crud".into(),
- title: " Manual coverage title ".into(),
- })
- .await
- .expect("manual title")
- .value
- .data
- .expect("renamed");
- assert_eq!(renamed.title, "Manual coverage title");
-
- let relabeled = thread_ops::thread_update_labels(UpdateConversationThreadLabelsRequest {
- thread_id: "thread/raw-crud".into(),
- labels: Vec::new(),
- })
- .await
- .expect("clear labels")
- .value
- .data
- .expect("relabeled");
- assert!(relabeled.labels.is_empty());
-
- let updated_message = thread_ops::message_update(UpdateConversationMessageRequest {
- thread_id: "thread/raw-crud".into(),
- message_id: "msg-1".into(),
- extra_metadata: Some(json!({ "after": true })),
- })
- .await
- .expect("update message")
- .value
- .data
- .expect("updated message");
- assert_eq!(updated_message.extra_metadata["after"], true);
- assert!(
- thread_ops::message_update(UpdateConversationMessageRequest {
- thread_id: "thread/raw-crud".into(),
- message_id: "missing".into(),
- extra_metadata: None,
- })
- .await
- .unwrap_err()
- .contains("message missing not found")
- );
-
- let all_threads = thread_ops::threads_list(EmptyRequest {})
- .await
- .expect("list threads")
- .value
- .data
- .expect("threads");
- assert!(all_threads.count >= 2);
- assert!(all_threads
- .threads
- .iter()
- .any(|thread| thread.title == "Manual coverage title"));
-
- let mut turn = TurnState::started("thread/raw-crud", "request-raw", 3, "2026-05-29T12:02:00Z");
- turn.lifecycle = TurnLifecycle::Streaming;
- turn.phase = Some(TurnPhase::Thinking);
- turn_state::store::put(workspace_dir.clone(), &turn).expect("put turn state");
- let turn_get = thread_ops::turn_state_get(GetTurnStateRequest {
- thread_id: "thread/raw-crud".into(),
- })
- .await
- .expect("turn get")
- .value
- .data
- .expect("turn response");
- assert_eq!(turn_get.turn_state.unwrap().request_id, "request-raw");
- let turn_list = thread_ops::turn_state_list(EmptyRequest {})
- .await
- .expect("turn list")
- .value
- .data
- .expect("turn list response");
- assert_eq!(turn_list.count, 1);
- assert!(
- thread_ops::turn_state_clear(ClearTurnStateRequest {
- thread_id: "missing".into(),
- })
- .await
- .expect("clear missing")
- .value
- .data
- .expect("clear response")
- .cleared
- == false
- );
- turn_state::store::put(workspace_dir.clone(), &turn).expect("restore turn state");
-
- let deleted = thread_ops::thread_delete(DeleteConversationThreadRequest {
- thread_id: "thread/raw-crud".into(),
- deleted_at: "2026-05-29T12:03:00Z".into(),
- })
- .await
- .expect("delete thread")
- .value
- .data
- .expect("delete response");
- assert!(deleted.deleted);
- assert!(turn_state::store::get(workspace_dir, "thread/raw-crud")
- .unwrap()
- .is_none());
-
- let purged = thread_ops::threads_purge(EmptyRequest {})
- .await
- .expect("purge")
- .value
- .data
- .expect("purge response");
- assert!(purged.agent_threads_deleted >= 1);
-}
-
-#[tokio::test]
-async fn threads_title_generation_branches_cover_noop_and_not_found_paths() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", tmp.path());
- Config::load_or_init().await.expect("init isolated config");
-
- let manual = thread_ops::thread_upsert(UpsertConversationThreadRequest {
- id: "thread/manual-title".into(),
- title: "Manual launch review".into(),
- created_at: "2026-05-29T13:00:00Z".into(),
- parent_thread_id: None,
- labels: None,
- personality_id: None,
- })
- .await
- .expect("upsert manual thread")
- .value
- .data
- .expect("manual thread");
- assert_eq!(manual.title, "Manual launch review");
-
- let unchanged_manual =
- thread_ops::thread_generate_title(GenerateConversationThreadTitleRequest {
- thread_id: "thread/manual-title".into(),
- assistant_message: Some("Assistant reply that should not be used".into()),
- })
- .await
- .expect("manual title skips generation")
- .value
- .data
- .expect("manual title response");
- assert_eq!(unchanged_manual.title, "Manual launch review");
-
- let placeholder = thread_ops::thread_upsert(UpsertConversationThreadRequest {
- id: "thread/no-user-message".into(),
- title: "Chat Jan 1 1:23 AM".into(),
- created_at: "2026-05-29T13:01:00Z".into(),
- parent_thread_id: None,
- labels: None,
- personality_id: None,
- })
- .await
- .expect("upsert placeholder thread")
- .value
- .data
- .expect("placeholder thread");
- assert_eq!(placeholder.title, "Chat Jan 1 1:23 AM");
-
- let no_user_message =
- thread_ops::thread_generate_title(GenerateConversationThreadTitleRequest {
- thread_id: "thread/no-user-message".into(),
- assistant_message: None,
- })
- .await
- .expect("no user message leaves placeholder")
- .value
- .data
- .expect("no user response");
- assert_eq!(no_user_message.title, "Chat Jan 1 1:23 AM");
-
- let missing = thread_ops::thread_generate_title(GenerateConversationThreadTitleRequest {
- thread_id: "thread/missing-title".into(),
- assistant_message: None,
- })
- .await
- .unwrap_err();
- let missing_text: String = missing.into();
- assert!(missing_text.contains("ThreadNotFound"));
-}
-
-#[tokio::test]
-async fn memory_sources_registry_rpc_and_schema_handlers_cover_crud_edges() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", module_workspace());
- let config = Config::load_or_init().await.expect("init isolated config");
- wipe_shared_store(&config);
- std::fs::write(tmp.path().join("reader-note.md"), "# Reader note").expect("write note");
-
- let schemas = all_memory_sources_controller_schemas();
- let controllers = all_memory_sources_registered_controllers();
- assert!(
- schemas.len() >= 9,
- "expected at least 9 memory_sources schemas, got {}",
- schemas.len()
- );
- assert_eq!(schemas.len(), controllers.len());
- assert_eq!(
- openhuman_core::openhuman::memory::sources::schemas::schemas("read_item").function,
- "read_item"
- );
-
- let add_controller = controllers
- .iter()
- .find(|controller| controller.schema.function == "add")
- .expect("add controller");
- let mut bad_params = Map::new();
- bad_params.insert("kind".into(), Value::String("folder".into()));
- assert!((add_controller.handler)(bad_params)
- .await
- .unwrap_err()
- .contains("missing field `label`"));
-
- let invalid_folder = memory_sources_rpc::add_rpc(memory_sources_rpc::AddRequest {
- kind: SourceKind::Folder,
- label: "Invalid folder".into(),
- enabled: true,
- toolkit: None,
- connection_id: None,
- path: None,
- glob: None,
- url: None,
- branch: None,
- paths: Vec::new(),
- query: None,
- since_days: None,
- max_items: None,
- max_commits: None,
- max_issues: None,
- max_prs: None,
- selector: None,
- max_tokens_per_sync: None,
- max_cost_per_sync_usd: None,
- sync_depth_days: None,
- })
- .await
- .unwrap_err();
- assert!(invalid_folder.contains("path"));
-
- let added = memory_sources_rpc::add_rpc(memory_sources_rpc::AddRequest {
- kind: SourceKind::Folder,
- label: "Folder source".into(),
- enabled: true,
- toolkit: None,
- connection_id: None,
- path: Some(tmp.path().to_string_lossy().to_string()),
- glob: Some("*.md".into()),
- url: None,
- branch: None,
- paths: Vec::new(),
- query: None,
- since_days: None,
- max_items: Some(4),
- max_commits: None,
- max_issues: None,
- max_prs: None,
- selector: None,
- max_tokens_per_sync: None,
- max_cost_per_sync_usd: None,
- sync_depth_days: None,
- })
- .await
- .expect("add folder")
- .value
- .source;
- assert_eq!(added.kind, SourceKind::Folder);
- assert!(memory_sources_rpc::add_rpc(memory_sources_rpc::AddRequest {
- kind: SourceKind::Folder,
- label: "Duplicate".into(),
- enabled: true,
- toolkit: None,
- connection_id: None,
- path: Some(tmp.path().to_string_lossy().to_string()),
- glob: None,
- url: None,
- branch: None,
- paths: Vec::new(),
- query: None,
- since_days: None,
- max_items: None,
- max_commits: None,
- max_issues: None,
- max_prs: None,
- selector: None,
- max_tokens_per_sync: None,
- max_cost_per_sync_usd: None,
- sync_depth_days: None,
- })
- .await
- .is_ok());
-
- let enabled_folders = registry::list_enabled_by_kind(SourceKind::Folder)
- .await
- .expect("enabled folders");
- assert!(enabled_folders.len() >= 2);
- assert_eq!(
- memory_sources_rpc::get_rpc(memory_sources_rpc::GetRequest {
- id: added.id.clone(),
- })
- .await
- .expect("get source")
- .value
- .source
- .unwrap()
- .label,
- "Folder source"
- );
- assert!(memory_sources_rpc::get_rpc(memory_sources_rpc::GetRequest {
- id: "missing".into(),
- })
- .await
- .expect("get missing")
- .value
- .source
- .is_none());
-
- let list_items = memory_sources_rpc::list_items_rpc(memory_sources_rpc::ListItemsRequest {
- source_id: added.id.clone(),
- })
- .await
- .expect("list items")
- .value
- .items;
- assert!(list_items.iter().any(|item| item.id == "reader-note.md"));
- let read_item = memory_sources_rpc::read_item_rpc(memory_sources_rpc::ReadItemRequest {
- source_id: added.id.clone(),
- item_id: "reader-note.md".into(),
- })
- .await
- .expect("read item")
- .value
- .content;
- assert_eq!(read_item.content_type, ContentType::Markdown);
-
- let disabled = memory_sources_rpc::update_rpc(memory_sources_rpc::UpdateRequest {
- id: added.id.clone(),
- patch: serde_json::from_value(json!({
- "label": "Disabled folder",
- "enabled": false,
- "glob": "**/*.md"
- }))
- .expect("patch"),
- })
- .await
- .expect("update source")
- .value
- .source;
- assert_eq!(disabled.label, "Disabled folder");
- assert!(!disabled.enabled);
- assert!(
- memory_sources_rpc::sync_rpc(memory_sources_rpc::SyncRequest {
- source_id: added.id.clone(),
- })
- .await
- .unwrap_err()
- .contains("disabled")
- );
- assert!(
- memory_sources_rpc::update_rpc(memory_sources_rpc::UpdateRequest {
- id: "missing".into(),
- patch: Default::default(),
- })
- .await
- .unwrap_err()
- .contains("not found")
- );
- assert!(
- memory_sources_rpc::list_items_rpc(memory_sources_rpc::ListItemsRequest {
- source_id: "missing".into(),
- })
- .await
- .unwrap_err()
- .contains("not found")
- );
-
- let statuses = memory_sources_rpc::status_list_rpc()
- .await
- .expect("status list")
- .value
- .statuses;
- assert!(statuses.iter().any(|status| status.source_id == added.id));
-
- assert!(
- memory_sources_rpc::remove_rpc(memory_sources_rpc::RemoveRequest {
- id: added.id.clone(),
- })
- .await
- .expect("remove source")
- .value
- .removed
- );
- assert!(
- !memory_sources_rpc::remove_rpc(memory_sources_rpc::RemoveRequest { id: added.id })
- .await
- .expect("remove missing")
- .value
- .removed
- );
-}
-
-#[tokio::test]
-async fn memory_ops_public_handlers_cover_document_file_kv_graph_and_envelopes() {
- Box::pin(memory_ops_public_handlers_cover_document_file_kv_graph_and_envelopes_body()).await;
-}
-
-async fn memory_ops_public_handlers_cover_document_file_kv_graph_and_envelopes_body() {
- let _lock = env_lock();
- ensure_memory_seams();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", module_workspace());
-
- let init = openhuman_core::openhuman::memory::ops::memory_init(MemoryInitRequest {
- jwt_token: Some("ignored-token".into()),
- })
- .await
- .expect("memory init")
- .value
- .data
- .expect("init data");
- assert!(init.initialized);
- assert!(init.memory_dir.ends_with("/memory"));
- let memory_dir = std::path::PathBuf::from(&init.memory_dir);
-
- let sync_channel = openhuman_core::openhuman::memory::ops::memory_sync_channel(
- openhuman_core::openhuman::memory::ops::SyncChannelParams {
- channel_id: "conn-not-present".into(),
- },
- )
- .await
- .expect("sync channel request")
- .value;
- assert!(sync_channel.requested);
- assert_eq!(sync_channel.channel_id, "conn-not-present");
- let sync_all = openhuman_core::openhuman::memory::ops::memory_sync_all()
- .await
- .expect("sync all request")
- .value;
- assert!(sync_all.requested);
- let ingestion = openhuman_core::openhuman::memory::ops::memory_ingestion_status()
- .await
- .expect("ingestion status")
- .value;
- assert_eq!(ingestion.queue_depth, 0);
- let learn_none = openhuman_core::openhuman::memory::ops::memory_learn_all(
- openhuman_core::openhuman::memory::ops::LearnAllParams {
- namespaces: Some(Vec::new()),
- },
- )
- .await
- .expect("learn empty request")
- .value;
- assert_eq!(learn_none.namespaces_processed, 0);
- assert!(learn_none.results.is_empty());
-
- let write =
- openhuman_core::openhuman::memory::ops::ai_write_memory_file(WriteMemoryFileRequest {
- relative_path: "notes/raw.md".into(),
- content: "Memory file coverage".into(),
- })
- .await
- .expect("write memory file")
- .value
- .data
- .expect("write data");
- assert!(write.written);
- assert_eq!(write.bytes_written, "Memory file coverage".len());
-
- let read = openhuman_core::openhuman::memory::ops::ai_read_memory_file(ReadMemoryFileRequest {
- relative_path: "notes/raw.md".into(),
- })
- .await
- .expect("read memory file")
- .value
- .data
- .expect("read data");
- assert_eq!(read.content, "Memory file coverage");
-
- std::fs::write(memory_dir.join("root.md"), "root").expect("root note");
- std::fs::write(memory_dir.join("memory.db"), "hidden").expect("sqlite stub");
- let root_files =
- openhuman_core::openhuman::memory::ops::ai_list_memory_files(ListMemoryFilesRequest {
- relative_dir: "".into(),
- })
- .await
- .expect("list root memory files")
- .value
- .data
- .expect("root list data");
- assert_eq!(root_files.files, vec!["root.md"]);
-
- let listed =
- openhuman_core::openhuman::memory::ops::ai_list_memory_files(ListMemoryFilesRequest {
- relative_dir: "notes".into(),
- })
- .await
- .expect("list memory files")
- .value
- .data
- .expect("list data");
- assert_eq!(listed.files, vec!["raw.md"]);
- assert!(
- openhuman_core::openhuman::memory::ops::ai_list_memory_files(ListMemoryFilesRequest {
- relative_dir: "../escape".into(),
- })
- .await
- .unwrap_err()
- .contains("traversal")
- );
-
- let namespace = "ops-raw-coverage";
- let document_id = openhuman_core::openhuman::memory::ops::doc_put(
- openhuman_core::openhuman::memory::ops::PutDocParams {
- namespace: namespace.into(),
- key: "doc-1".into(),
- title: "Ops coverage document".into(),
- content: "Alice owns deterministic coverage for memory ops.".into(),
- source_type: "test".into(),
- priority: "high".into(),
- tags: vec!["coverage".into()],
- metadata: json!({ "fixture": true }),
- category: "core".into(),
- session_id: Some("session-ops".into()),
- document_id: Some("doc-ops-raw".into()),
- },
- )
- .await
- .expect("doc put")
- .value
- .document_id;
- assert_eq!(document_id, "doc-ops-raw");
-
- let namespaces = openhuman_core::openhuman::memory::ops::namespace_list()
- .await
- .expect("namespace list")
- .value;
- assert!(namespaces.iter().any(|candidate| candidate == namespace));
- let learn_disabled = openhuman_core::openhuman::memory::ops::memory_learn_all(
- openhuman_core::openhuman::memory::ops::LearnAllParams {
- namespaces: Some(vec![namespace.into(), namespace.into(), "missing".into()]),
- },
- )
- .await
- .unwrap_err();
- assert!(learn_disabled.contains("local_ai.runtime_enabled=true"));
-
- let direct_docs = openhuman_core::openhuman::memory::ops::doc_list(Some(
- openhuman_core::openhuman::memory::ops::NamespaceOnlyParams {
- namespace: namespace.into(),
- },
- ))
- .await
- .expect("doc list")
- .value;
- assert!(direct_docs["documents"]
- .as_array()
- .unwrap()
- .iter()
- .any(|doc| doc["documentId"] == "doc-ops-raw"));
-
- let envelope_docs =
- openhuman_core::openhuman::memory::ops::memory_list_documents(ListDocumentsRequest {
- namespace: Some(namespace.into()),
- })
- .await
- .expect("memory list documents")
- .value;
- assert_eq!(envelope_docs.data.as_ref().unwrap().count, 1);
- assert_eq!(
- envelope_docs
- .meta
- .counts
- .as_ref()
- .unwrap()
- .get("num_documents"),
- Some(&1)
- );
-
- let query = openhuman_core::openhuman::memory::ops::context_query(
- openhuman_core::openhuman::memory::ops::QueryNamespaceParams {
- namespace: namespace.into(),
- query: "who owns deterministic coverage".into(),
- limit: Some(5),
- },
- )
- .await
- .expect("context query")
- .value;
- assert!(query.to_lowercase().contains("coverage"));
- let recalled = openhuman_core::openhuman::memory::ops::context_recall(
- openhuman_core::openhuman::memory::ops::RecallNamespaceParams {
- namespace: namespace.into(),
- limit: Some(5),
- },
- )
- .await
- .expect("context recall")
- .value
- .expect("recall text");
- assert!(recalled.contains("Ops coverage document"));
-
- openhuman_core::openhuman::memory::ops::kv_set(
- openhuman_core::openhuman::memory::ops::KvSetParams {
- namespace: Some(namespace.into()),
- key: "state".into(),
- value: json!({ "covered": true }),
- },
- )
- .await
- .expect("kv set");
- let kv = openhuman_core::openhuman::memory::ops::kv_get(
- openhuman_core::openhuman::memory::ops::KvGetDeleteParams {
- namespace: Some(namespace.into()),
- key: "state".into(),
- },
- )
- .await
- .expect("kv get")
- .value;
- assert_eq!(kv, Some(json!({ "covered": true })));
- let kv_rows = openhuman_core::openhuman::memory::ops::kv_list_namespace(
- openhuman_core::openhuman::memory::ops::NamespaceOnlyParams {
- namespace: namespace.into(),
- },
- )
- .await
- .expect("kv list")
- .value;
- assert!(kv_rows.iter().any(|row| row["key"] == "state"));
- assert!(
- openhuman_core::openhuman::memory::ops::kv_delete(
- openhuman_core::openhuman::memory::ops::KvGetDeleteParams {
- namespace: Some(namespace.into()),
- key: "state".into(),
- },
- )
- .await
- .expect("kv delete")
- .value
- );
-
- openhuman_core::openhuman::memory::ops::graph_upsert(
- openhuman_core::openhuman::memory::ops::GraphUpsertParams {
- namespace: Some(namespace.into()),
- subject: "Alice".into(),
- predicate: "OWNS".into(),
- object: "Memory Ops Coverage".into(),
- attrs: json!({ "source": "raw-test" }),
- },
- )
- .await
- .expect("graph upsert");
- let relations = openhuman_core::openhuman::memory::ops::graph_query(
- openhuman_core::openhuman::memory::ops::GraphQueryParams {
- namespace: Some(namespace.into()),
- subject: Some("Alice".into()),
- predicate: Some("OWNS".into()),
- },
- )
- .await
- .expect("graph query")
- .value;
- assert_eq!(relations[0]["object"], "MEMORY OPS COVERAGE");
-
- let tool_rule = openhuman_core::openhuman::memory::ops::tool_rule_put(
- openhuman_core::openhuman::memory::ops::ToolRulePutParams {
- tool_name: "shell".into(),
- rule: "Use dry-run flags before changing files.".into(),
- priority: Some(ApiToolMemoryPriority::High),
- source: Some(ApiToolMemorySource::UserExplicit),
- tags: vec!["safety".into()],
- id: Some("ops-rule-1".into()),
- },
- )
- .await
- .expect("tool rule put")
- .value;
- assert_eq!(tool_rule.id, "ops-rule-1");
- assert_eq!(tool_rule.priority, ApiToolMemoryPriority::High);
- let fetched_rule = openhuman_core::openhuman::memory::ops::tool_rule_get(
- openhuman_core::openhuman::memory::ops::ToolRuleRefParams {
- tool_name: "shell".into(),
- id: "ops-rule-1".into(),
- },
- )
- .await
- .expect("tool rule get")
- .value
- .expect("stored tool rule");
- assert_eq!(
- fetched_rule.rule,
- "Use dry-run flags before changing files."
- );
- let listed_rules = openhuman_core::openhuman::memory::ops::tool_rule_list(
- openhuman_core::openhuman::memory::ops::ToolRuleListParams {
- tool_name: "shell".into(),
- },
- )
- .await
- .expect("tool rule list")
- .value;
- assert!(listed_rules.iter().any(|rule| rule.id == "ops-rule-1"));
- let prompt_rules = openhuman_core::openhuman::memory::ops::tool_rules_for_prompt(
- openhuman_core::openhuman::memory::ops::ToolRulesForPromptParams {
- tools: vec!["shell".into()],
- },
- )
- .await
- .expect("tool rules prompt")
- .value;
- assert!(prompt_rules.rendered.contains("Use dry-run flags"));
- assert_eq!(prompt_rules.rules[0].id, "ops-rule-1");
- let tool_rules_json = openhuman_core::openhuman::memory::ops::tool_rules_json(
- openhuman_core::openhuman::memory::ops::ToolRuleListParams {
- tool_name: "shell".into(),
- },
- )
- .await
- .expect("tool rules json")
- .value;
- assert!(tool_rules_json
- .as_array()
- .unwrap()
- .iter()
- .any(|rule| rule["id"] == "ops-rule-1" && rule["priority"] == "high"));
- assert!(
- openhuman_core::openhuman::memory::ops::tool_rule_delete(
- openhuman_core::openhuman::memory::ops::ToolRuleRefParams {
- tool_name: "shell".into(),
- id: "ops-rule-1".into(),
- },
- )
- .await
- .expect("tool rule delete")
- .value
- );
- assert!(openhuman_core::openhuman::memory::ops::tool_rule_get(
- openhuman_core::openhuman::memory::ops::ToolRuleRefParams {
- tool_name: "shell".into(),
- id: "ops-rule-1".into(),
- },
- )
- .await
- .expect("tool rule missing")
- .value
- .is_none());
-
- let delete_missing =
- openhuman_core::openhuman::memory::ops::memory_delete_document(DeleteDocumentRequest {
- namespace: namespace.into(),
- document_id: "missing".into(),
- })
- .await
- .expect("delete missing")
- .value
- .data
- .expect("delete missing data");
- assert_eq!(delete_missing.status, "not_found");
-
- let deleted = openhuman_core::openhuman::memory::ops::doc_delete(
- openhuman_core::openhuman::memory::ops::DeleteDocParams {
- namespace: namespace.into(),
- document_id,
- },
- )
- .await
- .expect("doc delete")
- .value;
- assert_eq!(deleted["deleted"], true);
- let cleared = openhuman_core::openhuman::memory::ops::clear_namespace(
- openhuman_core::openhuman::memory::ops::ClearNamespaceParams {
- namespace: namespace.into(),
- },
- )
- .await
- .expect("clear namespace")
- .value;
- assert!(cleared.cleared);
-}
-
-#[tokio::test]
-async fn memory_tree_retrieval_rpc_and_schema_wrappers_cover_empty_and_invalid_paths() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", tmp.path());
- let config = config_in(&tmp);
-
- let schemas =
- openhuman_core::openhuman::memory::tree::retrieval::schemas::all_controller_schemas();
- let controllers =
- openhuman_core::openhuman::memory::tree::retrieval::schemas::all_registered_controllers();
- assert_eq!(schemas.len(), 5);
- assert_eq!(schemas.len(), controllers.len());
- assert_eq!(
- openhuman_core::openhuman::memory::tree::retrieval::schemas::schemas("missing").function,
- "unknown"
- );
- assert!(schemas
- .iter()
- .find(|schema| schema.function == "fetch_leaves")
- .unwrap()
- .description
- .contains("Batch-fetch"));
-
- let source = openhuman_core::openhuman::memory::tree::retrieval::rpc::query_source_rpc(
- &config,
- openhuman_core::openhuman::memory::tree::retrieval::rpc::QuerySourceRequest {
- source_id: Some("slack:#raw".into()),
- source_kind: Some("chat".into()),
- time_window_days: Some(7),
- query: None,
- limit: Some(2),
- },
- )
- .await
- .expect("query source rpc");
- assert!(source.value.hits.is_empty());
- assert!(source.logs[0].contains("has_source_id=true"));
- assert!(!source.logs[0].contains("slack:#raw"));
- assert!(
- openhuman_core::openhuman::memory::tree::retrieval::rpc::query_source_rpc(
- &config,
- openhuman_core::openhuman::memory::tree::retrieval::rpc::QuerySourceRequest {
- source_id: None,
- source_kind: Some("bogus".into()),
- time_window_days: None,
- query: None,
- limit: None,
- },
- )
- .await
- .unwrap_err()
- .contains("unknown source kind")
- );
-
- let search = openhuman_core::openhuman::memory::tree::retrieval::rpc::search_entities_rpc(
- &config,
- openhuman_core::openhuman::memory::tree::retrieval::rpc::SearchEntitiesRequest {
- query: "alice".into(),
- kinds: Some(vec!["email".into()]),
- limit: Some(10),
- },
- )
- .await
- .expect("search entities rpc");
- assert!(search.value.matches.is_empty());
- assert!(search.logs[0].contains("has_kinds=true"));
- assert!(
- openhuman_core::openhuman::memory::tree::retrieval::rpc::search_entities_rpc(
- &config,
- openhuman_core::openhuman::memory::tree::retrieval::rpc::SearchEntitiesRequest {
- query: "alice".into(),
- kinds: Some(vec!["missing".into()]),
- limit: None,
- },
- )
- .await
- .unwrap_err()
- .contains("unknown entity kind")
- );
-
- let drill = openhuman_core::openhuman::memory::tree::retrieval::rpc::drill_down_rpc(
- &config,
- openhuman_core::openhuman::memory::tree::retrieval::rpc::DrillDownRequest {
- node_id: "summary:source:redacted".into(),
- max_depth: None,
- query: None,
- limit: Some(3),
- },
- )
- .await
- .expect("drill down rpc");
- assert!(drill.value.hits.is_empty());
- assert!(drill.logs[0].contains("node_kind=summary"));
- assert!(!drill.logs[0].contains("redacted"));
-
- let fetch = openhuman_core::openhuman::memory::tree::retrieval::rpc::fetch_leaves_rpc(
- &config,
- openhuman_core::openhuman::memory::tree::retrieval::rpc::FetchLeavesRequest {
- chunk_ids: vec!["missing-1".into(), "missing-2".into()],
- },
- )
- .await
- .expect("fetch leaves rpc");
- assert!(fetch.value.hits.is_empty());
-
- let fetch_controller = controllers
- .iter()
- .find(|controller| controller.schema.function == "fetch_leaves")
- .expect("fetch controller");
- let mut bad_params = Map::new();
- bad_params.insert("chunk_ids".into(), json!("not-an-array"));
- assert!((fetch_controller.handler)(bad_params)
- .await
- .unwrap_err()
- .contains("invalid params"));
-}
-
-#[tokio::test]
-#[ignore = "needs a released tinymemory module serving the Retrieval family: \
- the query tools resolve the bound driver, and the currently \
- pinned artifact predates RetrieveSource"]
-async fn memory_query_backend_and_tree_flush_wrappers_cover_public_edges() {
- let _lock = env_lock();
- // The query tools resolve a bound memory driver; `module_workspace` is
- // where that driver lives for this whole process.
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", module_workspace());
- let mut config = Config::load_or_init().await.expect("init isolated config");
- config.memory_tree.embedding_endpoint = None;
- config.memory_tree.embedding_model = None;
- config.memory_tree.embedding_strict = false;
-
- let source_result = MemoryTreeQuerySourceTool
- .execute(json!({
- "source_id": "slack:#backend",
- "time_window_days": 1,
- "limit": 0
- }))
- .await
- .expect("source query tool");
- let source_response: retrieval::types::QueryResponse =
- serde_json::from_str(&source_result.text()).expect("source response json");
- assert!(source_response.hits.is_empty());
- assert_eq!(source_response.total, 0);
-
- let kind_result = MemoryTreeQuerySourceTool
- .execute(json!({ "source_kind": "chat", "limit": 3 }))
- .await
- .expect("query source kind");
- let kind_response: retrieval::types::QueryResponse =
- serde_json::from_str(&kind_result.text()).expect("kind response json");
- assert!(kind_response.hits.is_empty());
-
- let drill_result = MemoryTreeDrillDownTool
- .execute(json!({
- "node_id": "summary:missing",
- "max_depth": 1,
- "limit": 2
- }))
- .await
- .expect("drill down tool");
- let drill: Vec<retrieval::types::RetrievalHit> =
- serde_json::from_str(&drill_result.text()).expect("drill response json");
- assert!(drill.is_empty());
- let leaves_result = MemoryTreeFetchLeavesTool
- .execute(json!({ "chunk_ids": [] }))
- .await
- .expect("fetch leaves tool");
- let leaves: Vec<retrieval::types::RetrievalHit> =
- serde_json::from_str(&leaves_result.text()).expect("leaves response json");
- assert!(leaves.is_empty());
-
- let no_stale =
- tinymemory_core::tree::tree::flush::flush_stale_buffers_default(
- &config,
- &tinymemory_core::tree::tree::LabelStrategy::Empty,
- )
- .await
- .expect("flush empty buffers");
- assert_eq!(no_stale, 0);
- let missing_flush = tinymemory_core::tree::tree::flush::force_flush_tree(
- &config,
- "tree:missing",
- None,
- &tinymemory_core::tree::tree::LabelStrategy::Empty,
- )
- .await
- .unwrap_err();
- assert!(missing_flush.to_string().contains("no tree with id"));
-}
-
-/// The `tree_summarizer_*` handlers' validation, query and provider-consent
-/// edges — every one of them driven through the handler.
-///
-/// # One door, and why it is the handler's (#5560)
-///
-/// The subject is `tree_runtime::ops`, so the production path is the door: the
-/// five handlers resolve `memory::binding` and ask the loaded module over the
-/// contract's six runtime-tree members. This case used to seed its query with
-/// `tree_runtime_store::write_node` — the engine copy the `[dev-dependencies]`
-/// entry links into *this* binary — and after `d2697f00a` that is a different
-/// store from the one the handler reads, so the query answered "node 'root' not
-/// found in namespace 'ops_ns'" over a node that had just been written.
-///
-/// # The one assertion that could not survive the door change
-///
-/// The seed existed to reach `tree_summarizer_query`'s **success** branch, and
-/// no handler on this surface can create a node: `runtime_summarize` /
-/// `runtime_rebuild` are the only writers and both fold on the driver's own chat
-/// provider, which a hermetic case has no model for — and which this case
-/// deliberately refuses anyway, two asserts below. Seeding the module's store
-/// from the host's engine to get the branch back is precisely the divergence
-/// #5560 exists to remove, so the branch is asserted where a driver can be bound
-/// instead: `memory::tree::tree_runtime::ops_tests::
-/// tree_summarizer_query_returns_node_and_children` pins the whole
-/// `{node, children}` envelope and the `queried node 'root'` log line.
-///
-/// What replaces it here is the assertion the seed was in the way of: that an
-/// **ingest is not a node**. Buffering content leaves `total_nodes` at zero and
-/// leaves `root` absent, and the refusal names the trimmed namespace — the
-/// handler's own trim, over a padded input, which is what tells a
-/// namespace-mangling bug from an empty tree.
-#[tokio::test]
-async fn tree_summarizer_ops_cover_validation_query_and_local_provider_guards() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- // The handlers resolve a bound memory driver; `module_workspace` is where
- // that driver lives for this whole process, and the env var has to agree
- // with the config or the two halves address different stores.
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", module_workspace());
- let mut config = config_in(&tmp);
- use_module_workspace(&mut config);
- // Local AI off and cloud summarization un-opted-in: the state the two
- // provider guards below assert on.
- config.local_ai.runtime_enabled = false;
- config.memory_tree.cloud_summarization_opt_in = false;
-
- let empty_content =
- openhuman_core::openhuman::memory::tree::tree_runtime::ops::tree_summarizer_ingest(
- &config, "ops_ns", " ", None, None,
- )
- .await
- .unwrap_err();
- assert!(empty_content.contains("content must not be empty"));
-
- let ts = Utc.with_ymd_and_hms(2026, 5, 29, 17, 0, 0).unwrap();
- let ingest =
- openhuman_core::openhuman::memory::tree::tree_runtime::ops::tree_summarizer_ingest(
- &config,
- " ops_ns ",
- "buffered raw content for summarizer ops",
- Some(ts),
- Some(&json!({ "source": "coverage" })),
- )
- .await
- .expect("ingest buffer");
- assert_eq!(ingest.value["buffered"], true);
- assert_eq!(ingest.value["namespace"], "ops_ns");
- assert_eq!(ingest.value["has_metadata"], true);
-
- let status =
- openhuman_core::openhuman::memory::tree::tree_runtime::ops::tree_summarizer_status(
- &config, "ops_ns",
- )
- .await
- .expect("status");
- assert_eq!(status.value["namespace"], "ops_ns");
- assert_eq!(status.value["total_nodes"], 0);
-
- // An ingest buffers; it does not build a node. The default `root` target is
- // therefore still absent, and the refusal names the namespace **trimmed**,
- // from a padded argument — the handler's own wording, over the driver's
- // `Ok(None)`.
- let unbuilt_root =
- openhuman_core::openhuman::memory::tree::tree_runtime::ops::tree_summarizer_query(
- &config, " ops_ns ", None,
- )
- .await
- .unwrap_err();
- assert_eq!(
- unbuilt_root,
- "node 'root' not found in namespace 'ops_ns'",
- "buffering content must not create a tree node"
- );
-
- let missing =
- openhuman_core::openhuman::memory::tree::tree_runtime::ops::tree_summarizer_query(
- &config,
- "ops_ns",
- Some("2026/05/29/17"),
- )
- .await
- .unwrap_err();
- assert!(missing.contains("node '2026/05/29/17' not found"));
-
- let provider_guard =
- openhuman_core::openhuman::memory::tree::tree_runtime::ops::tree_summarizer_run(
- &config, "ops_ns",
- )
- .await
- .unwrap_err();
- // No local AI + cloud-summarization opt-in defaults off ⇒ the guard names the
- // local-AI remediation in user-facing prose ("enable local AI ...").
- assert!(provider_guard.contains("local AI"));
- let rebuild_guard =
- openhuman_core::openhuman::memory::tree::tree_runtime::ops::tree_summarizer_rebuild(
- &config, "ops_ns",
- )
- .await
- .unwrap_err();
- assert!(rebuild_guard.contains("local AI"));
-}
-
-#[tokio::test]
-async fn memory_sources_types_registry_and_sync_state_cover_public_persistence_edges() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", tmp.path());
- let _config = Config::load_or_init().await.expect("init isolated config");
- openhuman_core::openhuman::memory::sources::reconcile::ensure_composio_sources().await;
-
- let decoded_default: MemorySourceEntry = serde_json::from_value(json!({
- "id": "src_default",
- "kind": "rss_feed",
- "label": "Default enabled",
- "url": "https://example.test/feed.xml"
- }))
- .expect("deserialize source with default enabled");
- assert!(decoded_default.enabled);
-
- let mut invalid = source(SourceKind::Folder, "");
- assert_eq!(invalid.validate().unwrap_err(), "id is required");
- invalid.id = "src_missing_label".into();
- invalid.label.clear();
- assert_eq!(invalid.validate().unwrap_err(), "label is required");
- invalid.label = "Missing path".into();
- assert!(invalid.validate().unwrap_err().contains("path is required"));
- assert!(source(SourceKind::RssFeed, "rss_missing")
- .validate()
- .unwrap_err()
- .contains("url is required"));
- assert!(source(SourceKind::WebPage, "web_missing")
- .validate()
- .unwrap_err()
- .contains("url is required"));
-
- let mut entry = source(SourceKind::GithubRepo, "src_repo");
- entry.url = Some("https://github.com/tinyhumansai/openhuman".into());
- let added = registry::add_source(entry.clone())
- .await
- .expect("add repo source");
- assert_eq!(added.kind.as_str(), "github_repo");
- assert!(registry::add_source(entry)
- .await
- .unwrap_err()
- .contains("already exists"));
-
- let patch: registry::MemorySourcePatch = serde_json::from_value(json!({
- "label": "Updated repo",
- "enabled": false,
- "url": "https://github.com/tinyhumansai/openhuman-skills",
- "branch": "main",
- "paths": ["skills", "README.md"],
- "max_tokens_per_sync": 1000,
- "max_cost_per_sync_usd": 0.5,
- "sync_depth_days": 30,
- "max_commits": 5,
- "max_issues": 6,
- "max_prs": 7
- }))
- .expect("patch");
- let updated = registry::update_source("src_repo", patch)
- .await
- .expect("update repo source");
- assert_eq!(updated.label, "Updated repo");
- assert!(!updated.enabled);
- assert_eq!(
- updated.url.as_deref(),
- Some("https://github.com/tinyhumansai/openhuman-skills")
- );
- assert_eq!(updated.branch.as_deref(), Some("main"));
- assert_eq!(updated.paths, vec!["skills", "README.md"]);
- assert_eq!(updated.max_tokens_per_sync, Some(1000));
- assert_eq!(updated.max_cost_per_sync_usd, Some(0.5));
- assert_eq!(updated.sync_depth_days, Some(30));
- assert_eq!(updated.max_commits, Some(5));
- assert_eq!(updated.max_issues, Some(6));
- assert_eq!(updated.max_prs, Some(7));
-
- // `SyncState::load`/`::save` — the key/value persistence extension this
- // block used to round-trip through `tinymemory_core::tinycortex::
- // HostSyncAdapter` (a `SyncStateStore` impl) — no longer exist anywhere
- // in `tinymemory-core`: `HostSyncAdapter` now offers only `new`, and
- // `integrations::composio::ops::memory_cleanup`'s doc comments confirm
- // this in passing, speaking of `SyncState::load` only in the past tense
- // ("exactly as `SyncState::load` had them"). The connection-delete path
- // that used to read a persisted `SyncState` was rewritten to work
- // without it (`ForgetSelector`-based cleanup instead). This is a
- // genuine, unrecoverable coverage gap for the persistence half — the
- // pure in-memory `SyncState`/`DailyBudget` behaviour (construction,
- // `advance_cursor`, `mark_synced`, `is_synced`, `budget_remaining`, …)
- // is still exercised elsewhere in this file
- // (`memory_sync_composio_catalog_scope_and_state_helpers_cover_edge_cases`),
- // so only the load/save round trip and its malformed-JSON recovery
- // behaviour are lost.
- let mut saved = SyncState::new("gmail", "conn-raw");
- saved.advance_cursor("cursor-raw");
- saved.mark_synced("msg-1");
- saved.daily_budget.date = "2000-01-01".into();
- saved.daily_budget.requests_used = DEFAULT_DAILY_REQUEST_LIMIT;
- assert_eq!(saved.cursor.as_deref(), Some("cursor-raw"));
- assert!(saved.is_synced("msg-1"));
-}
-
-#[test]
-fn email_clean_helpers_cover_reply_footer_truncation_and_date_edges() {
- assert_eq!(
- email_clean::drop_reply_chain("Fresh note\n\nOn Tue, 21 Apr 2026, Bob wrote:\n> old")
- .trim(),
- "Fresh note"
- );
- assert_eq!(
- email_clean::collapse_blank_runs("a\n\n\n\nb\n\n").as_str(),
- "a\n\nb"
- );
- assert_eq!(email_clean::truncate_body(" short ", 10), "short");
- assert_eq!(email_clean::truncate_body("abcdef", 3), "abc…");
- assert_eq!(
- email_clean::md_escape("a_b*\nnext|`"),
- "a\\_b\\* next\\|\\`"
- );
- assert_eq!(
- email_clean::extract_email("Alice <[email protected]>").as_deref(),
- );
- assert_eq!(
- email_clean::extract_email("[email protected]").as_deref(),
- );
- assert!(email_clean::extract_email("Alice Example").is_none());
-
- assert!(email_clean::parse_message_date(&json!({ "date": "" })).is_none());
- assert_eq!(
- email_clean::parse_message_date(&json!({ "date": "1717000000000" }))
- .unwrap()
- .timestamp_millis(),
- 1_717_000_000_000
- );
- assert_eq!(
- email_clean::parse_message_date(&json!({ "date": "2026-05-29T12:00:00Z" }))
- .unwrap()
- .timestamp(),
- 1_780_056_000
- );
- assert_eq!(
- email_clean::parse_message_date(&json!({ "date": "Fri, 29 May 2026 12:00:00 +0000" }))
- .unwrap()
- .timestamp(),
- 1_780_056_000
- );
- assert_eq!(
- email_clean::parse_message_date(&json!({ "date": "Mon, 29 May 2026 12:00:00 +0000" }))
- .unwrap()
- .timestamp(),
- 1_780_056_000
- );
- assert_eq!(
- email_clean::parse_message_date(&json!({ "date": "2026-05-29" }))
- .unwrap()
- .timestamp(),
- 1_780_012_800
- );
- assert!(email_clean::parse_message_date(&json!({ "date": "Nope, 29 May 2026" })).is_none());
-}
-
-#[test]
-fn welcome_migration_public_entrypoint_covers_empty_marker_and_transcript_paths() {
- let tmp = TempDir::new().expect("tempdir");
- let workspace = tmp.path();
-
- let session_raw = workspace.join("session_raw");
- std::fs::create_dir_all(&session_raw).expect("raw dir");
- std::fs::write(session_raw.join("skip.txt"), "not jsonl").expect("skip file");
- std::fs::write(
- session_raw.join("1715000000_welcome_thread-abc.jsonl"),
- "{\"_meta\":{\"agent\":\"welcome_thread-abc\",\"thread_id\":\"thread-abc\"}}\n{\"role\":\"user\",\"content\":\"hi\"}\n",
- )
- .expect("raw transcript");
- let markdown = workspace.join("sessions/2026_05_01/1715000000_welcome_thread-abc.md");
- std::fs::create_dir_all(markdown.parent().unwrap()).expect("markdown dir");
- std::fs::write(&markdown, "# Session transcript\n").expect("markdown");
-
- let result = openhuman_core::openhuman::threads::migrate_welcome_agent_artifacts(workspace)
- .expect("migrate welcome artifacts");
- assert_eq!(result.threads_updated, 0);
- assert_eq!(result.transcripts_updated, 1);
- assert_eq!(result.transcript_files_renamed, 1);
- assert_eq!(result.markdown_files_renamed, 1);
- assert!(workspace
- .join("session_raw/1715000000_orchestrator_thread-abc.jsonl")
- .exists());
- assert!(workspace
- .join("sessions/2026_05_01/1715000000_orchestrator_thread-abc.md")
- .exists());
-
- let second = openhuman_core::openhuman::threads::migrate_welcome_agent_artifacts(workspace)
- .expect("second migration");
- assert!(second.already_done);
-}
diff --git a/tests/raw_coverage/memory_tree_sync_deep_raw_coverage_e2e.rs b/tests/raw_coverage/memory_tree_sync_deep_raw_coverage_e2e.rs
deleted file mode 100644
index 23c9bf53a8..0000000000
--- a/tests/raw_coverage/memory_tree_sync_deep_raw_coverage_e2e.rs
+++ /dev/null
@@ -1,661 +0,0 @@
-//! Deep raw coverage for memory_tree + memory_sync round 18.
-//!
-//! Hermetic by construction: temp workspaces, no real provider APIs, and the
-//! tree-summarizer CLI is driven through the local test binary.
-
-use std::ffi::OsString;
-use std::path::{Path, PathBuf};
-use std::process::Command;
-use std::sync::{
- atomic::{AtomicUsize, Ordering},
- Arc, Mutex, OnceLock,
-};
-
-use anyhow::Result;
-use async_trait::async_trait;
-use chrono::{TimeZone, Utc};
-use serde_json::json;
-use tempfile::TempDir;
-
-use openhuman_core::openhuman::config::{Config, SchedulerGateMode};
-use openhuman_core::openhuman::memory::tree::tree::rpc::{
- get_chunk_rpc, ingest_rpc, list_chunks_rpc, set_enabled_rpc, GetChunkRequest, IngestRequest,
- ListChunksRequest, SetEnabledRequest,
-};
-use tinymemory_core::chat::{ChatPrompt, ChatProvider};
-use tinymemory_core::store::chunks::store::{set_chunk_embedding, upsert_chunks, with_connection};
-use tinymemory_core::store::chunks::types::{chunk_id, Chunk, Metadata, SourceKind, SourceRef};
-use tinymemory_core::store::trees::types::{SummaryNode, Tree, TreeKind};
-use tinymemory_core::tree::score::embed::EMBEDDING_DIM;
-use tinymemory_core::tree::score::extract::{
- EntityExtractor, EntityKind, ExtractedEntities, LlmEntityExtractor, LlmExtractorConfig,
-};
-use tinymemory_core::tree::score::resolver::{canonicalise, CanonicalEntity};
-use tinymemory_core::tree::score::store::{index_entity, lookup_entity};
-use tinymemory_core::tree::tree::set_summary_embedding;
-use tinymemory_core::tree::tree::store as tree_store;
-use tinymemory_core::tree::tree::TreeStatus;
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<OsString>,
-}
-
-impl EnvVarGuard {
- fn set_path(key: &'static str, value: impl AsRef<Path>) -> Self {
- let old = std::env::var_os(key);
- unsafe { std::env::set_var(key, value.as_ref()) };
- Self { key, old }
- }
-
- fn set_str(key: &'static str, value: &str) -> Self {
- let old = std::env::var_os(key);
- unsafe { std::env::set_var(key, value) };
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- unsafe {
- match &self.old {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
-
-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- ENV_LOCK
- .get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-fn test_config(tmp: &TempDir) -> Config {
- let mut cfg = Config::default();
- cfg.workspace_dir = tmp.path().to_path_buf();
- cfg.memory_tree.embedding_endpoint = None;
- cfg.memory_tree.embedding_model = None;
- cfg.memory_tree.embedding_strict = false;
- cfg
-}
-
-fn cli_workspace(tmp: &TempDir) -> PathBuf {
- let workspace = tmp.path().join("cli-workspace");
- std::fs::create_dir_all(&workspace).expect("create cli workspace");
- workspace
-}
-
-fn run_core_cli(workspace: &Path, args: &[&str]) -> std::process::Output {
- let bin = env!("CARGO_BIN_EXE_openhuman-core");
- Command::new(bin)
- .args(args)
- .env("OPENHUMAN_WORKSPACE", workspace)
- .env("OPENHUMAN_TRIGGER_TRIAGE_DISABLED", "1")
- .env("RUST_LOG", "warn")
- .output()
- .expect("run openhuman-core")
-}
-
-fn assert_cli_ok(workspace: &Path, args: &[&str]) -> String {
- let output = run_core_cli(workspace, args);
- assert!(
- output.status.success(),
- "CLI failed for {args:?}\nstdout:\n{}\nstderr:\n{}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr)
- );
- String::from_utf8(output.stdout).expect("utf8 stdout")
-}
-
-fn assert_cli_err(workspace: &Path, args: &[&str], expected: &str) {
- let output = run_core_cli(workspace, args);
- assert!(
- !output.status.success(),
- "CLI unexpectedly succeeded for {args:?}: {}",
- String::from_utf8_lossy(&output.stdout)
- );
- let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(
- stderr.contains(expected),
- "stderr did not contain {expected:?}\nactual:\n{stderr}"
- );
-}
-
-fn sample_chunk(cfg: &Config, source_id: &str, seq: u32, text: &str, timestamp_ms: i64) -> Chunk {
- let ts = Utc.timestamp_millis_opt(timestamp_ms).unwrap();
- let chunk = Chunk {
- id: chunk_id(SourceKind::Chat, source_id, seq, text),
- content: text.to_string(),
- metadata: Metadata {
- source_kind: SourceKind::Chat,
- source_id: source_id.to_string(),
- owner: "round18-user".into(),
- timestamp: ts,
- time_range: (ts, ts),
- tags: vec!["round18".into()],
- source_ref: Some(SourceRef::new(format!("slack://{source_id}/{seq}"))),
- path_scope: None,
- },
- token_count: 32,
- seq_in_source: seq,
- created_at: ts,
- partial_message: false,
- };
- upsert_chunks(cfg, std::slice::from_ref(&chunk)).expect("upsert chunk");
- chunk
-}
-
-fn seed_topic_summary(
- cfg: &Config,
- entity_id: &str,
- summary_id: &str,
- score: f32,
- ts_ms: i64,
-) -> SummaryNode {
- let ts = Utc.timestamp_millis_opt(ts_ms).unwrap();
- let tree = Tree {
- id: format!("tree:{summary_id}"),
- kind: TreeKind::Topic,
- scope: entity_id.to_string(),
- ask: None,
- root_id: Some(summary_id.to_string()),
- max_level: 2,
- status: TreeStatus::Active,
- created_at: ts,
- last_sealed_at: Some(ts),
- };
- tree_store::insert_tree(cfg, &tree).expect("insert topic tree");
-
- let node = SummaryNode {
- id: summary_id.to_string(),
- tree_id: tree.id.clone(),
- tree_kind: TreeKind::Topic,
- level: 2,
- parent_id: None,
- child_ids: vec!["child-a".into(), "child-b".into()],
- content: "Phoenix topic summary with rollout decisions and owner notes.".into(),
- token_count: 64,
- entities: vec![entity_id.to_string()],
- topics: vec!["rollout".into()],
- time_range_start: ts,
- time_range_end: ts,
- score,
- sealed_at: ts,
- deleted: false,
- embedding: None,
- doc_id: None,
- version_ms: None,
- };
-
- with_connection(cfg, |conn| {
- conn.execute(
- "INSERT INTO mem_tree_summaries (
- id, tree_id, tree_kind, level, parent_id,
- child_ids_json, content, token_count,
- entities_json, topics_json,
- time_range_start_ms, time_range_end_ms,
- score, sealed_at_ms, deleted, embedding,
- content_path, content_sha256
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, NULL, NULL, NULL)",
- rusqlite::params![
- node.id,
- node.tree_id,
- node.tree_kind.as_str(),
- node.level,
- node.parent_id,
- serde_json::to_string(&node.child_ids).unwrap(),
- node.content,
- node.token_count,
- serde_json::to_string(&node.entities).unwrap(),
- serde_json::to_string(&node.topics).unwrap(),
- node.time_range_start.timestamp_millis(),
- node.time_range_end.timestamp_millis(),
- node.score,
- node.sealed_at.timestamp_millis(),
- node.deleted as i64,
- ],
- )?;
- Ok(())
- })
- .expect("insert summary row");
- node
-}
-
-fn one_hot(index: usize) -> Vec<f32> {
- let mut v = vec![0.0; EMBEDDING_DIM];
- v[index] = 1.0;
- v
-}
-
-struct ScriptedChatProvider {
- responses: Vec<Result<String, String>>,
- calls: AtomicUsize,
-}
-
-impl ScriptedChatProvider {
- fn new(responses: impl IntoIterator<Item = Result<String, String>>) -> Self {
- Self {
- responses: responses.into_iter().collect(),
- calls: AtomicUsize::new(0),
- }
- }
-
- fn calls(&self) -> usize {
- self.calls.load(Ordering::SeqCst)
- }
-}
-
-#[async_trait]
-impl ChatProvider for ScriptedChatProvider {
- fn name(&self) -> &str {
- "round18:scripted"
- }
-
- async fn chat_for_json(&self, prompt: &ChatPrompt) -> Result<String> {
- assert_eq!(prompt.kind, "memory_tree::extract");
- assert!(prompt.system.contains("Return JSON only"));
- assert!(prompt.user.contains("Return JSON only."));
- let idx = self.calls.fetch_add(1, Ordering::SeqCst);
- match self.responses.get(idx).cloned().unwrap_or_else(|| {
- Ok(
- r#"{"entities":[],"topics":[],"importance":0.0,"importance_reason":"empty"}"#
- .into(),
- )
- }) {
- Ok(value) => Ok(value),
- Err(msg) => anyhow::bail!(msg),
- }
- }
-}
-
-#[test]
-fn tree_summarizer_cli_covers_help_errors_file_ingest_query_and_status() {
- let tmp = TempDir::new().expect("tempdir");
- let workspace = cli_workspace(&tmp);
-
- let help = assert_cli_ok(&workspace, &["tree-summarizer", "--help"]);
- assert!(help.contains("tree-summarizer"));
- assert!(
- assert_cli_ok(&workspace, &["tree-summarizer", "ingest", "--help"])
- .contains("Either --content or --file is required")
- );
- assert_cli_ok(&workspace, &["tree-summarizer", "run", "--help"]);
- assert_cli_ok(&workspace, &["tree-summarizer", "query", "--help"]);
- assert_cli_ok(&workspace, &["tree-summarizer", "status", "--help"]);
- assert_cli_ok(&workspace, &["tree-summarizer", "rebuild", "--help"]);
-
- assert_cli_err(
- &workspace,
- &["tree-summarizer", "nonesuch"],
- "unknown tree-summarizer subcommand",
- );
- assert_cli_err(
- &workspace,
- &["tree-summarizer", "ingest", "round18-ns"],
- "either --content or --file is required",
- );
- assert_cli_err(
- &workspace,
- &[
- "tree-summarizer",
- "ingest",
- "round18-ns",
- "--file",
- "missing.md",
- ],
- "failed to read",
- );
-
- let empty = tmp.path().join("empty.txt");
- std::fs::write(&empty, " \n").expect("write empty input");
- assert_cli_err(
- &workspace,
- &[
- "tree-summarizer",
- "ingest",
- "round18-ns",
- "--file",
- empty.to_str().unwrap(),
- ],
- "content is empty",
- );
-
- let input = tmp.path().join("notes.txt");
- std::fs::write(&input, "Alice wrote the Phoenix rollout notes.").expect("write input");
- let ingested = assert_cli_ok(
- &workspace,
- &[
- "tree-summarizer",
- "ingest",
- "round18-ns",
- "--file",
- input.to_str().unwrap(),
- "-v",
- ],
- );
- assert!(ingested.contains("\"buffered\": true"));
-
- let ingested_content = assert_cli_ok(
- &workspace,
- &[
- "tree-summarizer",
- "ingest",
- "round18-ns",
- "--content",
- "Bob added deployment follow-up.",
- ],
- );
- assert!(ingested_content.contains("\"namespace\": \"round18-ns\""));
-
- let status = assert_cli_ok(&workspace, &["tree-summarizer", "status", "round18-ns"]);
- assert!(status.contains("\"namespace\": \"round18-ns\""));
- assert!(status.contains("\"total_nodes\""));
-
- assert_cli_err(
- &workspace,
- &["tree-summarizer", "query", "round18-ns"],
- "node 'root' not found",
- );
-
- assert_cli_err(
- &workspace,
- &[
- "tree-summarizer",
- "query",
- "round18-ns",
- "--node-id",
- "missing-node",
- ],
- "invalid node_id 'missing-node'",
- );
-}
-
-#[tokio::test]
-async fn llm_extractor_recovers_spans_topics_strict_filters_and_retry_paths() {
- let text = "Alice met Alice at the SF office about OAuth and PR #42.";
- let provider = Arc::new(ScriptedChatProvider::new([
- Ok(r#"{"entities":[{"kind":"person","text":"Alice"},{"kind":"person","text":"Alice"},{"kind":"location","text":"SF office"},{"kind":"technology","text":"OAuth"},{"kind":"artifact","text":"PR #42"},{"kind":"dragon","text":"hallucinated"}],"topics":[" auth flow ",""],"importance":1.8,"importance_reason":"Key migration decision"}"#.to_string()),
- ]));
- let extractor = LlmEntityExtractor::new(
- LlmExtractorConfig {
- emit_topics: true,
- output_language: Some("Spanish".into()),
- ..LlmExtractorConfig::default()
- },
- provider.clone(),
- );
- let extracted = extractor.extract(text).await.expect("extract");
- assert_eq!(provider.calls(), 1);
- assert_eq!(extracted.entities.len(), 5);
- assert_eq!(extracted.entities[0].span_start, 0);
- assert_eq!(extracted.entities[1].span_start, 10);
- assert_eq!(extracted.topics.len(), 1);
- assert_eq!(extracted.llm_importance, Some(1.0));
- assert_eq!(
- extracted.llm_importance_reason.as_deref(),
- Some("Key migration decision")
- );
-
- let canonical = canonicalise(&extracted);
- assert!(canonical
- .iter()
- .any(|entity| entity.canonical_id == "topic:auth flow"));
-
- let strict_provider = Arc::new(ScriptedChatProvider::new([Ok(
- r#"{"entities":[{"kind":"dragon","text":"Alice"},{"kind":"person","text":"Alice"}],"importance":0.4,"importance_reason":"ok"}"#.to_string(),
- )]));
- let strict = LlmEntityExtractor::new(
- LlmExtractorConfig {
- allowed_kinds: vec![EntityKind::Person],
- strict_kinds: true,
- ..LlmExtractorConfig::default()
- },
- strict_provider,
- );
- let strict_out = strict.extract(text).await.expect("strict extract");
- assert_eq!(strict_out.entities.len(), 1);
- assert_eq!(strict_out.entities[0].kind, EntityKind::Person);
-
- let retry_provider = Arc::new(ScriptedChatProvider::new([
- Err("transport down".to_string()),
- Ok(r#"{"entities":[{"kind":"person","text":"Alice"}],"importance":0.5,"importance_reason":"retried"}"#.to_string()),
- ]));
- let retrying = LlmEntityExtractor::new(LlmExtractorConfig::default(), retry_provider.clone());
- let retry_out = retrying.extract(text).await.expect("retry extract");
- assert_eq!(retry_provider.calls(), 2);
- assert_eq!(retry_out.entities.len(), 1);
-
- let truncated_provider = Arc::new(ScriptedChatProvider::new([
- Ok(r#"{"entities":[{"kind":"person","text":"Alice"}]"#.to_string()),
- Ok("not-json".to_string()),
- ]));
- let truncated = LlmEntityExtractor::new(LlmExtractorConfig::default(), truncated_provider);
- let empty_after_bad_json = truncated.extract(text).await.expect("bad json fallback");
- assert!(empty_after_bad_json.entities.is_empty());
-}
-
-/// The chunk-reading RPCs, the enable switch, and the ingest error surface.
-///
-/// **Status and backfill are deliberately not here any more.** They read
-/// through the memory contract now, and an integration test cannot answer
-/// that: `binding::install_diagnostics_for_test` is a `pub(crate)` test seam
-/// this crate cannot reach, and with no driver bound, resolving one either
-/// refuses — no module policy is published in a test process — or, where an
-/// artifact is on the path, reads the module's own store rather than the rows
-/// staged here. Writing rows and calling the handler proves nothing either way.
-///
-/// The coverage moved rather than being dropped, and is better placed:
-///
-/// - the precedence rule — `paused` > `error` > `degraded` > `syncing` >
-/// `running` > `idle` — in
-/// `rpc::tests::derive_pipeline_status_precedence_matches_spec`, against the
-/// pure function rather than a store coaxed into each state;
-/// - the handlers reading the driver's numbers, in
-/// `pipeline_status_renders_the_drivers_chunk_aggregates`,
-/// `pipeline_status_reflects_paused_when_scheduler_off` and
-/// `backfill_status_reports_the_drivers_pending_count`, each with a
-/// diagnostics driver bound;
-/// - and what a real store *is* — that an ingest raises the chunk count, that
-/// a deferred job stays ready without becoming eligible — in the driver's own
-/// conformance suite, where a real store exists.
-#[tokio::test]
-async fn memory_tree_rpc_chunk_reads_set_enabled_and_ingest_errors() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", tmp.path());
- let _triage = EnvVarGuard::set_str("OPENHUMAN_TRIGGER_TRIAGE_DISABLED", "1");
- let mut cfg = test_config(&tmp);
- // `list_chunks_rpc` below reads through the bound memory driver, which
- // under the `modules` gate is the loaded tinymemory artifact and resolves
- // its config from the process-wide boot policy. Publish it from THIS
- // test's config: the policy is first-call-wins and the module captures
- // its workspace at load, so the chunk seeded in-process and the rows the
- // module lists must name one store. The only driver-routed case in this
- // aggregated module, so nothing contends for the slot.
- #[cfg(feature = "modules")]
- openhuman_core::openhuman::modules::memory::set_modules_policy(Arc::new(cfg.clone()));
-
- let chunk = sample_chunk(
- &cfg,
- "chat:#status",
- 1,
- "A chunk the chunk-reading RPCs below can find.",
- 1_700_000_000_000,
- );
-
- // The gate is host state rather than the driver's: `set_enabled` reports
- // whether it changed anything, and which mode it landed in.
- cfg.scheduler_gate.mode = SchedulerGateMode::Off;
- let no_op = set_enabled_rpc(&mut cfg, SetEnabledRequest { enabled: false })
- .await
- .expect("set disabled no-op")
- .value;
- assert!(!no_op.changed);
- let changed = set_enabled_rpc(&mut cfg, SetEnabledRequest { enabled: true })
- .await
- .expect("set enabled")
- .value;
- assert!(changed.changed);
- assert_eq!(changed.mode, "auto");
-
- // One decoy per filter the request sets, so the assertion below fails if any
- // single one is ignored. With only the matching chunk in the store, a
- // handler that dropped every filter would still return exactly one row and
- // the test would pass.
- let wrong_source = sample_chunk(
- &cfg,
- "chat:#other",
- 1,
- "right kind, right owner, wrong source id",
- 1_700_000_001_000,
- );
- let wrong_time = sample_chunk(
- &cfg,
- "chat:#status",
- 2,
- "right source, outside the window",
- 1_900_000_000_000,
- );
- let wrong_owner = {
- let ts = Utc.timestamp_millis_opt(1_700_000_002_000).unwrap();
- let text = "right source and window, wrong owner";
- let chunk = Chunk {
- id: chunk_id(SourceKind::Chat, "chat:#status", 3, text),
- content: text.to_string(),
- metadata: Metadata {
- source_kind: SourceKind::Chat,
- source_id: "chat:#status".into(),
- owner: "someone-else".into(),
- timestamp: ts,
- time_range: (ts, ts),
- tags: vec!["round18".into()],
- source_ref: None,
- path_scope: None,
- },
- token_count: 32,
- seq_in_source: 3,
- created_at: ts,
- partial_message: false,
- };
- upsert_chunks(&cfg, std::slice::from_ref(&chunk)).expect("upsert decoy");
- chunk
- };
-
- let wrong_kind = {
- let ts = Utc.timestamp_millis_opt(1_700_000_003_000).unwrap();
- let text = "right source, owner and window, wrong source kind";
- let chunk = Chunk {
- id: chunk_id(SourceKind::Email, "chat:#status", 4, text),
- content: text.to_string(),
- metadata: Metadata {
- source_kind: SourceKind::Email,
- source_id: "chat:#status".into(),
- owner: "round18-user".into(),
- timestamp: ts,
- time_range: (ts, ts),
- tags: vec!["round18".into()],
- source_ref: None,
- path_scope: None,
- },
- token_count: 32,
- seq_in_source: 4,
- created_at: ts,
- partial_message: false,
- };
- upsert_chunks(&cfg, std::slice::from_ref(&chunk)).expect("upsert decoy");
- chunk
- };
-
- let listed = list_chunks_rpc(
- &cfg,
- ListChunksRequest {
- source_kind: Some("chat".into()),
- source_id: Some("chat:#status".into()),
- owner: Some("round18-user".into()),
- since_ms: Some(1_600_000_000_000),
- until_ms: Some(1_800_000_000_000),
- limit: Some(5),
- },
- )
- .await
- .expect("list chunks")
- .value
- .chunks;
- let listed_ids: Vec<&str> = listed.iter().map(|c| c.id.as_str()).collect();
- assert_eq!(
- listed_ids,
- vec![chunk.id.as_str()],
- "every filter must discriminate: {} (source id), {} (window), {} (owner), {} (source kind) are all in the store",
- wrong_source.id,
- wrong_time.id,
- wrong_owner.id,
- wrong_kind.id
- );
- let fetched = get_chunk_rpc(
- &cfg,
- GetChunkRequest {
- id: chunk.id.clone(),
- },
- )
- .await
- .expect("get chunk")
- .value
- .chunk
- .expect("chunk exists");
- assert_eq!(fetched.id, chunk.id);
- assert!(get_chunk_rpc(
- &cfg,
- GetChunkRequest {
- id: "missing".into()
- }
- )
- .await
- .expect("missing chunk")
- .value
- .chunk
- .is_none());
- assert!(list_chunks_rpc(
- &cfg,
- ListChunksRequest {
- source_kind: Some("unknown".into()),
- ..Default::default()
- },
- )
- .await
- .unwrap_err()
- .contains("unknown source kind"));
-
- let bad_chat = ingest_rpc(
- &cfg,
- IngestRequest {
- source_kind: SourceKind::Chat,
- source_id: "bad-chat".into(),
- owner: "owner".into(),
- tags: vec![],
- payload: json!({"not": "a chat batch"}),
- },
- )
- .await
- .unwrap_err();
- assert!(bad_chat.contains("invalid chat payload"));
- let bad_email = ingest_rpc(
- &cfg,
- IngestRequest {
- source_kind: SourceKind::Email,
- source_id: "bad-email".into(),
- owner: "owner".into(),
- tags: vec![],
- payload: json!({"not": "an email thread"}),
- },
- )
- .await
- .unwrap_err();
- assert!(bad_email.contains("invalid email payload"));
-
- let _empty_extracted = ExtractedEntities::default();
-}
diff --git a/tests/raw_coverage/memory_tree_sync_raw_coverage_e2e.rs b/tests/raw_coverage/memory_tree_sync_raw_coverage_e2e.rs
deleted file mode 100644
index 810b9d62ec..0000000000
--- a/tests/raw_coverage/memory_tree_sync_raw_coverage_e2e.rs
+++ /dev/null
@@ -1,524 +0,0 @@
-//! Focused raw integration coverage for memory-tree and memory-sync modules.
-//!
-//! This suite is intentionally hermetic: every test uses a temp workspace and
-//! any provider behavior is supplied by small in-process stubs. Run with
-//! `--test-threads=1` because config/env and a few registries are global.
-
-use std::ffi::OsString;
-use std::path::Path;
-use std::sync::{Mutex, OnceLock};
-
-use async_trait::async_trait;
-use chrono::{TimeZone, Utc};
-use serde_json::json;
-use tempfile::TempDir;
-
-use openhuman_core::core::events::DomainEvent;
-use tinybus::EventHandler;
-use openhuman_core::openhuman::config::Config;
-use tinymemory_core::store::chunks::store::upsert_chunks;
-use tinymemory_core::store::chunks::types::{
- approx_token_count, chunk_id, Chunk, Metadata, SourceKind as ChunkSourceKind, SourceRef,
-};
-use tinymemory_core::store::content;
-use tinymemory_core::store::trees::types::TreeKind;
-use tinymemory_core::store::trees::types::INPUT_TOKEN_BUDGET;
-use openhuman_core::openhuman::memory::sync::composio::bus::{
- ComposioConfigChangedSubscriber, ComposioTriggerSubscriber,
-};
-// `sync_state` moved off `memory::sync::composio::providers` (the deleted
-// engine registry's former home) onto the contract crate directly — this
-// data (a per-connection cursor/dedup-set/budget) was always pure `serde`
-// vocabulary shared by both sides of the module boundary, never engine
-// behaviour, so it re-exports unchanged. See
-// `integrations::composio::providers`'s module docs for the fuller account of
-// what moved where.
-use tinymemory_api::composio::state::{extract_item_id, DailyBudget, SyncState};
-use openhuman_core::openhuman::integrations::composio::providers::{
- agent_ready_toolkits, catalog_for_toolkit, classify_unknown, find_curated, has_native_provider,
- is_action_visible_with_pref, toolkit_from_slug, toolkit_has_scope, ToolScope, UserScopePref,
-};
-use tinymemory_core::tree::score::extract::{EntityKind, ExtractedEntities};
-use tinymemory_core::tree::score::resolver::canonicalise;
-use tinymemory_core::tree::tree::bucket_seal::append_leaf;
-use tinymemory_core::tree::tree::{
- append_leaf_deferred, get_or_create_tree, store as tree_store, LabelStrategy, LeafRef,
-};
-// As above: the host re-export is gone, the engine is named directly (#5560).
-//
-// `tree_runtime::rpc` is deliberately **not** imported here any more. Its five
-// handlers answer from the loaded module's store, and a case that mixed them
-// with these engine calls would be driving two stores that share no state — see
-// `tree_runtime_engine_rpc_and_walk_cover_success_and_edge_paths`.
-use tinymemory_core::tree::tree_runtime::{engine, store as runtime_store};
-use tinyinference::model::{ChatModel, ModelRequest, ModelResponse};
-
-struct EnvVarGuard {
- key: &'static str,
- old: Option<OsString>,
-}
-
-impl EnvVarGuard {
- fn set(key: &'static str, value: impl AsRef<Path>) -> Self {
- let old = std::env::var_os(key);
- unsafe {
- std::env::set_var(key, value.as_ref());
- }
- Self { key, old }
- }
-
- fn set_str(key: &'static str, value: &str) -> Self {
- let old = std::env::var_os(key);
- unsafe {
- std::env::set_var(key, value);
- }
- Self { key, old }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- unsafe {
- match &self.old {
- Some(value) => std::env::set_var(self.key, value),
- None => std::env::remove_var(self.key),
- }
- }
- }
-}
-
-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
-
-fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- ENV_LOCK
- .get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
-
-fn config_in(tmp: &TempDir) -> Config {
- let mut cfg = Config::default();
- cfg.workspace_dir = tmp.path().to_path_buf();
- cfg.config_path = tmp.path().join("config.toml");
- cfg.memory_tree.embedding_endpoint = None;
- cfg.memory_tree.embedding_model = None;
- cfg.memory_tree.embedding_strict = false;
- cfg
-}
-
-fn staged_chunk(cfg: &Config, source_id: &str, seq: u32, tokens: u32) -> Chunk {
- let ts = Utc
- .timestamp_millis_opt(1_700_000_000_000 + seq as i64)
- .unwrap();
- let content = format!("raw coverage chunk {source_id} {seq}");
- let chunk = Chunk {
- id: chunk_id(ChunkSourceKind::Chat, source_id, seq, &content),
- content,
- metadata: Metadata {
- source_kind: ChunkSourceKind::Chat,
- source_id: source_id.to_string(),
- owner: "coverage-user".into(),
- timestamp: ts,
- time_range: (ts, ts),
- tags: vec!["coverage".into(), "sync".into()],
- source_ref: Some(SourceRef::new(format!("chat://{source_id}/{seq}"))),
- path_scope: None,
- },
- token_count: tokens,
- seq_in_source: seq,
- created_at: ts,
- partial_message: false,
- };
- upsert_chunks(cfg, std::slice::from_ref(&chunk)).expect("upsert chunk");
- let content_root = cfg.memory_tree_content_root();
- std::fs::create_dir_all(&content_root).expect("content root");
- let staged = content::stage_chunks(&content_root, std::slice::from_ref(&chunk))
- .expect("stage chunk body");
- tinymemory_core::store::chunks::store::with_connection(cfg, |conn| {
- for staged_chunk in &staged {
- conn.execute(
- "UPDATE mem_tree_chunks
- SET content_path = ?1, content_sha256 = ?2
- WHERE id = ?3",
- rusqlite::params![
- staged_chunk.content_path,
- staged_chunk.content_sha256,
- staged_chunk.chunk.id
- ],
- )?;
- }
- Ok(())
- })
- .expect("persist staged chunk pointers");
- chunk
-}
-
-struct ScriptedProvider {
- responses: Mutex<Vec<String>>,
-}
-
-impl ScriptedProvider {
- fn new(responses: impl IntoIterator<Item = impl Into<String>>) -> Self {
- let mut items: Vec<String> = responses.into_iter().map(Into::into).collect();
- items.reverse();
- Self {
- responses: Mutex::new(items),
- }
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for ScriptedProvider {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference::Result<ModelResponse> {
- let response = self
- .responses
- .lock()
- .unwrap()
- .pop()
- .unwrap_or_else(|| "fallback scripted summary".to_string());
- Ok(ModelResponse::assistant(response))
- }
-}
-
-/// The engine's summarisation walk: buffer → hour leaves → propagated
-/// ancestors → rebuild, end to end against a scripted summariser.
-///
-/// # One door, and why it is the engine's (#5560)
-///
-/// This case used to seed and read through `tree_runtime::rpc`'s handlers while
-/// folding through `engine::run_summarization`, and after `d2697f00a` those are
-/// two different stores: the handlers answer from the **loaded module's** engine
-/// over the bus, `engine::` runs the copy the `[dev-dependencies]` entry links
-/// into this binary. The fold therefore drained a buffer the ingests had never
-/// written to and answered `None` — "last hour node".
-///
-/// The subject here is the walk, not the RPC envelope, so the whole case takes
-/// the engine door. That is also the only door it *can* take: `run_summarization`
-/// takes an explicit provider, and the contract's `runtime_summarize` does not —
-/// the fold runs on the driver's own chat provider, deliberately, so the
-/// [`ScriptedProvider`] below cannot cross the bus. Routing this through
-/// `tree_summarizer_run` would mean a real summarisation model in a hermetic
-/// suite.
-///
-/// Nothing is left uncovered by that choice. The handlers' side of the same
-/// ground is asserted where it belongs — against a bound driver — by
-/// `memory::tree::tree_runtime::ops_tests`
-/// (`tree_summarizer_status_reports_populated_tree_details` pins the same six
-/// nodes at depth five, `tree_summarizer_query_returns_node_and_children` the
-/// same node-plus-children envelope) and, module-routed, by
-/// `memory_tree_memory_round23_raw_coverage_e2e::
-/// tree_runtime_rpc_and_registered_handlers_cover_status_and_errors`.
-#[tokio::test]
-async fn tree_runtime_engine_rpc_and_walk_cover_success_and_edge_paths() {
- let tmp = TempDir::new().expect("tempdir");
- let cfg = config_in(&tmp);
- let ns = "round14-team";
-
- let first_ts = Utc.with_ymd_and_hms(2026, 5, 29, 10, 15, 0).unwrap();
- let second_ts = Utc.with_ymd_and_hms(2026, 5, 29, 11, 45, 0).unwrap();
- let first_path = runtime_store::buffer_write(
- &cfg,
- ns,
- "deployment notes mention Alice and the launch room",
- &first_ts,
- Some(&json!({"source": "round14"})),
- )
- .expect("buffer first");
- runtime_store::buffer_write(
- &cfg,
- ns,
- "follow-up notes mention Bob and post-launch cleanup",
- &second_ts,
- None,
- )
- .expect("buffer second");
- // The two ingests are what the fold consumes, so observe them before it
- // runs: this is the half `tree_summarizer_ingest` used to stand in for, and
- // it is the half that silently stopped being observed once the handler
- // started writing to the module's store instead of this one. Metadata is
- // read off the file rather than out of `buffer_read`, which strips the
- // frontmatter it is carried in.
- let on_disk = std::fs::read_to_string(&first_path).expect("buffer file exists");
- assert!(on_disk.contains("deployment notes mention Alice"));
- assert!(on_disk.contains("\"source\":\"round14\""));
- let buffered = runtime_store::buffer_read(&cfg, ns).expect("buffer read before drain");
- assert_eq!(buffered.len(), 2);
- assert!(buffered
- .iter()
- .any(|(_, body)| body.contains("post-launch cleanup")));
-
- let provider = ScriptedProvider::new([
- "hour 10 summary about Alice",
- "hour 11 summary about Bob",
- "rebuilt hour 10",
- "rebuilt hour 11",
- ]);
- let last = engine::run_summarization(&cfg, &provider, ns, Utc::now())
- .await
- .expect("run summarization")
- .expect("last hour node");
- assert_eq!(last.node_id, "2026/05/29/11");
- assert!(runtime_store::buffer_read(&cfg, ns)
- .expect("buffer read after drain")
- .is_empty());
-
- let status = runtime_store::get_tree_status(&cfg, ns).expect("status");
- assert_eq!(status.namespace, ns);
- assert_eq!(status.total_nodes, 6);
- assert_eq!(status.depth, 5);
-
- // What `tree_summarizer_query` renders as `{node, children}`, read as the
- // two store calls the handler now makes over the bus.
- let day = runtime_store::read_node(&cfg, ns, "2026/05/29")
- .expect("read day node")
- .expect("day node exists");
- assert_eq!(day.node_id, "2026/05/29");
- let children = runtime_store::read_children(&cfg, ns, "2026/05/29").expect("read day children");
- assert_eq!(children.len(), 2);
-
- runtime_store::buffer_write(
- &cfg,
- ns,
- "preserve me through rebuild",
- &Utc.with_ymd_and_hms(2026, 5, 29, 12, 0, 0).unwrap(),
- None,
- )
- .expect("write rebuild buffer");
- let rebuild_provider = ScriptedProvider::new([
- "rebuilt day summary",
- "rebuilt month summary",
- "rebuilt year summary",
- "rebuilt root summary",
- ]);
- let rebuilt = engine::rebuild_tree(&cfg, &rebuild_provider, ns)
- .await
- .expect("rebuild tree");
- assert_eq!(rebuilt.total_nodes, 6);
- assert_eq!(runtime_store::buffer_read(&cfg, ns).unwrap().len(), 1);
-}
-
-#[tokio::test]
-async fn bucket_seal_deferred_and_fallback_paths_preserve_buffers_and_labels() {
- let tmp = TempDir::new().expect("tempdir");
- let cfg = config_in(&tmp);
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(
- std::sync::Arc::new(cfg.clone()),
- );
- let tree = get_or_create_tree(&cfg, TreeKind::Source, "slack:#round14").expect("tree");
-
- let ts = Utc.timestamp_millis_opt(1_700_000_000_000).unwrap();
- let small = LeafRef {
- chunk_id: "missing-small".into(),
- token_count: 10,
- timestamp: ts,
- content: "small body".into(),
- entities: vec![],
- topics: vec![],
- score: 0.1,
- };
- assert!(!append_leaf_deferred(&cfg, &tree, &small).expect("append small"));
- assert!(!append_leaf_deferred(&cfg, &tree, &small).expect("append duplicate"));
- let l0 = tree_store::get_buffer(&cfg, &tree.id, 0).expect("l0 buffer");
- assert_eq!(l0.item_ids, vec!["missing-small"]);
- assert_eq!(l0.token_sum, 10);
-
- let c1 = staged_chunk(&cfg, "slack:#round14", 1, INPUT_TOKEN_BUDGET / 2);
- let c2 = staged_chunk(&cfg, "slack:#round14", 2, INPUT_TOKEN_BUDGET / 2);
- let leaf1 = LeafRef {
- chunk_id: c1.id.clone(),
- token_count: c1.token_count,
- timestamp: c1.created_at,
- content: c1.content.clone(),
- entities: vec!["email:[email protected]".into()],
- topics: vec!["launch".into()],
- score: 0.7,
- };
- let leaf2 = LeafRef {
- chunk_id: c2.id.clone(),
- token_count: c2.token_count,
- timestamp: c2.created_at,
- content: c2.content.clone(),
- entities: vec!["person:bob".into()],
- topics: vec!["cleanup".into()],
- score: 0.8,
- };
- assert!(!append_leaf_deferred(&cfg, &tree, &leaf1).expect("append leaf1"));
- assert!(append_leaf_deferred(&cfg, &tree, &leaf2).expect("append leaf2"));
-
- let seeded = tree_store::get_buffer(&cfg, &tree.id, 0).expect("seeded buffer");
- assert!(seeded.item_ids.iter().any(|id| id == &c1.id));
- assert!(seeded.item_ids.iter().any(|id| id == &c2.id));
-
- let sealed = append_leaf(&cfg, &tree, &leaf2, &LabelStrategy::Empty)
- .await
- .expect("fallback seal");
- assert_eq!(sealed.len(), 1);
- let summary = tree_store::get_summary(&cfg, &sealed[0])
- .expect("summary read")
- .expect("summary exists");
- assert_eq!(summary.level, 1);
- assert!(summary.content.contains("raw coverage chunk"));
- assert!(summary.entities.is_empty());
- assert!(summary.topics.is_empty());
-
- let after_l0 = tree_store::get_buffer(&cfg, &tree.id, 0).expect("after l0");
- assert!(after_l0.is_empty());
- let parent = tree_store::get_buffer(&cfg, &tree.id, 1).expect("parent buffer");
- assert_eq!(parent.item_ids, sealed);
-}
-
-#[tokio::test]
-async fn composio_providers_sync_state_and_bus_surfaces_cover_read_write_edges() {
- let _lock = env_lock();
- let tmp = TempDir::new().expect("tempdir");
- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", tmp.path());
- let _triage = EnvVarGuard::set_str("OPENHUMAN_TRIGGER_TRIAGE_DISABLED", "yes");
-
- // `capability_matrix()` — a pure host-side function that used to build
- // this table from the engine's provider registry — was deleted by
- // tinymemory v1.13.4 with no replacement here; `composio_list_capabilities`
- // now answers the equivalent RPC directly from the connectors module's
- // `ListCapabilities` member (module-mediated, not testable network-free
- // from this crate). What the matrix reported per toolkit is still
- // answerable from the two pure functions that fed it, though:
- // `has_native_provider` and `catalog_for_toolkit(..).is_some()`.
- assert!(has_native_provider("gmail"));
- assert!(catalog_for_toolkit("googlecalendar").is_some());
- let ready = agent_ready_toolkits();
- assert!(ready.windows(2).all(|pair| pair[0] <= pair[1]));
- assert!(ready.contains(&"gmail"));
-
- let gmail_catalog = catalog_for_toolkit("gmail").expect("gmail catalog");
- assert_eq!(
- find_curated(gmail_catalog, "gmail_fetch_emails").map(|c| c.scope),
- Some(ToolScope::Read)
- );
- assert_eq!(
- toolkit_from_slug("MICROSOFT_TEAMS_SEND_MESSAGE").as_deref(),
- Some("microsoft_teams")
- );
- assert_eq!(classify_unknown("GMAIL_DELETE_DRAFT"), ToolScope::Admin);
- assert_eq!(classify_unknown("NOTION_CREATE_PAGE"), ToolScope::Write);
- assert!(toolkit_has_scope("gmail", ToolScope::Read));
-
- let read_only = UserScopePref {
- read: true,
- write: false,
- admin: false,
- };
- assert!(is_action_visible_with_pref(
- "GMAIL_FETCH_EMAILS",
- &read_only
- ));
- assert!(!is_action_visible_with_pref("GMAIL_SEND_EMAIL", &read_only));
-
- let mut budget = DailyBudget {
- date: "1999-01-01".into(),
- requests_used: 499,
- limit: 500,
- };
- assert_eq!(budget.remaining(), 500);
- budget.record_requests(2);
- assert_eq!(budget.requests_used, 2);
- assert!(!budget.is_exhausted());
-
- let mut state = SyncState::new("gmail", "conn-round14");
- assert_eq!(state.budget_remaining(), 500);
- state.record_requests(500);
- assert!(state.budget_exhausted());
- state.mark_synced("msg-1");
- state.advance_cursor("1700000000000");
- state.set_last_seen_id("msg-2");
- state.set_last_sync_at_ms(1_700_000_000_123);
- assert!(state.is_synced("msg-1"));
- assert_eq!(state.cursor.as_deref(), Some("1700000000000"));
- assert_eq!(
- extract_item_id(
- &json!({"data": {"message": {"id": " nested-id "}}, "id": "fallback"}),
- &["data.message.id", "id"]
- )
- .as_deref(),
- Some("nested-id")
- );
-
- let trigger = ComposioTriggerSubscriber::new();
- assert_eq!(trigger.name(), "composio::trigger");
- assert_eq!(trigger.domains(), Some(&["composio"][..]));
- trigger
- .handle(&DomainEvent::ComposioTriggerReceived {
- toolkit: "gmail".into(),
- trigger: "GMAIL_NEW_GMAIL_MESSAGE".into(),
- metadata_id: "meta-1".into(),
- metadata_uuid: "uuid-1".into(),
- payload: json!({"subject": "coverage"}),
- })
- .await;
-
- let config_changed = ComposioConfigChangedSubscriber::new();
- assert_eq!(config_changed.name(), "composio::config_changed");
- config_changed
- .handle(&DomainEvent::ComposioConfigChanged {
- mode: "direct".into(),
- api_key_set: true,
- })
- .await;
-}
-
-// `default_composio_provider_hooks_cover_defaults_and_sync_preconditions`
-// used to implement a `MinimalProvider: ComposioProvider` and exercise the
-// trait's *default* method bodies: `identity_set`'s facet-count return,
-// `fetch_tasks`'s "provider has no task-fetch surface" default error,
-// `post_process_action_result`'s no-op default, `on_trigger`'s no-op
-// default, and `sync`'s "memory client is not ready" precondition check.
-//
-// `ComposioProvider` itself — trait, default methods included — is one of
-// the types tinymemory v1.13.4 deleted outright with the rest of the
-// in-process Composio pipeline (see
-// `crate::openhuman::integrations::composio::providers`'s module docs). It
-// did not move to a replacement inside this crate: reaching a connected
-// account now needs a credential this crate must not hold, so there is no
-// trait left to implement a minimal provider against, default methods
-// included. The nearest current behaviour — `run_sync_pass` refusing when no
-// connectors module is loaded, and `task_sources::pipeline::fetch_tasks_unavailable`
-// refusing task-board fetch for every toolkit — is already covered by
-// `composio_get_user_profile_refuses_cleanly_without_a_loaded_module`-style
-// tests elsewhere in this suite (see
-// memory_sync_round23_raw_coverage_e2e.rs and
-// json_rpc_e2e.rs::json_rpc_task_sources_fetch_pipeline_e2e), so this test
-// keeps only the entity-canonicalisation coverage below, which has nothing
-// to do with Composio and is untouched by the deletion. The trait-default
-// coverage above is a genuine gap with no local equivalent — flagged in the
-// migration report rather than papered over.
-#[tokio::test]
-async fn memory_tree_entity_canonicalisation_covers_email_and_person_kinds() {
- let extracted = ExtractedEntities {
- entities: vec![
- tinymemory_core::tree::score::extract::ExtractedEntity {
- kind: EntityKind::Email,
- text: "[email protected]".into(),
- span_start: 0,
- span_end: 19,
- score: 0.9,
- },
- tinymemory_core::tree::score::extract::ExtractedEntity {
- kind: EntityKind::Person,
- text: "Round Fourteen".into(),
- span_start: 20,
- span_end: 34,
- score: 0.7,
- },
- ],
- topics: vec![],
- llm_importance: Some(0.5),
- llm_importance_reason: Some("coverage fixture".into()),
- };
- let canonical = canonicalise(&extracted);
- assert!(canonical
- .iter()
- .any(|entity| entity.canonical_id == "email:[email protected]"));
- assert!(approx_token_count("one two three four") > 0);
-}
diff --git a/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs b/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
index 4f9eecab47..f4e6f670e7 100644
--- a/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/near90_closure_raw_coverage_e2e.rs
@@ -113,9 +113,6 @@ fn ensure_memory_seams(config: Arc<openhuman_core::openhuman::config::Config>) {
.name("round20-memory-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(move || {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::clone(
- &config,
- ));
#[cfg(feature = "modules")]
openhuman_core::openhuman::modules::memory::set_modules_policy(config);
})
diff --git a/tests/worker_c_modules_e2e.rs b/tests/worker_c_modules_e2e.rs
index 39dd431b23..a9edb5aa12 100644
--- a/tests/worker_c_modules_e2e.rs
+++ b/tests/worker_c_modules_e2e.rs
@@ -124,9 +124,6 @@ async fn setup() -> Harness {
.name("worker-c-memory-seams".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(|| {
- openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(Arc::new(
- openhuman_core::openhuman::config::Config::default(),
- ));
})
.expect("spawn worker-c memory seam installer")
.join()