Skip to content

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

chore(tests): remove obsolete memory sources e2e tests and fix env lock usage

Steven Enamakela33c144a0a45
diff --git a/tests/in_process/agent_approval_memory_coverage_e2e.rs b/tests/in_process/agent_approval_memory_coverage_e2e.rs
index 3f520b3ee8..75bc154118 100644
--- a/tests/in_process/agent_approval_memory_coverage_e2e.rs
+++ b/tests/in_process/agent_approval_memory_coverage_e2e.rs
@@ -703,7 +703,7 @@ async fn agent_registry_snapshot_counts_agree_with_the_component_inventory() {
/// `openhuman.memory_engines_list` agrees: nothing is active.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn memory_engine_status_explains_why_memory_is_off_when_signed_out() {
- let _lock = env_lock();
+ let _lock = env_lock_async().await;
let harness = setup().await;
let response = rpc(
diff --git a/tests/in_process/embeddings_rpc_e2e.rs b/tests/in_process/embeddings_rpc_e2e.rs
index 49833cb50f..d05e74355f 100644
--- a/tests/in_process/embeddings_rpc_e2e.rs
+++ b/tests/in_process/embeddings_rpc_e2e.rs
@@ -334,7 +334,7 @@ async fn embeddings_update_settings_switches_provider() {
#[tokio::test(flavor = "multi_thread")]
async fn embeddings_update_settings_dimension_change_applies_without_a_wipe() {
- let _lock = env_lock();
+ let _lock = env_lock_async().await;
let (rpc_base, _tmp, _guards, _join) = setup_embeddings_test().await;
// First set provider to voyage (a provider that supports multiple dims)
diff --git a/tests/in_process/memory_sources_e2e.rs b/tests/in_process/memory_sources_e2e.rs
deleted file mode 100644
index 5189b8162a..0000000000
--- a/tests/in_process/memory_sources_e2e.rs
+++ /dev/null
@@ -1,1321 +0,0 @@
-//! E2E tests for the memory_sources domain.
-//!
-//! Boots a real axum JSON-RPC server against an isolated workspace and
-//! exercises the full user flow: add source → list → list_items →
-//! read_item → ingest into memory tree → verify chunks indexed.
-//!
-//! Run with: `cargo test -p openhuman-cli --test in_process_all`
-
-use crate::env_guard::env_lock_async;
-use crate::env_guard::EnvVarGuard;
-use crate::memory_rpc::{ok, serve, write_config};
-use crate::rpc_auth::rpc_token;
-use std::path::Path;
-use std::sync::OnceLock;
-use std::time::Duration;
-
-use axum::http::header::AUTHORIZATION;
-use serde_json::{json, Value};
-use tempfile::tempdir;
-
-static TEST_HOME: OnceLock<tempfile::TempDir> = OnceLock::new();
-
-fn test_home() -> &'static Path {
- TEST_HOME
- .get_or_init(|| tempdir().expect("memory sources tempdir"))
- .path()
-}
-
-async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
- let client = reqwest::Client::builder()
- .timeout(Duration::from_secs(30))
- .build()
- .expect("client");
- let body = json!({
- "jsonrpc": "2.0",
- "id": id,
- "method": method,
- "params": params,
- });
- let url = format!("{}/rpc", base.trim_end_matches('/'));
- let resp = client
- .post(&url)
- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))
- .json(&body)
- .send()
- .await
- .unwrap_or_else(|e| panic!("POST {url}: {e}"));
- assert!(
- resp.status().is_success(),
- "HTTP error {} for {method}",
- resp.status(),
- );
- resp.json::<Value>()
- .await
- .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))
-}
-
-// ── Tests ─────────────────────────────────────────────────────────
-
-#[tokio::test]
-async fn memory_sources_crud_and_folder_read_flow() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- // Create a folder with test markdown files.
- let notes_dir = home.join("test-notes");
- std::fs::create_dir_all(&notes_dir).expect("mkdir notes");
- std::fs::write(
- notes_dir.join("architecture.md"),
- "# System Architecture\n\n\
- The platform uses microservices with three core services.\n\n\
- ## Auth Service\n\
- Handles OAuth2 flows and JWT rotation. Contact: [email protected]\n\n\
- ## Data Pipeline\n\
- Event-driven pipeline using Kafka. Throughput: ~50k events/sec. \
- Owner: [email protected]\n\n\
- Last reviewed: 2025-12-15 by the platform team.",
- )
- .expect("write architecture.md");
-
- std::fs::write(
- notes_dir.join("runbook.md"),
- "# Incident Runbook\n\n\
- ## P1: Database Connection Pool Exhaustion\n\
- 1. Check connection count via pg_stat_activity\n\
- 2. Scale read replicas if > 90% utilization\n\
- 3. Escalate to [email protected] if write-primary affected\n\n\
- Last updated: 2025-11-30",
- )
- .expect("write runbook.md");
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // ── Step 1: list sources (empty initially) ──
-
- let list0 = rpc(&rpc_base, 1, "openhuman.memory_sources_list", json!({})).await;
- let list0_result = ok(&list0, "initial list");
- let sources = list0_result
- .get("sources")
- .and_then(Value::as_array)
- .expect("sources array");
- assert!(sources.is_empty(), "should start with no sources");
-
- // ── Step 2: add a folder source ──
-
- let add = rpc(
- &rpc_base,
- 2,
- "openhuman.memory_sources_add",
- json!({
- "kind": "folder",
- "label": "Test Research Notes",
- "path": notes_dir.to_string_lossy(),
- "glob": "**/*.md",
- }),
- )
- .await;
- let add_result = ok(&add, "add folder source");
- let source = add_result.get("source").expect("source in add response");
- let source_id = source.get("id").and_then(Value::as_str).expect("source id");
- assert_eq!(source.get("kind").and_then(Value::as_str), Some("folder"));
- assert_eq!(
- source.get("label").and_then(Value::as_str),
- Some("Test Research Notes")
- );
- assert_eq!(source.get("enabled"), Some(&json!(true)));
-
- // ── Step 3: list sources (now has 1) ──
-
- let list1 = rpc(&rpc_base, 3, "openhuman.memory_sources_list", json!({})).await;
- let list1_result = ok(&list1, "list after add");
- let sources = list1_result
- .get("sources")
- .and_then(Value::as_array)
- .expect("sources array");
- assert_eq!(sources.len(), 1);
-
- // ── Step 4: get source by id ──
-
- let get = rpc(
- &rpc_base,
- 4,
- "openhuman.memory_sources_get",
- json!({ "id": source_id }),
- )
- .await;
- let get_result = ok(&get, "get source");
- let fetched = get_result.get("source").expect("source");
- assert_eq!(fetched.get("id").and_then(Value::as_str), Some(source_id));
-
- // ── Step 5: list items from the folder source ──
-
- let items_resp = rpc(
- &rpc_base,
- 5,
- "openhuman.memory_sources_list_items",
- json!({ "source_id": source_id }),
- )
- .await;
- let items_result = ok(&items_resp, "list_items");
- let items = items_result
- .get("items")
- .and_then(Value::as_array)
- .expect("items array");
- assert_eq!(items.len(), 2, "should list 2 markdown files");
-
- let item_ids: Vec<&str> = items
- .iter()
- .filter_map(|i| i.get("id").and_then(Value::as_str))
- .collect();
- assert!(item_ids.contains(&"architecture.md"));
- assert!(item_ids.contains(&"runbook.md"));
-
- // ── Step 6: read one item's content ──
-
- let read = rpc(
- &rpc_base,
- 6,
- "openhuman.memory_sources_read_item",
- json!({
- "source_id": source_id,
- "item_id": "architecture.md",
- }),
- )
- .await;
- let read_result = ok(&read, "read_item");
- let content = read_result.get("content").expect("content");
- let body = content.get("body").and_then(Value::as_str).expect("body");
- assert!(body.contains("System Architecture"));
- assert!(body.contains("[email protected]"));
- assert_eq!(
- content.get("content_type").and_then(Value::as_str),
- Some("markdown")
- );
-
- // ── Step 7: ingest the content into the memory tree ──
-
- let ingest = rpc(
- &rpc_base,
- 7,
- "openhuman.memory_tree_ingest",
- json!({
- "source_kind": "document",
- "source_id": format!("memory_sources:{source_id}:architecture.md"),
- "owner": "user",
- "tags": ["memory_sources", "folder"],
- "payload": {
- "provider": "memory_sources",
- "title": "System Architecture",
- "body": body,
- },
- }),
- )
- .await;
- let ingest_result = ok(&ingest, "memory_tree ingest");
- let chunks_written = ingest_result
- .get("chunks_written")
- .and_then(Value::as_u64)
- .unwrap_or(0);
- assert!(
- chunks_written >= 1,
- "should ingest at least 1 chunk, got {chunks_written}; full result: {ingest_result}"
- );
-
- // ── Step 8: verify chunks exist via list_sources ──
-
- let ls = rpc(
- &rpc_base,
- 8,
- "openhuman.memory_tree_list_sources",
- json!({}),
- )
- .await;
- let ls_result = ok(&ls, "memory_tree list_sources");
- // list_sources returns {sources: [...]} — but some RPCs wrap it differently.
- let mem_sources = if let Some(arr) = ls_result.as_array() {
- arr.clone()
- } else if let Some(arr) = ls_result.get("sources").and_then(Value::as_array) {
- arr.clone()
- } else {
- panic!("expected sources array in: {ls_result}");
- };
- assert!(
- !mem_sources.is_empty(),
- "memory tree should have at least one source after ingest"
- );
-
- // ── Step 9: update source label ──
-
- let update = rpc(
- &rpc_base,
- 9,
- "openhuman.memory_sources_update",
- json!({
- "id": source_id,
- "label": "Renamed Notes",
- }),
- )
- .await;
- let update_result = ok(&update, "update source");
- assert_eq!(
- update_result
- .get("source")
- .and_then(|s| s.get("label"))
- .and_then(Value::as_str),
- Some("Renamed Notes")
- );
-
- // ── Step 10: disable source ──
-
- let disable = rpc(
- &rpc_base,
- 10,
- "openhuman.memory_sources_update",
- json!({
- "id": source_id,
- "enabled": false,
- }),
- )
- .await;
- let disable_result = ok(&disable, "disable source");
- assert_eq!(
- disable_result.get("source").and_then(|s| s.get("enabled")),
- Some(&json!(false))
- );
-
- // ── Step 11: remove source ──
-
- let remove = rpc(
- &rpc_base,
- 11,
- "openhuman.memory_sources_remove",
- json!({ "id": source_id }),
- )
- .await;
- let remove_result = ok(&remove, "remove source");
- assert_eq!(remove_result.get("removed"), Some(&json!(true)));
-
- // Verify it's gone.
- let list_final = rpc(&rpc_base, 12, "openhuman.memory_sources_list", json!({})).await;
- let final_sources = ok(&list_final, "final list")
- .get("sources")
- .and_then(Value::as_array)
- .expect("sources")
- .len();
- assert_eq!(final_sources, 0, "source should be removed");
-
- // ── Step 12: removing again is idempotent ──
-
- let remove_again = rpc(
- &rpc_base,
- 13,
- "openhuman.memory_sources_remove",
- json!({ "id": source_id }),
- )
- .await;
- let remove_again_result = ok(&remove_again, "remove again");
- assert_eq!(remove_again_result.get("removed"), Some(&json!(false)));
-
- rpc_join.abort();
-}
-
-#[tokio::test]
-async fn memory_sources_validation_rejects_bad_input() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // Folder source without path → should error.
- let bad_add = rpc(
- &rpc_base,
- 20,
- "openhuman.memory_sources_add",
- json!({
- "kind": "folder",
- "label": "Missing path",
- }),
- )
- .await;
- assert!(
- bad_add.get("error").is_some(),
- "adding folder without path should fail: {bad_add}"
- );
-
- // GitHub source without url → should error.
- let bad_gh = rpc(
- &rpc_base,
- 21,
- "openhuman.memory_sources_add",
- json!({
- "kind": "github_repo",
- "label": "No URL",
- }),
- )
- .await;
- assert!(
- bad_gh.get("error").is_some(),
- "adding github_repo without url should fail: {bad_gh}"
- );
-
- // list_items for nonexistent source → should error.
- let bad_items = rpc(
- &rpc_base,
- 22,
- "openhuman.memory_sources_list_items",
- json!({ "source_id": "nonexistent" }),
- )
- .await;
- assert!(
- bad_items.get("error").is_some(),
- "list_items for missing source should fail: {bad_items}"
- );
-
- rpc_join.abort();
-}
-
-/// GitHub source E2E: add a public repo → list_items (commits/issues/PRs)
-/// → read one commit and one issue → ingest into memory tree.
-///
-/// Requires network + `gh` CLI (or unauthenticated GitHub API access).
-/// The test targets a small, stable public repo so API responses are
-/// predictable. Kept out of the default run so CI without
-/// outbound GitHub access doesn't fail on rate limits or transient
-/// network blips. `#[ignore]`d so it reports as ignored rather than passing
-/// without asserting. Run locally with:
-/// cargo test -p openhuman-cli --test in_process_all \
-/// memory_sources_github_repo_activity_flow -- --ignored
-#[tokio::test]
-#[ignore = "needs outbound network to GitHub (kelseyhightower/nocode via the gh CLI / GitHub API); not run in CI. Run: cargo test -p openhuman-cli --test in_process_all memory_sources_github_repo_activity_flow -- --ignored"]
-async fn memory_sources_github_repo_activity_flow() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // ── Step 1: add a GitHub repo source ──
-
- let add = rpc(
- &rpc_base,
- 100,
- "openhuman.memory_sources_add",
- json!({
- "kind": "github_repo",
- "label": "kelseyhightower/nocode",
- "url": "https://github.com/kelseyhightower/nocode",
- }),
- )
- .await;
- let add_result = ok(&add, "add github source");
- let source = add_result.get("source").expect("source");
- let source_id = source.get("id").and_then(Value::as_str).expect("id");
- assert_eq!(
- source.get("kind").and_then(Value::as_str),
- Some("github_repo")
- );
-
- // ── Step 2: list items — should return commits, issues, PRs ──
-
- let items_resp = rpc(
- &rpc_base,
- 101,
- "openhuman.memory_sources_list_items",
- json!({ "source_id": source_id }),
- )
- .await;
- let items_result = ok(&items_resp, "github list_items");
- let items = items_result
- .get("items")
- .and_then(Value::as_array)
- .expect("items array");
-
- assert!(
- !items.is_empty(),
- "github repo should have at least some activity items"
- );
-
- let has_commits = items.iter().any(|i| {
- i.get("id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .starts_with("commit:")
- });
- assert!(has_commits, "should have commit items");
-
- // ── Step 3: read a commit ──
-
- let commit_item = items
- .iter()
- .find(|i| {
- i.get("id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .starts_with("commit:")
- })
- .expect("at least one commit");
- let commit_id = commit_item
- .get("id")
- .and_then(Value::as_str)
- .expect("commit id");
-
- let read_commit = rpc(
- &rpc_base,
- 102,
- "openhuman.memory_sources_read_item",
- json!({
- "source_id": source_id,
- "item_id": commit_id,
- }),
- )
- .await;
- let commit_content = ok(&read_commit, "read commit");
- let content = commit_content.get("content").expect("content");
- let body = content.get("body").and_then(Value::as_str).expect("body");
- assert!(body.contains("Commit:"), "commit body should have header");
- assert!(body.contains("SHA:"), "commit body should have SHA");
- assert_eq!(
- content.get("content_type").and_then(Value::as_str),
- Some("markdown")
- );
-
- // ── Step 4: ingest the commit into memory tree ──
-
- let ingest = rpc(
- &rpc_base,
- 103,
- "openhuman.memory_tree_ingest",
- json!({
- "source_kind": "document",
- "source_id": format!("github:{source_id}:{commit_id}"),
- "owner": "user",
- "tags": ["memory_sources", "github", "commit"],
- "payload": {
- "provider": "github",
- "title": commit_item.get("title").and_then(Value::as_str).unwrap_or("commit"),
- "body": body,
- },
- }),
- )
- .await;
- let ingest_result = ok(&ingest, "ingest github commit");
- let chunks = ingest_result
- .get("chunks_written")
- .and_then(Value::as_u64)
- .unwrap_or(0);
- assert!(
- chunks >= 1,
- "should ingest at least 1 chunk from commit, got {chunks}"
- );
-
- // ── Step 5: read an issue if one exists ──
-
- if let Some(issue_item) = items.iter().find(|i| {
- i.get("id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .starts_with("issue:")
- }) {
- let issue_id = issue_item
- .get("id")
- .and_then(Value::as_str)
- .expect("issue id");
-
- let read_issue = rpc(
- &rpc_base,
- 104,
- "openhuman.memory_sources_read_item",
- json!({
- "source_id": source_id,
- "item_id": issue_id,
- }),
- )
- .await;
- let issue_content = ok(&read_issue, "read issue");
- let icontent = issue_content.get("content").expect("content");
- let ibody = icontent.get("body").and_then(Value::as_str).expect("body");
- assert!(ibody.contains("Issue #"), "issue body should have header");
- assert!(ibody.contains("State:"), "issue body should have state");
- }
-
- // ── Cleanup ──
-
- let remove = rpc(
- &rpc_base,
- 105,
- "openhuman.memory_sources_remove",
- json!({ "id": source_id }),
- )
- .await;
- ok(&remove, "remove github source");
-
- rpc_join.abort();
-}
-
-/// Composio source E2E: add a composio source entry → verify it's in
-/// the registry → list_items returns the connection as an item →
-/// read_item returns a descriptive placeholder → remove.
-///
-/// Does NOT require an actual Composio connection — tests the registry
-/// and reader behavior with synthetic config.
-#[tokio::test]
-async fn memory_sources_composio_registry_flow() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // ── Step 1: add a composio source ──
-
- let add = rpc(
- &rpc_base,
- 200,
- "openhuman.memory_sources_add",
- json!({
- "kind": "composio",
- "label": "Gmail · [email protected]",
- "toolkit": "gmail",
- "connection_id": "cmp_test_123",
- }),
- )
- .await;
- let add_result = ok(&add, "add composio source");
- let source = add_result.get("source").expect("source");
- let source_id = source.get("id").and_then(Value::as_str).expect("id");
- assert_eq!(source.get("kind").and_then(Value::as_str), Some("composio"));
- assert_eq!(source.get("toolkit").and_then(Value::as_str), Some("gmail"));
- assert_eq!(
- source.get("connection_id").and_then(Value::as_str),
- Some("cmp_test_123")
- );
-
- // ── Step 2: verify it shows up in list ──
-
- let list = rpc(&rpc_base, 201, "openhuman.memory_sources_list", json!({})).await;
- let list_result = ok(&list, "list with composio");
- let sources = list_result
- .get("sources")
- .and_then(Value::as_array)
- .expect("sources");
- assert_eq!(sources.len(), 1);
- assert_eq!(
- sources[0].get("toolkit").and_then(Value::as_str),
- Some("gmail")
- );
-
- // ── Step 3: list_items returns the connection as an item ──
-
- let items = rpc(
- &rpc_base,
- 202,
- "openhuman.memory_sources_list_items",
- json!({ "source_id": source_id }),
- )
- .await;
- let items_result = ok(&items, "composio list_items");
- let item_list = items_result
- .get("items")
- .and_then(Value::as_array)
- .expect("items");
- assert_eq!(item_list.len(), 1);
- assert_eq!(
- item_list[0].get("id").and_then(Value::as_str),
- Some("cmp_test_123")
- );
-
- // ── Step 4: read_item returns descriptive content ──
-
- let read = rpc(
- &rpc_base,
- 203,
- "openhuman.memory_sources_read_item",
- json!({
- "source_id": source_id,
- "item_id": "cmp_test_123",
- }),
- )
- .await;
- let read_result = ok(&read, "composio read_item");
- let content = read_result.get("content").expect("content");
- let body = content.get("body").and_then(Value::as_str).expect("body");
- assert!(
- body.contains("gmail"),
- "composio read should mention the toolkit"
- );
-
- // ── Step 5: add a second composio source (slack) ──
-
- let add2 = rpc(
- &rpc_base,
- 204,
- "openhuman.memory_sources_add",
- json!({
- "kind": "composio",
- "label": "Slack · workspace",
- "toolkit": "slack",
- "connection_id": "cmp_test_456",
- }),
- )
- .await;
- let add2_result = ok(&add2, "add slack composio source");
- let slack_id = add2_result
- .get("source")
- .and_then(|s| s.get("id"))
- .and_then(Value::as_str)
- .expect("slack source id");
-
- // ── Step 6: list should have both ──
-
- let list2 = rpc(&rpc_base, 205, "openhuman.memory_sources_list", json!({})).await;
- let sources2 = ok(&list2, "list with both")
- .get("sources")
- .and_then(Value::as_array)
- .expect("sources")
- .len();
- assert_eq!(sources2, 2);
-
- // ── Step 7: disable gmail, verify it persists ──
-
- let disable = rpc(
- &rpc_base,
- 206,
- "openhuman.memory_sources_update",
- json!({
- "id": source_id,
- "enabled": false,
- }),
- )
- .await;
- let disabled = ok(&disable, "disable gmail");
- assert_eq!(
- disabled.get("source").and_then(|s| s.get("enabled")),
- Some(&json!(false))
- );
-
- // ── Step 8: remove both ──
-
- for (idx, sid) in [source_id, slack_id].iter().enumerate() {
- let r = rpc(
- &rpc_base,
- 210 + idx as i64,
- "openhuman.memory_sources_remove",
- json!({ "id": sid }),
- )
- .await;
- ok(&r, &format!("remove {sid}"));
- }
-
- rpc_join.abort();
-}
-
-// ─── Relative folder-source paths (openhuman#5830, vendored via PR #5838) ────
-//
-// `FolderReader` was the only reader in `tinymemory-sources` that ignored the
-// workspace it is handed: `PathBuf::from(base_path)` used the configured string
-// verbatim, so a RELATIVE path resolved against the host process's current
-// working directory. For the desktop app that is the Tauri build directory, so
-// a source configured as `docs` looked in `…/crates/openhuman-app/docs`, found
-// nothing, and failed on every sync cycle forever.
-//
-// `resolve_base` now anchors a relative path on the workspace (absolute paths
-// are still taken verbatim, so every source configured before the fix resolves
-// exactly where it did). The reader is linked into the host as
-// `tinymemory_sources::readers::folder`, so this is reachable over the real
-// `memory_sources_*` RPC surface.
-//
-// The pre-existing `memory_sources_crud_and_folder_read_flow` above passes an
-// ABSOLUTE path, which is the branch the fix deliberately left alone — it
-// cannot catch this.
-
-/// A folder source configured with a RELATIVE path resolves against the
-/// workspace, not the process CWD.
-#[tokio::test]
-async fn memory_sources_folder_relative_path_resolves_against_the_workspace() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- // An explicit workspace makes "the workspace, not the CWD" a decidable
- // claim: the files exist only under this directory, and the test process's
- // CWD (the crate root) has no `relative-notes` at all.
- let workspace = home.join("relative-workspace");
- std::fs::create_dir_all(&workspace).expect("mkdir workspace");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace);
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let notes_dir = workspace.join("relative-notes");
- std::fs::create_dir_all(&notes_dir).expect("mkdir relative notes");
- std::fs::write(
- notes_dir.join("brief.md"),
- "# Relative Brief\n\nAnchored on the workspace, not the process CWD.",
- )
- .expect("write brief.md");
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // Note the path: relative, exactly as openhuman#5830 was configured.
- let add = rpc(
- &rpc_base,
- 900,
- "openhuman.memory_sources_add",
- json!({
- "kind": "folder",
- "label": "Relative Notes",
- "path": "relative-notes",
- "glob": "**/*.md",
- }),
- )
- .await;
- let add_result = ok(&add, "add relative folder source");
- let source_id = add_result
- .get("source")
- .and_then(|s| s.get("id"))
- .and_then(Value::as_str)
- .expect("source id")
- .to_string();
-
- // THE assertion. Before the fix the reader looked under the CWD, found no
- // `relative-notes`, and this call returned a "folder does not exist" error
- // rather than an items array.
- let items_resp = rpc(
- &rpc_base,
- 901,
- "openhuman.memory_sources_list_items",
- json!({ "source_id": source_id }),
- )
- .await;
- let items_result = ok(&items_resp, "list_items for a relative folder source");
- let items = items_result
- .get("items")
- .and_then(Value::as_array)
- .expect("items array");
- let item_ids: Vec<&str> = items
- .iter()
- .filter_map(|i| i.get("id").and_then(Value::as_str))
- .collect();
- assert!(
- item_ids.contains(&"brief.md"),
- "a relative folder path must resolve against the workspace; got {item_ids:?}"
- );
-
- // And the content actually reads back through the same resolution.
- let read = rpc(
- &rpc_base,
- 902,
- "openhuman.memory_sources_read_item",
- json!({ "source_id": source_id, "item_id": "brief.md" }),
- )
- .await;
- let read_result = ok(&read, "read_item for a relative folder source");
- let body = read_result
- .get("content")
- .and_then(|c| c.get("body"))
- .and_then(Value::as_str)
- .expect("body");
- assert!(
- body.contains("Anchored on the workspace"),
- "the resolved file must be the workspace one; got {body:?}"
- );
-
- rpc_join.abort();
-}
-
-/// A missing relative folder names **where the reader looked**, not just what
-/// it was configured with — the second half of the fix. Reporting `docs` alone
-/// is what made openhuman#5830 cost an `lsof` of the running process to
-/// diagnose.
-#[tokio::test]
-async fn memory_sources_missing_relative_folder_reports_the_resolved_path() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let workspace = home.join("missing-folder-workspace");
- std::fs::create_dir_all(&workspace).expect("mkdir workspace");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace);
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- let add = rpc(
- &rpc_base,
- 910,
- "openhuman.memory_sources_add",
- json!({
- "kind": "folder",
- "label": "Absent",
- "path": "no-such-folder",
- "glob": "**/*.md",
- }),
- )
- .await;
- let source_id = ok(&add, "add absent folder source")
- .get("source")
- .and_then(|s| s.get("id"))
- .and_then(Value::as_str)
- .expect("source id")
- .to_string();
-
- let items_resp = rpc(
- &rpc_base,
- 911,
- "openhuman.memory_sources_list_items",
- json!({ "source_id": source_id }),
- )
- .await;
-
- // The whole response is searched rather than a specific error field: the
- // point is that the resolved root reaches the caller at all.
- let serialized = items_resp.to_string();
- assert!(
- serialized.contains("no-such-folder"),
- "the error must still name the configured path; got {items_resp}"
- );
- // The concrete resolved root, not just the phrase "resolved to". A reader
- // that still joined on the process CWD, or that emitted something generic
- // like "resolved to an unavailable location", would satisfy a phrase-only
- // check while keeping the exact diagnostic gap this test exists to close.
- let expected_resolved = workspace.join("no-such-folder");
- let expected_resolved = expected_resolved.to_string_lossy();
- assert!(
- serialized.contains("resolved to"),
- "a relative path's error must name where the reader looked; got {items_resp}"
- );
- assert!(
- serialized.contains(expected_resolved.as_ref()),
- "the resolved root must be the workspace one ({expected_resolved}); got {items_resp}"
- );
-
- rpc_join.abort();
-}
-
-/// Regression for #5801, fixed by #5808: `MemorySourceSync::run_source_sync` is
-/// a **defaulted** contract member whose default body answers
-/// `Unsupported(SourceSync)`. `ModuleMemoryProvider` inherited that default
-/// instead of bridging the call, so the user's "Sync now" button reported
-/// `unsupported capability: source_sync` on a build whose module could sync
-/// perfectly well — while the module's own scheduler, which never crosses this
-/// bridge, kept syncing fine.
-///
-/// A defaulted member that was never bridged is indistinguishable from a
-/// bridged one at compile time, which is exactly why the bug shipped. So this
-/// asserts on the **runtime** answer.
-///
-/// The discriminator: `binding::build` binds `module_provider` — i.e.
-/// `ModuleMemoryProvider` — whenever the `modules` feature is on, which it is by
-/// default, so this RPC really does reach the bridged member. No module artifact
-/// is installed in a test run, so a **bridged** member fails while trying to
-/// reach the module (a transport/availability failure), whereas an **unbridged**
-/// one refuses the capability outright before any transport is attempted. Those
-/// two failures are distinguishable in the message, and only the second is the
-/// regression.
-///
-/// Deliberately not asserted: that the sync *succeeds*. That would need a live
-/// module artifact and a network fetch, which this lane must not depend on.
-/// The bug was never "sync returns the wrong data" — it was "the call is
-/// refused before it is attempted", and that is what this pins.
-#[tokio::test]
-async fn sources_sync_dispatches_to_the_module_rather_than_refusing_the_capability() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let notes_dir = home.join("sync-dispatch-notes");
- std::fs::create_dir_all(&notes_dir).expect("mkdir sync-dispatch-notes");
- std::fs::write(notes_dir.join("note.md"), "# Note\n\nBody.\n").expect("write note.md");
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- let add = rpc(
- &rpc_base,
- 901,
- "openhuman.memory_sources_add",
- json!({
- "kind": "folder",
- "label": "Sync Dispatch Fixture",
- "path": notes_dir.to_string_lossy(),
- "glob": "**/*.md",
- }),
- )
- .await;
- let source = ok(&add, "add sync-dispatch source");
- let source = source.get("source").expect("source in add response");
- let source_id = source
- .get("id")
- .and_then(Value::as_str)
- .expect("source id")
- .to_string();
- // The enabled gate in `sync_rpc` returns before the driver is ever asked, so
- // a disabled source would make this test vacuous.
- assert_eq!(
- source.get("enabled"),
- Some(&json!(true)),
- "fixture must be enabled or sync_rpc short-circuits before reaching the driver"
- );
-
- let sync = rpc(
- &rpc_base,
- 902,
- "openhuman.memory_sources_sync",
- json!({ "source_id": source_id }),
- )
- .await;
-
- let message = sync
- .get("error")
- .and_then(|e| e.get("message"))
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string();
-
- assert!(
- !message.contains("unsupported capability"),
- "memory_sources_sync refused the capability instead of dispatching to the module \
- — `run_source_sync` is inheriting its defaulted `Unsupported` body again (#5801). \
- Got: {message}"
- );
- // Pin the specific family too, so a future unrelated `Unsupported` cannot
- // satisfy the assertion above by accident.
- assert!(
- !message.contains("source_sync"),
- "memory_sources_sync named the source_sync capability as unsupported (#5801). \
- Got: {message}"
- );
- // The OTHER way the call can be refused before dispatch, and the one the two
- // assertions above cannot see. `sync_rpc` resolves
- // `binding.provider().as_source_sync()` and bails with
- //
- // the bound memory driver '<id>' does not serve source sync
- //
- // (`memory/sources/rpc_part_01.rs:560-564`) when the capability is absent.
- // That string carries "source sync" with a SPACE — so it contains neither
- // "unsupported capability" nor the underscored "source_sync", and both
- // assertions above pass while `run_source_sync` was never reached. Codex
- // caught this on #5973; without it the test is green for the exact
- // regression it exists to catch, one layer up from the defaulted body.
- assert!(
- !message.contains("does not serve source sync"),
- "memory_sources_sync was refused host-side: the bound provider does not expose \
- SourceSync at all, so the bridged member was never reached. This is the same \
- class of failure as #5801, one layer up. Got: {message}"
- );
-
- // openhuman#6257: whatever the run's outcome, it leaves a Sync History row.
- // A sync that reached the driver and recorded nothing is how Brain › Sync ›
- // Sync History stayed empty after every manual sync.
- //
- // The host's run log is read directly, not only through the history RPC.
- // The module can fault inside the sync itself (the call above then answers
- // `ModuleUnavailable`), and a faulted driver cannot serve its own audit log
- // either, so through the RPC alone the row would be unobservable in exactly
- // the run that failed. `write_config` seeds the pre-login `users/local`
- // directory, whose workspace this core resolves.
- let run_log = openhuman_home
- .join("users")
- .join("local")
- .join("workspace")
- .join("state")
- .join("memory_sync_runs.jsonl");
- let run_log_text = std::fs::read_to_string(&run_log).unwrap_or_else(|e| {
- panic!(
- "a manual sync must write the host run log at {}: {e}. Sync answered: {sync}",
- run_log.display()
- )
- });
- let rows: Vec<Value> = run_log_text
- .lines()
- .filter_map(|line| serde_json::from_str::<Value>(line).ok())
- .filter(|row| row.get("source_id").and_then(Value::as_str) == Some(source_id.as_str()))
- .collect();
- // Exactly one: a run recorded twice would read as two syncs in the history.
- let [row] = rows.as_slice() else {
- panic!(
- "one manual sync must leave exactly one run row for its source, success or \
- failure; found {}. Sync answered: {sync}. Log: {run_log_text}",
- rows.len()
- );
- };
- assert_eq!(
- row.get("success").and_then(Value::as_bool),
- Some(sync.get("error").is_none()),
- "the row must carry the run's outcome. Sync answered: {sync}. Row: {row}"
- );
-
- // And through the RPC the panel reads, whenever the driver can serve its
- // half. The host's half must always read: only the driver may refuse.
- let history = rpc(
- &rpc_base,
- 904,
- "openhuman.memory_sources_sync_audit_log",
- json!({}),
- )
- .await;
- match history.get("error") {
- None => {
- let history = ok(&history, "sync history after a manual sync");
- let entries = history
- .get("entries")
- .and_then(Value::as_array)
- .expect("entries array in the sync history");
- let named = entries
- .iter()
- .filter(|row| {
- row.get("source_id").and_then(Value::as_str) == Some(source_id.as_str())
- })
- .count();
- assert_eq!(
- named, 1,
- "the history must include the manual sync's row, once. History: {entries:?}"
- );
- }
- Some(history_error) => {
- let history_message = history_error
- .get("message")
- .and_then(Value::as_str)
- .unwrap_or_default();
- assert!(
- history_message.contains("sync audit log:")
- && !history_message.contains("sync run log:"),
- "only the driver's audit log may be unreadable here; the host's run log \
- must always read. Got: {history_error}"
- );
- }
- }
-
- let _ = rpc(
- &rpc_base,
- 903,
- "openhuman.memory_sources_remove",
- json!({ "id": source_id }),
- )
- .await;
-
- rpc_join.abort();
-}
-
-/// #5725 routed `reset_tree` and `flush_now` through the `MemoryProvider`
-/// contract (`Maintenance::reset_derived_index` / `flush_pending`) instead of
-/// reaching into the engine. Nothing exercised either afterwards: in the
-/// raw-coverage lane `"flush_now"` and `"reset_tree"` appear only as string
-/// literals fed to `memory::schema::schemas(...)` — a schema lookup — and in
-/// `worker_c_modules_e2e.rs` they sit in a 68-method loop whose helper
-/// (`assert_rpc_completed`) passes on an error response. So both paths could
-/// stop reaching a driver entirely and every lane would stay green.
-///
-/// This drives both RPCs for real and pins the routing: the bound driver must
-/// SERVE Maintenance and the call must reach it.
-///
-/// What is asserted is the host-side refusal, not success. `reset_tree_rpc` and
-/// `flush_now_rpc` each resolve `binding.provider().as_maintenance()` and bail
-/// with `"driver '<id>' does not serve Maintenance"` when the capability is
-/// absent — that message is produced *before* any driver call, so it is the one
-/// failure that proves the contract hop did not happen. A driver-side failure
-/// (no module artifact in this lane) is a different message and is fine here:
-/// it means the call was dispatched, which is the thing under test.
-///
-/// Deliberately NOT asserted: that rows were deleted or a flush was enqueued.
-/// Those need a live module artifact and a network fetch (see FINDING 1 in
-/// W3-test-findings.md), and a lane that must not depend on the network cannot
-/// honestly pin them.
-#[tokio::test]
-async fn tree_reset_and_flush_route_through_the_maintenance_contract() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let (rpc_base, rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- for (id, method) in [
- (921_i64, "openhuman.memory_tree_flush_now"),
- (922, "openhuman.memory_tree_reset_tree"),
- ] {
- let resp = rpc(&rpc_base, id, method, json!({})).await;
- let message = resp
- .get("error")
- .and_then(|e| e.get("message"))
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string();
-
- assert!(
- !message.contains("does not serve Maintenance"),
- "{method} never reached a driver: the bound provider does not serve the \
- Maintenance capability, so the contract hop #5725 introduced is not happening. \
- Got: {message}"
- );
- // A renamed or removed RPC must not read as success. The assertion above
- // only excludes one string, so an unknown method — whose message is
- // `unknown method: <name>` and contains no "does not serve Maintenance" —
- // would satisfy it while nothing was dispatched at all (Codex, #5973).
- assert!(
- !message.contains("unknown method"),
- "{method} is not a registered RPC any more, so this test was asserting \
- against a method that no longer exists. Got: {message}"
- );
- // And the response has to be one of the two shapes a dispatched call can
- // produce: a result, or a driver-side error. Anything else means the
- // request did not complete.
- assert!(
- resp.get("result").is_some() || resp.get("error").is_some(),
- "{method} returned neither a result nor an error, so nothing was dispatched: {resp}"
- );
- }
-
- rpc_join.abort();
-}
-
-// ── A2: `openhuman.memory_scheduler_override` ────────────────────────
-//
-// Gate controller `memory_scheduler_override` had zero references under
-// `tests/` or `app/test/` before this test.
-//
-// The scheduler gate's pauses (`mode = off`, signed-out, battery) exist to stop
-// background work the user did not ask for. This RPC is the sanctioned
-// exception for work they explicitly did — "process my memory now" — so the
-// bound on how long that exception lasts is the whole safety property
-// (openhuman#5935). `memory/ops/sync.rs` clamps it host-side:
-//
-// let seconds = seconds.unwrap_or(600).min(3600);
-//
-// and the handler reports back the value it *granted*, not the one that was
-// asked for. Two regressions are therefore invisible today: dropping the
-// `.min(3600)` opens an unbounded background-work window, and reporting the
-// requested rather than the granted value makes every surface that displays it
-// lie about when maintenance stops.
-//
-// This goes over JSON-RPC rather than calling the handler directly, because
-// with the `modules` feature on the call dispatches into the loaded tinymemory
-// module — the same boundary the rest of this file exercises. If the module is
-// unavailable the call fails loudly here rather than silently skipping.
-
-/// The clamp is a safety bound, so each case pins the exact granted value.
-///
-/// `None` → the 600 s default; a value under the ceiling passes through
-/// unchanged; a value over the ceiling is cut to 3600. The three expected
-/// values are mutually distinct, so no single constant satisfies all three.
-#[tokio::test]
-async fn scheduler_override_clamps_its_window_and_reports_the_granted_value() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
-
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
-
- write_config(&openhuman_home);
-
- let (rpc_base, _rpc_join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // (requested, granted) — `None` means the parameter is omitted entirely.
- let cases: [(Option<u64>, u64); 4] = [
- (None, 600), // default
- (Some(120), 120), // under the ceiling: untouched
- (Some(3600), 3600), // exactly the ceiling: untouched
- (Some(99_999), 3600), // over the ceiling: clamped
- ];
-
- for (index, (requested, granted)) in cases.into_iter().enumerate() {
- let params = match requested {
- Some(seconds) => json!({ "seconds": seconds }),
- None => json!({}),
- };
- let response = rpc(
- &rpc_base,
- 920 + index as i64,
- "openhuman.memory_scheduler_override",
- params,
- )
- .await;
- let result = ok(
- &response,
- &format!("memory_scheduler_override(requested={requested:?})"),
- );
-
- // The gate was actually opened — without this the `seconds` assertion
- // below could be satisfied by a handler that echoed a number and did
- // nothing, which is precisely the shape of the bug it guards against.
- assert_eq!(
- result.get("overridden"),
- Some(&json!(true)),
- "override(requested={requested:?}) did not report overridden=true — got {result}"
- );
-
- let reported = result
- .get("seconds")
- .and_then(Value::as_u64)
- .unwrap_or_else(|| panic!("no numeric `seconds` in {result}"));
- assert_eq!(
- reported, granted,
- "override(requested={requested:?}) must grant {granted}s and report that granted \
- value, not the requested one — got {reported}s. A ceiling that stops clamping \
- opens an unbounded background-maintenance window (openhuman#5935)."
- );
- }
-}
diff --git a/tests/in_process/memory_tree_health_e2e.rs b/tests/in_process/memory_tree_health_e2e.rs
deleted file mode 100644
index fab26c5c4d..0000000000
--- a/tests/in_process/memory_tree_health_e2e.rs
+++ /dev/null
@@ -1,708 +0,0 @@
-//! End-to-end cover for the `memory_tree` health and lifecycle controllers.
-//!
-//! # Why this target exists
-//!
-//! `memory_tree` reported **5/5, 100%** to
-//! `scripts/check-domain-e2e-coverage.mjs` while carrying **31** dispatchable
-//! controllers. Discovery read `const NAMESPACE` one file at a time, so it only
-//! saw the five declared in `memory/tree/retrieval/schemas.rs` — the other 26
-//! live in `memory/schema/{tree_operations,vault_and_pipeline}_schema.rs` and
-//! reach their `const` through `use super::*`. A namespace nobody measures is
-//! the same fail-open shape as a test filter that matches nothing, except this
-//! one had a green tick on it. The gate fix in the same change makes the real
-//! figure 24/31; the seven cases below are the gap it exposes.
-//!
-//! They live in their own target rather than under `tests/raw_coverage/`; the old
-//! `memory_goals_people_e2e.rs` fixture that also drove `memory_tree_*` was
-//! quarantined under #6382 and has been removed.
-//!
-//! # What is asserted, and what is not
-//!
-//! Every case here asserts a claim the handler makes about itself, not that a
-//! call returns 200. Where a claim needs state this harness cannot produce —
-//! a terminally failed job for `retry_failed` to requeue — the case asserts the
-//! cross-method invariant that IS reachable and says so in a comment, rather
-//! than asserting `0 == 0` and calling it coverage.
-
-use crate::env_guard::env_lock_async;
-use crate::env_guard::EnvVarGuard;
-use crate::memory_rpc::{ok, serve, write_config};
-use crate::rpc_auth::rpc_token;
-use std::path::Path;
-use std::sync::OnceLock;
-use std::time::Duration;
-
-use axum::http::header::AUTHORIZATION;
-use serde_json::{json, Value};
-use tempfile::tempdir;
-
-static TEST_HOME: OnceLock<tempfile::TempDir> = OnceLock::new();
-
-fn test_home() -> &'static Path {
- TEST_HOME
- .get_or_init(|| tempdir().expect("memory tree health tempdir"))
- .path()
-}
-
-async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
- let client = reqwest::Client::builder()
- .timeout(Duration::from_secs(30))
- .build()
- .expect("client");
- let body = json!({
- "jsonrpc": "2.0",
- "id": id,
- "method": method,
- "params": params,
- });
- let url = format!("{}/rpc", base.trim_end_matches('/'));
- let resp = client
- .post(&url)
- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))
- .json(&body)
- .send()
- .await
- .unwrap_or_else(|e| panic!("POST {url}: {e}"));
- assert!(
- resp.status().is_success(),
- "HTTP error {} for {method}",
- resp.status(),
- );
- resp.json::<Value>()
- .await
- .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))
-}
-
-// ── Tests ──────────────────────────────────
-
-/// Ingest one source under `home`, returning the chunk count written.
-async fn ingest_source(base: &str, id: i64, source_id: &str, body: &str) -> u64 {
- let response = rpc(
- base,
- id,
- "openhuman.memory_tree_ingest",
- json!({
- "source_kind": "document",
- "source_id": source_id,
- "owner": "user",
- "tags": ["memory_tree_health_e2e", "document"],
- "payload": { "provider": "memory_tree_health_e2e", "title": source_id, "body": body },
- }),
- )
- .await;
- ok(&response, &format!("ingest {source_id}"))
- .get("chunks_written")
- .and_then(Value::as_u64)
- .unwrap_or_else(|| panic!("ingest {source_id} must report chunks_written: {response}"))
-}
-
-/// Enough prose that chunking produces at least one chunk per source.
-fn body_for(source: &str) -> String {
- format!(
- "{source} is a durable note used by the memory tree health suite. \
- It repeats enough distinct sentences that the chunker has real content to seal. \
- The retention policy for {source} is tested by deleting it and observing that \
- every other source survives untouched. Structural recall over {source} must \
- continue to answer after its siblings are removed."
- )
-}
-
-/// `memory_tree.doctor` must agree with itself.
-///
-/// The handler's own schema states the invariant: `healthy` is
-/// "True when no stage is blocking (first_blocking_cause is null)". A doctor
-/// whose verdict and evidence disagree is worse than no doctor — it is the
-/// surface an operator trusts to decide whether memory is working, and the
-/// failure mode worth catching is a rewrite that always answers `healthy: true`
-/// while `first_blocking_cause` is populated. Asserting the two fields against
-/// each other catches that in either direction without needing to force a fault.
-#[tokio::test]
-async fn memory_tree_doctor_verdict_agrees_with_its_own_evidence() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- let response = rpc(&base, 500, "openhuman.memory_tree_doctor", json!({})).await;
- let doctor = ok(&response, "memory_tree_doctor");
-
- let healthy = doctor
- .get("healthy")
- .and_then(Value::as_bool)
- .unwrap_or_else(|| panic!("doctor must report `healthy`: {doctor}"));
- // A healthy doctor OMITS the key rather than serialising `null`
- // (`skip_serializing_if = "Option::is_none"`), so absent and null are the
- // same statement — "nothing is blocking". Treating them differently made
- // this case depend on whatever state the store happened to be in.
- let blocking = doctor
- .get("first_blocking_cause")
- .cloned()
- .unwrap_or(Value::Null);
-
- assert_eq!(
- healthy,
- blocking.is_null(),
- "`healthy` is defined as `first_blocking_cause is null`; the two disagree: {doctor}"
- );
-
- // The evidence must actually be there. An empty stage list would make the
- // verdict above true by vacuity whatever the pipeline was doing.
- let stages = doctor
- .get("stages")
- .and_then(Value::as_array)
- .unwrap_or_else(|| panic!("doctor must report a `stages` array: {doctor}"));
- assert!(
- !stages.is_empty(),
- "an empty `stages` array makes the verdict unfalsifiable: {doctor}"
- );
- for stage in stages {
- assert!(
- stage.get("stage").and_then(Value::as_str).is_some(),
- "every stage row must name its stage: {stage}"
- );
- assert!(
- stage.get("ok").and_then(Value::as_bool).is_some(),
- "every stage row must carry a boolean `ok`: {stage}"
- );
- }
-
- // And a blocking cause, when present, must be typed rather than bare prose:
- // the frontend routes remediation off `remediation_key`.
- if !blocking.is_null() {
- for field in ["code", "class", "remediation_key"] {
- assert!(
- blocking.get(field).is_some(),
- "a blocking cause must be typed and carry `{field}`: {blocking}"
- );
- }
- }
-
- // `counters` is what an operator reads next; a stage saying "not ok" with no
- // counters is a dead end.
- let counters = doctor
- .get("counters")
- .unwrap_or_else(|| panic!("doctor must report `counters`: {doctor}"));
- for field in ["total_chunks", "jobs_ready", "jobs_running", "jobs_failed"] {
- assert!(
- counters.get(field).and_then(Value::as_u64).is_some(),
- "counters must carry a numeric `{field}`: {counters}"
- );
- }
-
- rpc_join.abort();
-}
-
-/// `memory_tree.delete_source` must delete ONE source, not the neighbourhood.
-///
-/// Over-deletion is silent data loss: the call reports success either way, and
-/// the only difference is the sibling that is no longer there. So the assertion
-/// is on the survivor, not on the return value. Two sources are ingested, one is
-/// deleted, and the other must still be listed with its chunks intact.
-#[tokio::test]
-async fn memory_tree_delete_source_removes_only_the_named_source() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- let doomed = "memory_tree_health:doomed-source";
- let survivor = "memory_tree_health:surviving-source";
-
- let doomed_chunks = ingest_source(&base, 510, doomed, &body_for(doomed)).await;
- let survivor_chunks = ingest_source(&base, 511, survivor, &body_for(survivor)).await;
- assert!(
- doomed_chunks >= 1 && survivor_chunks >= 1,
- "both fixtures must write at least one chunk, or the deletion proves nothing \
- (doomed={doomed_chunks}, survivor={survivor_chunks})"
- );
-
- let deleted = rpc(
- &base,
- 512,
- "openhuman.memory_tree_delete_source",
- json!({ "source_id": doomed }),
- )
- .await;
- let deleted_result = ok(&deleted, "memory_tree_delete_source");
- assert_eq!(
- deleted_result.get("deleted").and_then(Value::as_bool),
- Some(true),
- "deleting a source that exists must report real work: {deleted_result}"
- );
- assert!(
- deleted_result
- .get("chunks_removed")
- .and_then(Value::as_u64)
- .is_some_and(|removed| removed >= 1),
- "deleting a source with chunks must remove at least one: {deleted_result}"
- );
-
- // THE POINT: the sibling survived.
- let listed = rpc(&base, 513, "openhuman.memory_tree_list_sources", json!({})).await;
- let sources = ok(&listed, "memory_tree_list_sources");
- let rendered = sources.to_string();
- assert!(
- rendered.contains(survivor),
- "deleting `{doomed}` must leave `{survivor}` in place; list was: {rendered}"
- );
- assert!(
- !rendered.contains(doomed),
- "the deleted source must be gone from list_sources; list was: {rendered}"
- );
-
- // Deleting an id that does not exist must be honest about doing nothing,
- // rather than reporting success and hiding a typo'd id from the caller.
- let absent = rpc(
- &base,
- 514,
- "openhuman.memory_tree_delete_source",
- json!({ "source_id": "memory_tree_health:never-ingested" }),
- )
- .await;
- let absent_result = ok(&absent, "memory_tree_delete_source (absent)");
- assert_eq!(
- absent_result.get("chunks_removed").and_then(Value::as_u64),
- Some(0),
- "deleting a source that was never ingested must remove nothing: {absent_result}"
- );
-
- rpc_join.abort();
-}
-
-/// `vault_health_check` and `pipeline_status` must not contradict each other.
-///
-/// Two health surfaces over one pipeline. They are read by different callers —
-/// onboarding reads the vault snapshot, the memory panel reads the pipeline —
-/// and nothing today stops them drifting apart. The invariant asserted here is
-/// the one an operator relies on: if `doctor` names a blocking cause, the
-/// pipeline must not simultaneously present itself as unblocked.
-#[tokio::test]
-async fn memory_tree_vault_and_pipeline_health_surfaces_agree() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- let vault = rpc(
- &base,
- 520,
- "openhuman.memory_tree_vault_health_check",
- json!({}),
- )
- .await;
- let vault_result = ok(&vault, "memory_tree_vault_health_check");
- assert!(
- vault_result.is_object(),
- "the vault snapshot must be an object, not a bare scalar: {vault_result}"
- );
-
- let pipeline = rpc(
- &base,
- 521,
- "openhuman.memory_tree_pipeline_status",
- json!({}),
- )
- .await;
- let pipeline_result = ok(&pipeline, "memory_tree_pipeline_status");
- assert!(
- pipeline_result.is_object(),
- "the pipeline snapshot must be an object: {pipeline_result}"
- );
-
- let doctor = ok(
- &rpc(&base, 522, "openhuman.memory_tree_doctor", json!({})).await,
- "memory_tree_doctor",
- );
- let blocked = !doctor
- .get("first_blocking_cause")
- .map(Value::is_null)
- .unwrap_or(true);
-
- if blocked {
- // A pipeline that calls itself healthy while the doctor is blocked is the
- // drift this case exists to catch.
- let pipeline_claims_health = pipeline_result
- .get("healthy")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- assert!(
- !pipeline_claims_health,
- "doctor reports a blocking cause ({:?}) while pipeline_status reports healthy: {pipeline_result}",
- doctor.get("first_blocking_cause")
- );
- }
-
- rpc_join.abort();
-}
-
-/// `memory_tree.retry_failed` must report what it requeued, and not invent work.
-///
-/// The honest limit of this case, stated rather than hidden: this harness has no
-/// way to force a terminally failed `mem_tree_jobs` row, so it cannot prove the
-/// requeue path moves a real job. What it CAN prove is the cross-method
-/// invariant — `requeued` must never exceed the `jobs_failed` the doctor counted
-/// a moment earlier, and a second call with nothing left to requeue must report
-/// zero. A handler that returns an invented non-zero count, or that counts the
-/// whole job table rather than the failed rows, fails both.
-#[tokio::test]
-async fn memory_tree_retry_failed_never_requeues_more_than_had_failed() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- let before = ok(
- &rpc(&base, 530, "openhuman.memory_tree_doctor", json!({})).await,
- "memory_tree_doctor (before retry)",
- );
- let failed_before = before
- .get("counters")
- .and_then(|counters| counters.get("jobs_failed"))
- .and_then(Value::as_u64)
- .unwrap_or_else(|| panic!("doctor must count jobs_failed: {before}"));
-
- let retried = rpc(&base, 531, "openhuman.memory_tree_retry_failed", json!({})).await;
- let retried_result = ok(&retried, "memory_tree_retry_failed");
- let requeued = retried_result
- .get("requeued")
- .and_then(Value::as_u64)
- .unwrap_or_else(|| panic!("retry_failed must report `requeued`: {retried_result}"));
-
- assert!(
- requeued <= failed_before,
- "retry_failed requeued {requeued} jobs but the doctor counted only {failed_before} failed; \
- it must requeue failed rows, not the whole job table"
- );
-
- // Nothing is left failed after a requeue, so a second call must be a no-op.
- // A handler that re-counts the same rows every time reports non-zero forever.
- let again = rpc(&base, 532, "openhuman.memory_tree_retry_failed", json!({})).await;
- assert_eq!(
- ok(&again, "memory_tree_retry_failed (second call)")
- .get("requeued")
- .and_then(Value::as_u64),
- Some(0),
- "a second retry_failed with nothing left to requeue must report 0: {again}"
- );
-
- rpc_join.abort();
-}
-
-/// `flush_source` must seal the scope it was given, and echo that scope back.
-///
-/// The echo is the assertable half: `tree_scope` is documented as "Echo of the
-/// source scope", so a handler that flushes a different scope than it was asked
-/// to — or silently falls back to a global flush — shows up as a mismatch.
-#[tokio::test]
-async fn memory_tree_flush_source_seals_only_the_scope_it_was_given() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- let scope = "memory_tree_health:flush-scope";
- let chunks = ingest_source(&base, 540, scope, &body_for(scope)).await;
- assert!(
- chunks >= 1,
- "the fixture must write a chunk, or there is nothing to seal"
- );
-
- let flushed = rpc(
- &base,
- 541,
- "openhuman.memory_tree_flush_source",
- json!({ "source_scope": scope }),
- )
- .await;
- let flushed_result = ok(&flushed, "memory_tree_flush_source");
-
- assert_eq!(
- flushed_result.get("tree_scope").and_then(Value::as_str),
- Some(scope),
- "flush_source must echo back the scope it sealed, not a different one: {flushed_result}"
- );
- assert!(
- flushed_result
- .get("seals_fired")
- .and_then(Value::as_u64)
- .is_some(),
- "flush_source must report how many seal cascades fired: {flushed_result}"
- );
-
- rpc_join.abort();
-}
-
-/// `backfill_connector_trees` with `dry_run` must not mutate.
-///
-/// A dry run that writes is the worst kind of defect in a backfill: the operator
-/// ran it precisely to find out what WOULD happen. The chunk total before and
-/// after is the observable that proves it, and it is read from `doctor.counters`
-/// rather than from the backfill's own return value, so the check does not
-/// depend on the code under test telling the truth about itself.
-#[tokio::test]
-async fn memory_tree_backfill_dry_run_reports_without_writing() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- let source = "memory_tree_health:backfill-source";
- assert!(
- ingest_source(&base, 550, source, &body_for(source)).await >= 1,
- "the fixture must write a chunk, or an unchanged total proves nothing"
- );
-
- let chunks_of = |doctor: &Value| -> u64 {
- doctor
- .get("counters")
- .and_then(|counters| counters.get("total_chunks"))
- .and_then(Value::as_u64)
- .unwrap_or_else(|| panic!("doctor must count total_chunks: {doctor}"))
- };
-
- let before = chunks_of(&ok(
- &rpc(&base, 551, "openhuman.memory_tree_doctor", json!({})).await,
- "doctor (before dry run)",
- ));
- assert!(
- before >= 1,
- "the tree must hold at least one chunk before the dry run, or an unchanged \
- total is unfalsifiable"
- );
-
- let dry = rpc(
- &base,
- 552,
- "openhuman.memory_tree_backfill_connector_trees",
- json!({ "dry_run": true }),
- )
- .await;
- ok(&dry, "memory_tree_backfill_connector_trees (dry run)");
-
- let after = chunks_of(&ok(
- &rpc(&base, 553, "openhuman.memory_tree_doctor", json!({})).await,
- "doctor (after dry run)",
- ));
- assert_eq!(
- after, before,
- "a dry run must not change the chunk total ({before} -> {after})"
- );
-
- rpc_join.abort();
-}
-
-/// `smart_walk` must answer a query over content that was actually ingested.
-///
-/// The retrieval half of the tree. The assertion is that a query drawn from the
-/// ingested body reaches a result set, and that the shape is the documented one
-/// — not that a specific chunk ranks first, which would pin the ranker rather
-/// than the contract.
-#[tokio::test]
-async fn memory_tree_smart_walk_answers_over_ingested_content() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- let source = "memory_tree_health:smart-walk-source";
- assert!(
- ingest_source(&base, 560, source, &body_for(source)).await >= 1,
- "the fixture must write a chunk, or the walk has nothing to reach"
- );
-
- let walked = rpc(
- &base,
- 561,
- "openhuman.memory_tree_smart_walk",
- json!({ "query": "retention policy", "limit": 5 }),
- )
- .await;
- let result = ok(&walked, "memory_tree_smart_walk");
- assert!(
- result.is_object() || result.is_array(),
- "smart_walk must return a structured result set: {result}"
- );
-
- // `limit` is the caller's bound; a walk that ignores it can flood a prompt.
- if let Some(items) = result
- .get("results")
- .or_else(|| result.get("chunks"))
- .and_then(Value::as_array)
- {
- assert!(
- items.len() <= 5,
- "smart_walk returned {} items for limit=5: {result}",
- items.len()
- );
- }
-
- rpc_join.abort();
-}
-
-/// `memory.namespace_summaries` — the total must equal the parts, and the parts
-/// must be the counts that were actually written.
-///
-/// Its own description calls this "the verification surface for whether a sync's
-/// items actually landed", which makes a wrong total worse than no total: it
-/// vindicates a broken sync. `memory/ops/documents.rs` computes
-/// `total_documents` as `namespaces.iter().map(|n| n.count).sum()`.
-///
-/// `total == sum` alone is too weak — an all-zero response satisfies it, and so
-/// does a handler that echoes one row's count into every row. So this seeds two
-/// namespaces with **different non-zero counts** and asserts each one exactly.
-/// Two distinct values is what rules out the echo; a non-zero fixture is what
-/// rules out the empty store. (Credit to the parallel `memory_roundtrip_e2e`
-/// work for the distinct-counts argument.)
-///
-/// This is the **controller** test, over JSON-RPC. `tests/memory_roundtrip_e2e.rs`
-/// covers the same ground one layer down by calling
-/// `openhuman_core::memory::ops::memory_namespace_summaries` directly. Both are
-/// worth having and only this one exercises dispatch, parameter decoding and the
-/// `Outcome` envelope.
-#[tokio::test]
-async fn memory_namespace_summaries_counts_each_namespace_it_was_given() {
- let _guard = env_lock_async().await;
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- write_config(&openhuman_home);
- let _home_guard = EnvVarGuard::set_to_path("HOME", home);
- let _ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let _backend = EnvVarGuard::unset("BACKEND_URL");
- let _vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- let (base, rpc_join) = serve().await;
-
- // Distinct counts on purpose: 2 and 3, so a handler that reports one row's
- // count for every row cannot pass.
- let small = "memory_tree_health_summaries_small";
- let large = "memory_tree_health_summaries_large";
- let seeded: [(&str, usize); 2] = [(small, 2), (large, 3)];
-
- // Start from a known floor so a leftover store cannot make the assertions
- // pass for the wrong reason.
- for (namespace, _) in seeded {
- rpc(
- &base,
- 580,
- "openhuman.memory_clear_namespace",
- json!({ "namespace": namespace }),
- )
- .await;
- }
-
- let mut id = 581;
- for (namespace, count) in seeded {
- for index in 0..count {
- let response = rpc(
- &base,
- id,
- "openhuman.memory_doc_put",
- json!({
- "namespace": namespace,
- "key": format!("{namespace}-doc-{index}"),
- "title": format!("{namespace} document {index}"),
- "content": format!(
- "Document {index} of namespace {namespace}, written by the \
- namespace-summaries e2e case so the counts below are ones \
- this test put there itself."
- ),
- }),
- )
- .await;
- ok(&response, &format!("memory_doc_put {namespace}#{index}"));
- id += 1;
- }
- }
-
- let response = rpc(
- &base,
- 600,
- "openhuman.memory_namespace_summaries",
- json!({}),
- )
- .await;
- let summaries = ok(&response, "memory_namespace_summaries");
-
- let namespaces = summaries
- .get("namespaces")
- .and_then(Value::as_array)
- .unwrap_or_else(|| panic!("summaries must carry a `namespaces` array: {summaries}"))
- .clone();
- let total = summaries
- .get("total_documents")
- .and_then(Value::as_u64)
- .unwrap_or_else(|| panic!("summaries must carry `total_documents`: {summaries}"));
-
- let count_for = |wanted: &str| -> u64 {
- namespaces
- .iter()
- .find(|entry| entry.get("namespace").and_then(Value::as_str) == Some(wanted))
- .and_then(|entry| entry.get("count").and_then(Value::as_u64))
- .unwrap_or_else(|| panic!("namespace `{wanted}` must appear with a count: {summaries}"))
- };
-
- // Each namespace reports the count IT was given, not the other one's.
- for (namespace, expected) in seeded {
- assert_eq!(
- count_for(namespace),
- expected as u64,
- "namespace `{namespace}` must report the {expected} documents written to it: {summaries}"
- );
- }
-
- // And the headline figure is the sum of the rows, not an independent tally
- // that can drift from them.
- let summed: u64 = namespaces
- .iter()
- .map(|entry| {
- entry
- .get("count")
- .and_then(Value::as_u64)
- .unwrap_or_else(|| panic!("every namespace row must carry a count: {entry}"))
- })
- .sum();
- assert_eq!(
- total, summed,
- "total_documents ({total}) must equal the sum of per-namespace counts ({summed}): {summaries}"
- );
- assert!(
- total >= 5,
- "the five seeded documents must be included in the total: {summaries}"
- );
-
- rpc_join.abort();
-}
diff --git a/tests/in_process/tree_summarizer_e2e.rs b/tests/in_process/tree_summarizer_e2e.rs
deleted file mode 100644
index 515c22069e..0000000000
--- a/tests/in_process/tree_summarizer_e2e.rs
+++ /dev/null
@@ -1,236 +0,0 @@
-//! E2E coverage for the `tree_summarizer` ingestion buffer.
-//!
-//! Gate controller `tree_summarizer_ingest` had zero references under `tests/`
-//! or `app/test/` before this target.
-//!
-//! The claim under test is a **boundary contract**, which is why this is an RI
-//! suite rather than a unit test. `memory/tree/tree_runtime/ops.rs` defaults the
-//! timestamp host-side, deliberately, and says why:
-//!
-//! // Defaulted here rather than driver-side, exactly as before: the reply
-//! // echoes the instant the content was filed under, and a timestamp the
-//! // driver resolved would disagree with the one reported here by however
-//! // long the call took to cross.
-//!
-//! If that defaulting ever migrates across the bus, the reply starts reporting
-//! a different instant than the one the content was actually filed under. The
-//! field stays present and stays plausible, so every downstream ordering or
-//! dedupe decision keyed on that echo drifts silently. Nothing catches it
-//! today.
-//!
-//! Run with: `cargo test -p openhuman-cli --test in_process_all`
-
-use crate::env_guard::env_lock_async;
-use crate::env_guard::EnvVarGuard;
-use crate::memory_rpc::{serve, write_config};
-use crate::rpc_auth::rpc_token;
-use std::path::{Path, PathBuf};
-use std::sync::OnceLock;
-use std::time::Duration;
-
-use axum::http::header::AUTHORIZATION;
-use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
-use serde_json::{json, Value};
-use tempfile::TempDir;
-
-const NAMESPACE: &str = "tree-summarizer-e2e";
-
-static TEST_HOME: OnceLock<TempDir> = OnceLock::new();
-
-fn test_home() -> &'static Path {
- TEST_HOME
- .get_or_init(|| tempfile::tempdir().expect("tree summarizer tempdir"))
- .path()
-}
-
-async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
- let client = reqwest::Client::builder()
- .timeout(Duration::from_secs(30))
- .build()
- .expect("client");
- let url = format!("{}/rpc", base.trim_end_matches('/'));
- let resp = client
- .post(&url)
- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))
- .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))
- .send()
- .await
- .unwrap_or_else(|e| panic!("POST {url}: {e}"));
- assert!(
- resp.status().is_success(),
- "HTTP error {} for {method}",
- resp.status()
- );
- resp.json::<Value>()
- .await
- .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))
-}
-
-fn ok(v: &Value, ctx: &str) -> Value {
- if let Some(err) = v.get("error") {
- panic!("{ctx}: JSON-RPC error: {err}");
- }
- let outer = v
- .get("result")
- .unwrap_or_else(|| panic!("{ctx}: missing result: {v}"));
- // Outcome wraps its payload under an inner "result" alongside "logs".
- outer
- .get("result")
- .cloned()
- .unwrap_or_else(|| outer.clone())
-}
-
-fn setup() -> (EnvVarGuard, EnvVarGuard, EnvVarGuard, EnvVarGuard, PathBuf) {
- let home = test_home();
- let openhuman_home = home.join(".openhuman");
- let home_guard = EnvVarGuard::set_to_path("HOME", home);
- let ws = EnvVarGuard::unset("OPENHUMAN_WORKSPACE");
- let backend = EnvVarGuard::unset("BACKEND_URL");
- let vite = EnvVarGuard::unset("VITE_BACKEND_URL");
- write_config(&openhuman_home);
- (home_guard, ws, backend, vite, openhuman_home)
-}
-
-// ── Tests ────────────────────────────────────────────────────────────
-
-/// An explicit `timestamp` is echoed back exactly, not replaced by `now()`.
-///
-/// The fixture instant is fixed and far in the past, so a handler that resolved
-/// its own `now()` could not satisfy this by coincidence.
-#[tokio::test]
-async fn ingest_echoes_the_caller_supplied_timestamp() {
- let _lock = env_lock_async().await;
- let (_home, _ws, _backend, _vite, _oh) = setup();
-
- let (rpc_base, _join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // 2021-03-04T05:06:07Z — fixed, and years away from any plausible `now()`.
- let fixed: DateTime<Utc> = Utc
- .with_ymd_and_hms(2021, 3, 4, 5, 6, 7)
- .single()
- .expect("fixed fixture instant");
- let fixed_rfc3339 = fixed.to_rfc3339_opts(SecondsFormat::Secs, true);
-
- let before = Utc::now();
- let response = rpc(
- &rpc_base,
- 401,
- "openhuman.tree_summarizer_ingest",
- json!({
- "namespace": NAMESPACE,
- "content": "Engineering note filed under a caller-supplied instant.",
- "timestamp": fixed_rfc3339,
- }),
- )
- .await;
- let result = ok(&response, "tree_summarizer_ingest with explicit timestamp");
-
- // Fixture guard: if the write did not happen there is nothing to assert
- // about, and `buffered` is the handler's own statement that it did.
- assert_eq!(
- result.get("buffered"),
- Some(&json!(true)),
- "ingest did not report buffered=true — got {result}"
- );
-
- let echoed = result
- .get("timestamp")
- .and_then(Value::as_str)
- .unwrap_or_else(|| panic!("no `timestamp` in {result}"));
- let echoed: DateTime<Utc> = DateTime::parse_from_rfc3339(echoed)
- .unwrap_or_else(|e| panic!("unparseable timestamp {echoed:?}: {e}"))
- .with_timezone(&Utc);
-
- assert_eq!(
- echoed, fixed,
- "ingest must echo the instant the caller filed the content under ({fixed}), not one it \
- resolved itself. A driver-side default would disagree with the reply by however long the \
- call took to cross (memory/tree/tree_runtime/ops.rs)."
- );
- // Stated separately so a regression that returns `now()` names itself,
- // rather than only showing two timestamps that happen to differ.
- assert!(
- echoed < before,
- "echoed timestamp {echoed} is not the fixture instant but a value at or after this \
- test started ({before}) — the handler resolved its own clock"
- );
-
- assert_eq!(
- result.get("namespace"),
- Some(&json!(NAMESPACE)),
- "ingest must echo the namespace it filed under — got {result}"
- );
- assert_eq!(
- result.get("has_metadata"),
- Some(&json!(false)),
- "no metadata was sent, so has_metadata must be false — got {result}"
- );
- let path = result
- .get("path")
- .and_then(Value::as_str)
- .unwrap_or_else(|| panic!("no `path` in {result}"));
- assert!(
- !path.is_empty(),
- "ingest must report the buffer path the driver wrote"
- );
-}
-
-/// With no `timestamp`, the handler resolves one itself and it lands inside the
-/// window this test brackets.
-///
-/// Bracketing both sides is what makes this non-vacuous: a handler returning a
-/// constant, a zero instant or an unparseable string fails.
-#[tokio::test]
-async fn ingest_without_a_timestamp_files_under_the_host_clock() {
- let _lock = env_lock_async().await;
- let (_home, _ws, _backend, _vite, _oh) = setup();
-
- let (rpc_base, _join) = serve().await;
- tokio::time::sleep(Duration::from_millis(100)).await;
-
- // One second of slack each side: the assertion is "the host clock", not a
- // claim about RPC latency.
- let before = Utc::now() - chrono::Duration::seconds(1);
- let response = rpc(
- &rpc_base,
- 402,
- "openhuman.tree_summarizer_ingest",
- json!({
- "namespace": NAMESPACE,
- "content": "Engineering note filed without an explicit instant.",
- "metadata": { "source": "tree-summarizer-e2e" },
- }),
- )
- .await;
- let after = Utc::now() + chrono::Duration::seconds(1);
- let result = ok(&response, "tree_summarizer_ingest without timestamp");
-
- assert_eq!(
- result.get("buffered"),
- Some(&json!(true)),
- "ingest did not report buffered=true — got {result}"
- );
-
- let echoed = result
- .get("timestamp")
- .and_then(Value::as_str)
- .unwrap_or_else(|| panic!("no `timestamp` in {result}"));
- let echoed: DateTime<Utc> = DateTime::parse_from_rfc3339(echoed)
- .unwrap_or_else(|e| panic!("unparseable timestamp {echoed:?}: {e}"))
- .with_timezone(&Utc);
-
- assert!(
- echoed >= before && echoed <= after,
- "an omitted timestamp must be defaulted to the host clock; {echoed} is outside the \
- window [{before}, {after}] this call was made in"
- );
-
- // The metadata this call *did* send must be reflected, so the two tests
- // together pin both branches of `has_metadata`.
- assert_eq!(
- result.get("has_metadata"),
- Some(&json!(true)),
- "metadata was sent, so has_metadata must be true — got {result}"
- );
-}
diff --git a/tests/in_process/worker_c_modules_e2e.rs b/tests/in_process/worker_c_modules_e2e.rs
index 4f2cb61178..4d53d73a9a 100644
--- a/tests/in_process/worker_c_modules_e2e.rs
+++ b/tests/in_process/worker_c_modules_e2e.rs
@@ -726,7 +726,7 @@ async fn threads_remaining_controller_paths_round_trip() {
#[tokio::test]
async fn memory_v2_controller_surface_is_reachable() {
- let _lock = env_lock();
+ let _lock = env_lock_async().await;
let harness = setup().await;
let methods = [
diff --git a/tests/support/memory_rpc.rs b/tests/support/memory_rpc.rs
deleted file mode 100644
index be33ac0598..0000000000
--- a/tests/support/memory_rpc.rs
+++ /dev/null
@@ -1,94 +0,0 @@
-//! Boilerplate shared by the memory RPC suites that serve the core router
-//! in-process (`memory_sources_e2e`, `memory_tree_health_e2e`,
-//! `tree_summarizer_e2e`): the memory-module policy seam, a minimal workspace
-//! config, a served router with the memory module settled, and the
-//! `Outcome`-unwrapping `ok`.
-//!
-//! Declare it at the root of an aggregated target next to `rpc_auth` and
-//! `memory_module`.
-
-#![allow(dead_code)]
-
-use std::path::Path;
-use std::sync::{Arc, OnceLock};
-
-use openhuman_rpc::server::build_core_http_router;
-use serde_json::Value;
-
-use crate::memory_module;
-use crate::rpc_auth::ensure_rpc_auth;
-
-static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();
-
-/// Install the memory module's policy once per process, on a thread with a
-/// stack deep enough for the policy build (a default test stack overflows).
-pub fn ensure_memory_seams() {
- MEMORY_SEAMS_INIT.get_or_init(|| {
- std::thread::Builder::new()
- .name("memory-e2e-seams".to_string())
- .stack_size(8 * 1024 * 1024)
- .spawn(|| {
- let config = Arc::new(openhuman_core::config::Config::default());
- #[cfg(feature = "modules")]
- openhuman_core::modules::memory::set_modules_policy(config);
- #[cfg(not(feature = "modules"))]
- drop(config);
- })
- .expect("spawn memory seam installer")
- .join()
- .expect("memory seam installer panicked");
- });
-}
-
-/// Write the minimal workspace config (plus the `users/local` copy) under `dir`.
-pub fn write_config(dir: &Path) {
- std::fs::create_dir_all(dir).expect("mkdir");
- let cfg = r#"
-default_model = "e2e-mock-model"
-default_temperature = 0.7
-
-[secrets]
-encrypt = false
-
-[memory_tree]
-embedding_strict = false
-"#;
- std::fs::write(dir.join("config.toml"), cfg).expect("write config");
-
- let user_dir = dir.join("users").join("local");
- std::fs::create_dir_all(&user_dir).expect("mkdir user dir");
- std::fs::write(user_dir.join("config.toml"), cfg).expect("write user config");
-}
-
-/// Serve the core router with the memory module loaded; returns the base URL.
-///
-/// Every flow reaches the memory module, so wait out its load: a test running
-/// in its own process would otherwise race it (see `memory_module`).
-pub async fn serve() -> (String, tokio::task::JoinHandle<Result<(), std::io::Error>>) {
- ensure_memory_seams();
- ensure_rpc_auth();
- memory_module::settle().await;
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
- .await
- .expect("bind");
- let addr = listener.local_addr().expect("addr");
- let handle =
- tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });
- (format!("http://{addr}"), handle)
-}
-
-/// The envelope's payload: `result.result` when the `Outcome` wraps one next to
-/// its `logs`, else `result`. Panics with `ctx` on a JSON-RPC error.
-pub fn ok(v: &Value, ctx: &str) -> Value {
- if let Some(err) = v.get("error") {
- panic!("{ctx}: JSON-RPC error: {err}");
- }
- let outer = v
- .get("result")
- .unwrap_or_else(|| panic!("{ctx}: missing result: {v}"));
- if let Some(inner) = outer.get("result") {
- inner.clone()
- } else {
- outer.clone()
- }
-}