The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(e2e): cover 42 untested RPC controllers across 9 namespaces\n\nCloses the W3 slice of the e2e coverage wave: `learning` (0/11),\n`memory_goals` (0/5), `people` (0/4), `tree_summarizer` (1/5),\n`session_db` (0/6), `session_import` (0/1), `tokenjuice` (6/8),\n`ai` (0/4) and `test_support` (0/5) all reach 100% on\n`scripts/check-domain-e2e-coverage.mjs`, taking the repo-wide count\nfrom 379 to 422 invoked controllers.\n\nThree new suites under `tests/raw_coverage/`, so they are modules of\nthe existing aggregated `raw_coverage_all` target rather than three\nnew binaries — no `Cargo.toml` edit, and the large `openhuman` rlib\nis linked once instead of three more times.\n\nEvery case boots the real axum JSON-RPC router and asserts on response\n*content*, with at least one failure path per namespace. Two hazards\nof the shared-process aggregate are handled explicitly: the env lock\nis the crate-wide `SHARED_ENV_LOCK` (a private lock isolates nothing\nwhen 77 suites share one process), and the RPC bearer is read back\nfrom `core::auth::get_rpc_token()` rather than assumed, because that\ntoken is a process-global `OnceLock` a sibling suite may seed first.\n\nFault-injected to prove the assertions bite. Six faults in one pass,\neach targeting a different case; exactly the six predicted tests\nfailed and nothing else, then `src/` was restored:\n\n - learning: let Dropped facets stay in the visible list\n - tree_summarizer: remove the cloud-summarization consent gate\n - people: always report `created: true` on resolve\n - artifacts: filter by thread after pagination\n - session_import: write the global marker on a dry run\n - tokenjuice: report a compactedBytes that does not describe `text`\n\nSix findings written up under `~/tinyhuman/bugs/`, none fixed here —\na test PR that also changes behaviour cannot be reviewed as either.\nThe two that matter most: nothing in `src/` ever calls\n`tinyagents_session::record_session_start`/`record_message`/\n`record_tool_call`, so the whole `session_db` namespace reads a table\nthe product never writes; and `test_support` is gated on\n`e2e-test-support`, which is in neither feature set, so those five\ncontrollers cannot be reached by any lane — the suite asserts the\nnegative contract (absent from `/schema`, unroutable) under the\nproduct features and carries the positive path behind the cfg.\n\nNo `src/` or `Cargo.toml` changes.\n
M3gA-Mind9f5b636147e2
diff --git a/tests/raw_coverage/learning_facets_e2e.rs b/tests/raw_coverage/learning_facets_e2e.rsnew file mode 100644index 0000000000..ea07cac16d--- /dev/null+++ b/tests/raw_coverage/learning_facets_e2e.rs@@ -0,0 +1,904 @@+//! JSON-RPC E2E coverage for the `learning` namespace — the eleven controllers+//! behind the user-profile facet cache.+//!+//! The arc these cases walk is the production one: real observations are pushed+//! into `learning::candidate::global()` (the same buffer+//! `learning::extract::heuristics`, `extract::signature` and+//! `learning::reflection` push into), `learning.rebuild_cache` runs the+//! stability detector over them, and every read/mutate controller is then driven+//! over the actual axum JSON-RPC router. Nothing is written to the facet store+//! behind the RPC surface's back.+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target, not a+//! target of its own — `build.rs` globs `tests/raw_coverage/` and generates the+//! `mod` list. Run with:+//! `~/tinyhuman/ci-slot.sh cargo test --test raw_coverage_all \+//! --features "$(bash scripts/ci/product-features.sh)" -- learning_facets`+//!+//! ## Two hazards this file is written around+//!+//! 1. **One process, ~77 suites.** The env lock is the crate-wide+//! `SHARED_ENV_LOCK`; a lock private to this module would isolate nothing.+//! The RPC bearer is read back from `core::auth::get_rpc_token()` rather than+//! assumed, because that token is a process-global `OnceLock` and a sibling+//! suite may have seeded it first.+//!+//! 2. **The facet store is shared.** The memory module host captures one+//! workspace per process, so these cases key everything on a unique+//! `E2E_KEY_*` slug and assert on *their own* rows — never on a global count.+//! `cache_stats` is asserted as "at least mine", and `reset_cache` is checked+//! by what happened to this suite's two facets, not by the totals.++use std::net::SocketAddr;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::TempDir;++use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;+use openhuman_core::openhuman::agent::learning::candidate::{+ self, CueFamily, EvidenceRef, FacetClass, LearningCandidate,+};+use openhuman_core::openhuman::config::Config;++/// Preferred bearer. Only the real one if this module wins the process-global+/// `OnceLock` race — send [`rpc_bearer`], never this.+const PREFERRED_RPC_TOKEN: &str = "learning-facets-e2e-token";++/// Facet keys this suite owns. Distinctive enough that a sibling suite (or a+/// leftover row in the shared store) can never be mistaken for one of them.+const PINNED_KEY: &str = "e2e_learning_pinned_slug";+const VOLATILE_KEY: &str = "e2e_learning_volatile_slug";++static AUTH_INIT: OnceLock<()> = OnceLock::new();+static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();++/// The crate-wide env lock — see the module docs.+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())+}++// ── Env isolation ─────────────────────────────────────────────────────────++struct EnvVarGuard {+ key: &'static str,+ old: Option<String>,+}++impl EnvVarGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, path.as_os_str());+ Self { key, old }+ }++ fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, value);+ Self { key, old }+ }++ fn unset(key: &'static str) -> Self {+ let old = std::env::var(key).ok();+ std::env::remove_var(key);+ Self { key, old }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+}++// ── Shared memory workspace ───────────────────────────────────────────────++/// The transport-only JSON-RPC router builds no core runtime context, so a+/// memory-backed route has no seams unless they are installed explicitly.+fn ensure_memory_seams() {+ MEMORY_SEAMS_INIT.get_or_init(|| {+ std::thread::Builder::new()+ .name("learning-facets-e2e-seams".to_string())+ .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);+ })+ .expect("spawn learning facets seam installer")+ .join()+ .expect("learning facets seam installer panicked");+ });+}++/// The one memory workspace every case in this module shares.+///+/// The module host captures a workspace **once per process** — the loaded+/// artifact takes its `workspace_dir` at load time and later policy calls are+/// ignored — while a per-case `TempDir` would be deleted the moment its case+/// returned, leaving every later read answering from a dead store. So this is+/// one leaked directory, published once, and every case points both its config+/// and `OPENHUMAN_WORKSPACE` at it. The path ends in `workspace` so+/// `resolve_config_dir_for_workspace` treats it as the workspace itself rather+/// than appending another segment.+fn learning_workspace() -> &'static Path {+ static WORKSPACE: OnceLock<PathBuf> = OnceLock::new();+ WORKSPACE.get_or_init(|| {+ let dir = TempDir::new().expect("learning workspace tempdir");+ let path = dir.path().join("workspace");+ std::fs::create_dir_all(&path).expect("create learning workspace");+ // Leaked on purpose: the module keeps this path for the process lifetime.+ std::mem::forget(dir);+ path+ })+}++/// A config whose workspace **and** config path are the shared ones.+///+/// `config_path` matters as much as `workspace_dir`: `Config::default()` names+/// the developer's real `~/.openhuman/config.toml`, and pointing it beside the+/// shared workspace is where `Config::load_or_init` resolves it from+/// `OPENHUMAN_WORKSPACE` too — so env-driven and config-driven paths agree.+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+}++fn write_min_config(config_path: &Path) {+ if let Some(parent) = config_path.parent() {+ std::fs::create_dir_all(parent).expect("create config dir");+ }+ let cfg = r#"api_url = "http://127.0.0.1:9"+default_model = "e2e-model"+default_temperature = 0.2++[secrets]+encrypt = false++[local_ai]+enabled = false++[memory_tree]+embedding_strict = false+"#;+ std::fs::write(config_path, cfg).expect("write config.toml");+ let _: Config = toml::from_str(cfg).expect("test config must match schema");+}++// ── Harness ───────────────────────────────────────────────────────────────++fn ensure_rpc_auth() {+ AUTH_INIT.get_or_init(|| {+ std::env::set_var(CORE_TOKEN_ENV_VAR, PREFERRED_RPC_TOKEN);+ let token_dir = std::env::temp_dir().join("openhuman-learning-facets-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+}++/// The bearer the running process actually validates — see the module docs.+fn rpc_bearer() -> &'static str {+ ensure_rpc_auth();+ openhuman_core::core::auth::get_rpc_token()+ .expect("the RPC token must be initialised before a request is signed")+}++struct Harness {+ _guards: Vec<EnvVarGuard>,+ workspace: PathBuf,+ rpc_base: String,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++async fn serve_rpc() -> (+ SocketAddr,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let join =+ tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });+ (addr, join)+}++async fn setup() -> Harness {+ ensure_memory_seams();+ let workspace = learning_workspace().to_path_buf();+ let config_path = workspace+ .parent()+ .expect("shared workspace has a parent")+ .join("config.toml");+ write_min_config(&config_path);++ let guards = vec![+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let (addr, join) = serve_rpc().await;+ Harness {+ _guards: guards,+ workspace,+ rpc_base: format!("http://{addr}"),+ join,+ }+}++async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("client");+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", rpc_bearer()))+ .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+}++/// The payload of a successful dispatch, unwrapping the `RpcOutcome`+/// `{ result, logs }` envelope when the handler produced one.+fn payload(value: &Value, context: &str) -> Value {+ if let Some(error) = value.get("error") {+ panic!("{context}: unexpected JSON-RPC error: {error}");+ }+ let outer = value+ .get("result")+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"));+ match outer.get("result") {+ Some(inner) => inner.clone(),+ None => outer.clone(),+ }+}++fn error_message(value: &Value, context: &str) -> String {+ value+ .get("error")+ .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}"))+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{context}: error object has no message: {value}"))+ .to_string()+}++// ── Candidate seeding ─────────────────────────────────────────────────────++fn now_secs() -> f64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs_f64()+}++/// Push `repeats` observations of one (class, key, value) into the global+/// candidate buffer — the same buffer the production extractors push into.+///+/// `Explicit` and a recent `observed_at` are chosen deliberately: the stability+/// formula is `Σ(weight × exp(-Δt/half_life) × ln(1 + evidence_count))` with a+/// ×2.0 multiplier for an explicit cue, so several fresh explicit observations+/// clear `TAU_PROMOTE` (1.5) and enter as `Active`. Anything weaker would enter+/// as `Provisional` or `Candidate` and the assertions below would be about the+/// thresholds rather than about the controllers.+fn seed_candidate(class: FacetClass, key: &str, value: &str, repeats: i64) {+ let buffer = candidate::global();+ for i in 0..repeats {+ buffer.push(LearningCandidate {+ class,+ key: key.to_string(),+ value: value.to_string(),+ cue_family: CueFamily::Explicit,+ evidence: EvidenceRef::Episodic { episodic_id: i + 1 },+ initial_confidence: 0.9,+ observed_at: now_secs(),+ });+ }+}++/// Find one facet by its full `class/key` in a `list_facets` / `cache_stats`+/// style array.+fn find_facet<'a>(facets: &'a [Value], full_key: &str) -> Option<&'a Value> {+ facets+ .iter()+ .find(|f| f.get("key").and_then(Value::as_str) == Some(full_key))+}++fn facets_of(payload: &Value, context: &str) -> Vec<Value> {+ payload+ .get("facets")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("{context}: expected a facets array: {payload}"))+ .clone()+}++// ── Tests ─────────────────────────────────────────────────────────────────++/// The full facet lifecycle over RPC: rebuild from observations → list → get →+/// update → pin → unpin → cache_stats → forget → reset.+///+/// One case rather than nine, because these controllers share one durable row+/// and splitting them would either re-seed nine times or make each case depend+/// on the previous one's leftovers — the state-leak the wave brief forbids.+#[tokio::test]+async fn learning_facet_lifecycle_from_rebuild_to_reset() {+ let _lock = env_lock();+ let harness = setup().await;++ // Drain anything a sibling suite left, so `rebuild` scores only these.+ let _ = candidate::global().drain();+ seed_candidate(FacetClass::Style, PINNED_KEY, "terse", 6);+ seed_candidate(FacetClass::Tooling, VOLATILE_KEY, "pnpm", 6);++ let pinned_full = format!("style/{PINNED_KEY}");+ let volatile_full = format!("tooling/{VOLATILE_KEY}");++ // ── rebuild_cache: the detector promotes both observations ──+ let rebuilt = rpc(+ &harness.rpc_base,+ 40_001,+ "openhuman.learning_rebuild_cache",+ json!({}),+ )+ .await;+ let rebuilt = payload(&rebuilt, "learning_rebuild_cache");+ for field in ["added", "evicted", "kept", "total_size"] {+ assert!(+ rebuilt.get(field).and_then(Value::as_u64).is_some(),+ "rebuild_cache must report {field}: {rebuilt}"+ );+ }+ assert!(+ rebuilt.get("added").and_then(Value::as_u64).unwrap_or(0) >= 2,+ "both seeded observations must be added as facets: {rebuilt}"+ );+ assert!(+ rebuilt+ .get("total_size")+ .and_then(Value::as_u64)+ .unwrap_or(0)+ >= 2,+ "the cache must hold at least the two seeded facets: {rebuilt}"+ );++ // ── list_facets: both are visible, with the value they were seeded with ──+ let listed = rpc(+ &harness.rpc_base,+ 40_002,+ "openhuman.learning_list_facets",+ json!({}),+ )+ .await;+ let listed = payload(&listed, "learning_list_facets");+ let facets = facets_of(&listed, "learning_list_facets");+ assert_eq!(+ listed.get("count").and_then(Value::as_u64),+ Some(facets.len() as u64),+ "count must agree with the array it summarises: {listed}"+ );+ let seeded = find_facet(&facets, &pinned_full)+ .unwrap_or_else(|| panic!("the seeded style facet must be listed: {listed}"));+ assert_eq!(seeded.get("value").and_then(Value::as_str), Some("terse"));+ assert_eq!(+ seeded.get("state").and_then(Value::as_str),+ Some("active"),+ "six fresh explicit cues clear TAU_PROMOTE: {seeded}"+ );+ assert_eq!(seeded.get("class").and_then(Value::as_str), Some("style"));+ assert!(+ seeded.get("stability").and_then(Value::as_f64).unwrap_or(0.0) > 0.0,+ "a promoted facet carries a positive stability: {seeded}"+ );+ assert!(+ find_facet(&facets, &volatile_full).is_some(),+ "the seeded tooling facet must be listed too: {listed}"+ );++ // ── list_facets(class=…): the filter narrows to one class ──+ let styled = rpc(+ &harness.rpc_base,+ 40_003,+ "openhuman.learning_list_facets",+ json!({ "class": "style" }),+ )+ .await;+ let styled = payload(&styled, "learning_list_facets style");+ let styled_facets = facets_of(&styled, "learning_list_facets style");+ assert!(+ find_facet(&styled_facets, &pinned_full).is_some(),+ "the style facet survives its own class filter: {styled}"+ );+ assert!(+ find_facet(&styled_facets, &volatile_full).is_none(),+ "a tooling facet must not appear under class=style: {styled}"+ );++ // ── get_facet: found, with the same value list reported ──+ let got = rpc(+ &harness.rpc_base,+ 40_004,+ "openhuman.learning_get_facet",+ json!({ "class": "style", "key": PINNED_KEY }),+ )+ .await;+ let got = payload(&got, "learning_get_facet");+ assert_eq!(got.get("found").and_then(Value::as_bool), Some(true));+ assert_eq!(+ got.get("facet")+ .and_then(|f| f.get("value"))+ .and_then(Value::as_str),+ Some("terse")+ );++ // ── update_facet: writes the new value AND pins, so it survives rebuilds ──+ let updated = rpc(+ &harness.rpc_base,+ 40_005,+ "openhuman.learning_update_facet",+ json!({ "class": "style", "key": PINNED_KEY, "value": "exhaustive" }),+ )+ .await;+ let updated = payload(&updated, "learning_update_facet");+ let updated_facet = updated+ .get("facet")+ .unwrap_or_else(|| panic!("update_facet returns the facet: {updated}"));+ assert_eq!(+ updated_facet.get("value").and_then(Value::as_str),+ Some("exhaustive"),+ "the new value must be persisted, not echoed: {updated}"+ );+ assert_eq!(+ updated_facet.get("user_state").and_then(Value::as_str),+ Some("pinned"),+ "an edit pins the facet so a later rebuild cannot revert it: {updated}"+ );++ // Re-read through a different controller to prove it was written, not echoed.+ let reread = rpc(+ &harness.rpc_base,+ 40_006,+ "openhuman.learning_get_facet",+ json!({ "class": "style", "key": PINNED_KEY }),+ )+ .await;+ assert_eq!(+ payload(&reread, "learning_get_facet after update")+ .get("facet")+ .and_then(|f| f.get("value"))+ .and_then(Value::as_str),+ Some("exhaustive")+ );++ // ── unpin then pin: user_state round-trips on the volatile facet ──+ let pinned = rpc(+ &harness.rpc_base,+ 40_007,+ "openhuman.learning_pin_facet",+ json!({ "class": "tooling", "key": VOLATILE_KEY }),+ )+ .await;+ assert_eq!(+ payload(&pinned, "learning_pin_facet")+ .get("facet")+ .and_then(|f| f.get("user_state"))+ .and_then(Value::as_str),+ Some("pinned")+ );++ let unpinned = rpc(+ &harness.rpc_base,+ 40_008,+ "openhuman.learning_unpin_facet",+ json!({ "class": "tooling", "key": VOLATILE_KEY }),+ )+ .await;+ assert_eq!(+ payload(&unpinned, "learning_unpin_facet")+ .get("facet")+ .and_then(|f| f.get("user_state"))+ .and_then(Value::as_str),+ Some("auto"),+ "unpin returns the facet to automatic lifecycle management"+ );++ // ── cache_stats: the aggregate sees this suite's rows ──+ let stats = rpc(+ &harness.rpc_base,+ 40_009,+ "openhuman.learning_cache_stats",+ json!({}),+ )+ .await;+ let stats = payload(&stats, "learning_cache_stats");+ let total = stats+ .get("total")+ .and_then(Value::as_u64)+ .unwrap_or_else(|| panic!("cache_stats must report a total: {stats}"));+ let by_state: u64 = ["active", "provisional", "candidate", "dropped"]+ .iter()+ .map(|k| stats.get(*k).and_then(Value::as_u64).unwrap_or(0))+ .sum();+ assert_eq!(+ total, by_state,+ "the per-state counts must partition the total: {stats}"+ );+ assert!(total >= 2, "both seeded facets are counted: {stats}");+ assert!(+ stats+ .get("by_class")+ .and_then(|c| c.get("style"))+ .and_then(Value::as_u64)+ .unwrap_or(0)+ >= 1,+ "by_class must attribute the style facet: {stats}"+ );++ // ── forget_facet: drops the volatile one out of the visible list ──+ let forgotten = rpc(+ &harness.rpc_base,+ 40_010,+ "openhuman.learning_forget_facet",+ json!({ "class": "tooling", "key": VOLATILE_KEY }),+ )+ .await;+ let forgotten = payload(&forgotten, "learning_forget_facet");+ let forgotten_facet = forgotten+ .get("facet")+ .unwrap_or_else(|| panic!("forget_facet returns the facet: {forgotten}"));+ assert_eq!(+ forgotten_facet.get("state").and_then(Value::as_str),+ Some("dropped")+ );+ assert_eq!(+ forgotten_facet.get("user_state").and_then(Value::as_str),+ Some("forgotten"),+ "forget must record the user's intent so a rebuild cannot resurface it"+ );++ let after_forget = rpc(+ &harness.rpc_base,+ 40_011,+ "openhuman.learning_list_facets",+ json!({}),+ )+ .await;+ let after_forget = facets_of(+ &payload(&after_forget, "learning_list_facets after forget"),+ "list after forget",+ );+ assert!(+ find_facet(&after_forget, &volatile_full).is_none(),+ "a dropped facet must leave the user-visible list"+ );+ assert!(+ find_facet(&after_forget, &pinned_full).is_some(),+ "forgetting one facet must not touch the other"+ );++ // ── reset_cache: clears non-pinned rows, preserves pinned ones ──+ let reset = rpc(+ &harness.rpc_base,+ 40_012,+ "openhuman.learning_reset_cache",+ json!({}),+ )+ .await;+ let reset = payload(&reset, "learning_reset_cache");+ assert!(+ reset.get("deleted").and_then(Value::as_u64).is_some(),+ "reset_cache must report a delete count: {reset}"+ );+ assert!(+ reset+ .get("pinned_preserved")+ .and_then(Value::as_u64)+ .unwrap_or(0)+ >= 1,+ "the pinned facet must be counted as preserved: {reset}"+ );++ let survivor = rpc(+ &harness.rpc_base,+ 40_013,+ "openhuman.learning_get_facet",+ json!({ "class": "style", "key": PINNED_KEY }),+ )+ .await;+ let survivor = payload(&survivor, "learning_get_facet after reset");+ assert_eq!(+ survivor.get("found").and_then(Value::as_bool),+ Some(true),+ "reset_cache must not delete a pinned facet: {survivor}"+ );+ assert_eq!(+ survivor+ .get("facet")+ .and_then(|f| f.get("value"))+ .and_then(Value::as_str),+ Some("exhaustive"),+ "and it must survive with the value the user set"+ );++ harness.join.abort();+}++/// Failure paths across the facet controllers: missing params are refused by+/// name, and a key with no row is refused rather than silently created.+///+/// The wording asserted here is **`core::all::validate_params`'**, not the+/// handlers'. Every dispatch is schema-validated for required-presence, unknown+/// params and declared types *before* the handler body runs+/// (`src/core/all.rs:1334`), so the handlers' own+/// ``missing required `class` `` strings are unreachable over RPC. Asserting the+/// handler's wording would pass only if that uniform gate were removed.+#[tokio::test]+async fn learning_facet_controllers_refuse_bad_input_and_absent_keys() {+ let _lock = env_lock();+ let harness = setup().await;++ // `get_facet` needs both halves of the key.+ let no_class = rpc(+ &harness.rpc_base,+ 40_101,+ "openhuman.learning_get_facet",+ json!({ "key": "verbosity" }),+ )+ .await;+ assert!(+ error_message(&no_class, "get_facet without class")+ .contains("missing required param 'class'"),+ "the refusal must name the param: {no_class}"+ );++ let no_key = rpc(+ &harness.rpc_base,+ 40_102,+ "openhuman.learning_get_facet",+ json!({ "class": "style" }),+ )+ .await;+ assert!(+ error_message(&no_key, "get_facet without key").contains("missing required param 'key'"),+ "the refusal must name the param: {no_key}"+ );++ // `update_facet` needs a value on top of the key.+ let no_value = rpc(+ &harness.rpc_base,+ 40_103,+ "openhuman.learning_update_facet",+ json!({ "class": "style", "key": "verbosity" }),+ )+ .await;+ assert!(+ error_message(&no_value, "update_facet without value")+ .contains("missing required param 'value'"),+ "the refusal must name the param: {no_value}"+ );++ // A key with no row: `get` reports absence, the mutators refuse.+ let absent = "e2e_learning_key_that_was_never_observed";+ let missing = rpc(+ &harness.rpc_base,+ 40_104,+ "openhuman.learning_get_facet",+ json!({ "class": "style", "key": absent }),+ )+ .await;+ let missing = payload(&missing, "get_facet absent");+ assert_eq!(+ missing.get("found").and_then(Value::as_bool),+ Some(false),+ "absence is a clean `found: false` on the read path: {missing}"+ );+ assert_eq!(+ missing.get("facet"),+ Some(&Value::Null),+ "and it carries no facet: {missing}"+ );++ for (id, method, context) in [+ (40_105_i64, "openhuman.learning_update_facet", "update"),+ (40_106, "openhuman.learning_pin_facet", "pin"),+ (40_107, "openhuman.learning_unpin_facet", "unpin"),+ ] {+ let mut params = json!({ "class": "style", "key": absent });+ if method.ends_with("update_facet") {+ params+ .as_object_mut()+ .expect("params object")+ .insert("value".into(), json!("anything"));+ }+ let response = rpc(&harness.rpc_base, id, method, params).await;+ let message = error_message(&response, context);+ assert!(+ message.contains("facet not found") && message.contains(absent),+ "{context} on an absent key must refuse and name it, got: {message}"+ );+ }++ // `forget_facet` is the odd one out and this pins the behaviour as it is,+ // not as it should be: it answers `Ok` with a null facet for a key that was+ // never observed, while its three sibling mutators refuse. The log line it+ // emits says `state=dropped user_state=forgotten` for a row that does not+ // exist, so a caller reading the log cannot tell a real forget from a typo.+ // See `~/tinyhuman/bugs/e2e-wave-learning-forget-facet-succeeds-on-absent-key.md`.+ let forgotten_nothing = rpc(+ &harness.rpc_base,+ 40_108,+ "openhuman.learning_forget_facet",+ json!({ "class": "style", "key": absent }),+ )+ .await;+ let forgotten_nothing = payload(&forgotten_nothing, "forget_facet absent");+ assert_eq!(+ forgotten_nothing.get("facet"),+ Some(&Value::Null),+ "forget on an absent key reports success with no facet: {forgotten_nothing}"+ );++ harness.join.abort();+}++/// `learning.save_profile` writes `PROFILE.md` into the active workspace, and+/// refuses a call with no body.+///+/// `summarize` is left at its default `false`: with it on the handler routes the+/// body through the LLM compressor, which needs a provider this hermetic suite+/// deliberately does not have.+#[tokio::test]+async fn learning_save_profile_writes_the_workspace_file() {+ let _lock = env_lock();+ let harness = setup().await;++ let body = "# E2E Profile\n\n- Prefers terse answers\n- Uses pnpm\n";+ let saved = rpc(+ &harness.rpc_base,+ 40_201,+ "openhuman.learning_save_profile",+ json!({ "markdown": body }),+ )+ .await;+ let saved = payload(&saved, "learning_save_profile");+ assert_eq!(+ saved.get("bytes").and_then(Value::as_u64),+ Some(body.len() as u64),+ "the reported byte count is the body's, not a rounded estimate: {saved}"+ );+ let reported = saved+ .get("path")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("save_profile must report the path it wrote: {saved}"));++ let expected = harness.workspace.join("PROFILE.md");+ assert_eq!(+ std::fs::read_to_string(&expected).expect("PROFILE.md must exist on disk"),+ body,+ "the file content must be the markdown handed in"+ );+ assert!(+ reported.ends_with("PROFILE.md"),+ "the reported path must name the file: {reported}"+ );++ // A second save replaces rather than appends.+ let shorter = "# Replaced\n";+ let replaced = rpc(+ &harness.rpc_base,+ 40_202,+ "openhuman.learning_save_profile",+ json!({ "markdown": shorter }),+ )+ .await;+ assert_eq!(+ payload(&replaced, "learning_save_profile replace")+ .get("bytes")+ .and_then(Value::as_u64),+ Some(shorter.len() as u64)+ );+ assert_eq!(+ std::fs::read_to_string(&expected).expect("PROFILE.md must still exist"),+ shorter,+ "save_profile truncates — a stale tail would corrupt the profile"+ );++ // Failure path: no body at all.+ let empty = rpc(+ &harness.rpc_base,+ 40_203,+ "openhuman.learning_save_profile",+ json!({}),+ )+ .await;+ assert!(+ error_message(&empty, "save_profile without markdown")+ .contains("missing required param 'markdown'"),+ "the refusal must name the param: {empty}"+ );++ harness.join.abort();+}++/// `learning.linkedin_enrichment` runs a network pipeline (Gmail search → Apify+/// scrape → memory write). With `api_url` pointed at a closed port it must+/// surface a *pipeline* failure — not panic, not hang, and not report success+/// with an empty result.+#[tokio::test]+async fn learning_linkedin_enrichment_fails_loudly_without_a_backend() {+ let _lock = env_lock();+ let harness = setup().await;++ let response = rpc(+ &harness.rpc_base,+ 40_301,+ "openhuman.learning_linkedin_enrichment",+ json!({ "profile_url": "https://www.linkedin.com/in/e2e-nobody" }),+ )+ .await;++ // Either shape is a correct contract here, and both are asserted rather+ // than one being assumed: the pipeline may refuse outright (no backend+ // reachable) or complete with an empty, honestly-reported log. What it must+ // never do is claim it scraped a profile it could not reach.+ match response.get("error") {+ Some(_) => {+ let message = error_message(&response, "learning_linkedin_enrichment");+ assert!(+ !message.is_empty(),+ "a refusal must carry a message: {response}"+ );+ }+ None => {+ let body = payload(&response, "learning_linkedin_enrichment");+ assert!(+ body.get("log").and_then(Value::as_array).is_some(),+ "the pipeline always reports its stages: {body}"+ );+ assert_eq!(+ body.get("profile_data"),+ Some(&Value::Null),+ "no backend means no scraped profile: {body}"+ );+ }+ }++ harness.join.abort();+}diff --git a/tests/raw_coverage/memory_goals_people_e2e.rs b/tests/raw_coverage/memory_goals_people_e2e.rsnew file mode 100644index 0000000000..00b0f515e4--- /dev/null+++ b/tests/raw_coverage/memory_goals_people_e2e.rs@@ -0,0 +1,1007 @@+//! JSON-RPC E2E coverage for three memory-family namespaces that had none:+//! `memory_goals` (5 controllers), `people` (4), and the four uncovered+//! `tree_summarizer` reads/passes (`query`, `status`, `run`, `rebuild`).+//!+//! All three sit behind the bound memory driver rather than a path this host+//! owns, so every case drives them over the real axum JSON-RPC router and+//! asserts on what came back through the driver — never on a file the test+//! wrote itself.+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target, not a+//! target of its own — `build.rs` globs `tests/raw_coverage/` and generates the+//! `mod` list. Run with:+//! `~/tinyhuman/ci-slot.sh cargo test --test raw_coverage_all \+//! --features "$(bash scripts/ci/product-features.sh)" -- memory_goals_people`+//!+//! ## Written around a shared process and a shared store+//!+//! ~77 suites share one process here, so the env lock is the crate-wide+//! `SHARED_ENV_LOCK` and the RPC bearer is read back from+//! `core::auth::get_rpc_token()` rather than assumed — a private lock would+//! isolate nothing and a hard-coded token would 401 whenever a sibling suite+//! seeded the process-global one first.+//!+//! The goals document is workspace-wide and the people store is shared, so+//! every case keys on a distinctive `e2e-…` marker and asserts on **its own**+//! rows: a goal is added, found by the id the handler assigned, edited, and+//! deleted. No case asserts a global count, because a sibling suite's row would+//! make that assertion fail for a reason unrelated to the controller.++use std::net::SocketAddr;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::TempDir;++use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;+use openhuman_core::openhuman::config::Config;++/// Preferred bearer. Only the real one if this module wins the process-global+/// `OnceLock` race — send [`rpc_bearer`], never this.+const PREFERRED_RPC_TOKEN: &str = "memory-goals-people-e2e-token";++static AUTH_INIT: OnceLock<()> = OnceLock::new();+static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();++/// The crate-wide env lock — see the module docs.+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())+}++// ── Env isolation ─────────────────────────────────────────────────────────++struct EnvVarGuard {+ key: &'static str,+ old: Option<String>,+}++impl EnvVarGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, path.as_os_str());+ Self { key, old }+ }++ fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, value);+ Self { key, old }+ }++ fn unset(key: &'static str) -> Self {+ let old = std::env::var(key).ok();+ std::env::remove_var(key);+ Self { key, old }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+}++// ── Shared memory workspace ───────────────────────────────────────────────++/// The transport-only JSON-RPC router builds no core runtime context, so a+/// memory-backed route has no seams unless they are installed explicitly.+fn ensure_memory_seams() {+ MEMORY_SEAMS_INIT.get_or_init(|| {+ std::thread::Builder::new()+ .name("memory-goals-people-e2e-seams".to_string())+ .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);+ })+ .expect("spawn memory goals/people seam installer")+ .join()+ .expect("memory goals/people seam installer panicked");+ });+}++/// The one memory workspace every case in this module shares.+///+/// The module host captures a workspace **once per process**: the loaded+/// artifact takes its `workspace_dir` at load time and later policy calls are+/// ignored. A per-case `TempDir` would be deleted when its case returned,+/// leaving every later read answering from a dead store — 0 rows where a case+/// had just written one. One leaked directory, published once, is the same+/// arrangement `tests/json_rpc_e2e.rs` uses. The path ends in `workspace` so+/// `resolve_config_dir_for_workspace` treats it as the workspace itself rather+/// than appending another segment.+fn memory_workspace() -> &'static Path {+ static WORKSPACE: OnceLock<PathBuf> = OnceLock::new();+ WORKSPACE.get_or_init(|| {+ let dir = TempDir::new().expect("memory workspace tempdir");+ let path = dir.path().join("workspace");+ std::fs::create_dir_all(&path).expect("create memory workspace");+ // Leaked on purpose: the module keeps this path for the process lifetime.+ std::mem::forget(dir);+ path+ })+}++/// A config whose workspace **and** config path are the shared ones.+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+}++/// The config on disk. `local_ai.enabled = false` and no+/// `memory_tree.cloud_summarization_opt_in` are the *defaults* and are written+/// out explicitly, because the tree-summarizer consent gate below asserts on+/// the refusal they produce.+fn write_min_config(config_path: &Path) {+ if let Some(parent) = config_path.parent() {+ std::fs::create_dir_all(parent).expect("create config dir");+ }+ let cfg = r#"api_url = "http://127.0.0.1:9"+default_model = "e2e-model"+default_temperature = 0.2++[secrets]+encrypt = false++[local_ai]+enabled = false++[memory_tree]+embedding_strict = false+cloud_summarization_opt_in = false+"#;+ std::fs::write(config_path, cfg).expect("write config.toml");+ let _: Config = toml::from_str(cfg).expect("test config must match schema");+}++// ── Harness ───────────────────────────────────────────────────────────────++fn ensure_rpc_auth() {+ AUTH_INIT.get_or_init(|| {+ std::env::set_var(CORE_TOKEN_ENV_VAR, PREFERRED_RPC_TOKEN);+ let token_dir = std::env::temp_dir().join("openhuman-memory-goals-people-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+}++/// The bearer the running process actually validates — see the module docs.+fn rpc_bearer() -> &'static str {+ ensure_rpc_auth();+ openhuman_core::core::auth::get_rpc_token()+ .expect("the RPC token must be initialised before a request is signed")+}++struct Harness {+ _guards: Vec<EnvVarGuard>,+ rpc_base: String,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++async fn serve_rpc() -> (+ SocketAddr,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let join =+ tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });+ (addr, join)+}++async fn setup() -> Harness {+ ensure_memory_seams();+ let workspace = memory_workspace().to_path_buf();+ let config_path = workspace+ .parent()+ .expect("shared workspace has a parent")+ .join("config.toml");+ write_min_config(&config_path);++ let guards = vec![+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let (addr, join) = serve_rpc().await;+ Harness {+ _guards: guards,+ rpc_base: format!("http://{addr}"),+ join,+ }+}++async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("client");+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", rpc_bearer()))+ .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+}++/// The payload of a successful dispatch, unwrapping the `RpcOutcome`+/// `{ result, logs }` envelope when the handler produced one.+fn payload(value: &Value, context: &str) -> Value {+ if let Some(error) = value.get("error") {+ panic!("{context}: unexpected JSON-RPC error: {error}");+ }+ let outer = value+ .get("result")+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"));+ match outer.get("result") {+ Some(inner) => inner.clone(),+ None => outer.clone(),+ }+}++fn error_message(value: &Value, context: &str) -> String {+ value+ .get("error")+ .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}"))+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{context}: error object has no message: {value}"))+ .to_string()+}++/// The `items` array of a goals document, wherever the handler put it.+///+/// `list` answers the bare `GoalsDoc`; `add` answers `{ id, goals }`. Both+/// shapes are a published compatibility surface, so this reads either rather+/// than normalising one into the other.+fn goal_items(payload: &Value, context: &str) -> Vec<Value> {+ let doc = payload.get("goals").unwrap_or(payload);+ doc.get("items")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("{context}: expected a goals items array: {payload}"))+ .clone()+}++fn find_goal<'a>(items: &'a [Value], id: &str) -> Option<&'a Value> {+ items+ .iter()+ .find(|item| item.get("id").and_then(Value::as_str) == Some(id))+}++// ── memory_goals ──────────────────────────────────────────────────────────++/// The goals CRUD arc over RPC: add mints an id, list sees it, edit rewrites+/// the text in place, delete removes it, and list no longer sees it.+///+/// One case rather than four: the document is a single workspace-wide object,+/// so separate cases would either depend on each other's leftovers or leak a+/// goal for the next suite to trip over.+#[tokio::test]+async fn memory_goals_add_list_edit_delete_round_trip() {+ let _lock = env_lock();+ let harness = setup().await;++ let original = "e2e-goals-marker: keep the RPC surface honest";+ let rewritten = "e2e-goals-marker: keep the RPC surface honest and small";++ // ── add: the handler assigns the id, the caller does not ──+ let added = rpc(+ &harness.rpc_base,+ 41_001,+ "openhuman.memory_goals_add",+ json!({ "text": original }),+ )+ .await;+ let added = payload(&added, "memory_goals_add");+ let goal_id = added+ .get("id")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("add must return the assigned id: {added}"))+ .to_string();+ assert!(+ goal_id.starts_with('g'),+ "ids come from the contract's `g<N>` allocator, got {goal_id}"+ );+ let after_add = goal_items(&added, "memory_goals_add");+ assert_eq!(+ find_goal(&after_add, &goal_id)+ .and_then(|g| g.get("text"))+ .and_then(Value::as_str),+ Some(original),+ "add returns the updated list read back through the driver: {added}"+ );++ // ── list: an independent read sees the same row ──+ let listed = rpc(+ &harness.rpc_base,+ 41_002,+ "openhuman.memory_goals_list",+ json!({}),+ )+ .await;+ let listed_items = goal_items(&payload(&listed, "memory_goals_list"), "memory_goals_list");+ assert_eq!(+ find_goal(&listed_items, &goal_id)+ .and_then(|g| g.get("text"))+ .and_then(Value::as_str),+ Some(original),+ "the goal must be durable, not a value echoed by add"+ );++ // ── edit: rewrites in place, keeping the id ──+ let edited = rpc(+ &harness.rpc_base,+ 41_003,+ "openhuman.memory_goals_edit",+ json!({ "id": goal_id, "text": rewritten }),+ )+ .await;+ let edited_items = goal_items(&payload(&edited, "memory_goals_edit"), "memory_goals_edit");+ assert_eq!(+ find_goal(&edited_items, &goal_id)+ .and_then(|g| g.get("text"))+ .and_then(Value::as_str),+ Some(rewritten),+ "edit must replace the text under the same id: {edited}"+ );+ assert_eq!(+ edited_items+ .iter()+ .filter(|g| g.get("id").and_then(Value::as_str) == Some(goal_id.as_str()))+ .count(),+ 1,+ "edit must not duplicate the row it rewrote"+ );++ // ── delete: removes it, and a following list confirms ──+ let deleted = rpc(+ &harness.rpc_base,+ 41_004,+ "openhuman.memory_goals_delete",+ json!({ "id": goal_id }),+ )+ .await;+ let deleted_items = goal_items(+ &payload(&deleted, "memory_goals_delete"),+ "memory_goals_delete",+ );+ assert!(+ find_goal(&deleted_items, &goal_id).is_none(),+ "delete must return the list without the deleted goal: {deleted}"+ );++ let final_list = rpc(+ &harness.rpc_base,+ 41_005,+ "openhuman.memory_goals_list",+ json!({}),+ )+ .await;+ let final_items = goal_items(+ &payload(&final_list, "memory_goals_list final"),+ "memory_goals_list final",+ );+ assert!(+ find_goal(&final_items, &goal_id).is_none(),+ "the delete must be durable, not just reflected in its own reply"+ );++ harness.join.abort();+}++/// The goals validation boundary, which is deliberately **host-side**: a goal+/// that carries a secret or an email address must be refused before it reaches+/// the driver, and an unknown id must be a `NotFound` rather than a silent+/// no-op.+#[tokio::test]+async fn memory_goals_refuse_pii_secrets_blank_text_and_unknown_ids() {+ let _lock = env_lock();+ let harness = setup().await;++ // Empty / whitespace-only text.+ let blank = rpc(+ &harness.rpc_base,+ 41_101,+ "openhuman.memory_goals_add",+ json!({ "text": " " }),+ )+ .await;+ assert!(+ !error_message(&blank, "memory_goals_add blank").is_empty(),+ "a blank goal must be refused: {blank}"+ );++ // A multi-line goal — the contract is one concise sentence.+ let multiline = rpc(+ &harness.rpc_base,+ 41_102,+ "openhuman.memory_goals_add",+ json!({ "text": "first line\nsecond line" }),+ )+ .await;+ assert!(+ !error_message(&multiline, "memory_goals_add multiline").is_empty(),+ "a multi-line goal must be refused: {multiline}"+ );++ // An email address is PII by the host's own predicate.+ let pii = rpc(+ &harness.rpc_base,+ 41_103,+ "openhuman.memory_goals_add",+ json!({ "text": "email the report to [email protected] every Friday" }),+ )+ .await;+ let pii_message = error_message(&pii, "memory_goals_add pii");+ assert!(+ pii_message.contains("secrets or PII"),+ "the refusal must say why, got: {pii_message}"+ );++ // The type contract. This is `core::all::validate_params`' wording, not the+ // handler's: every dispatch is schema-validated for required-presence and+ // declared types before the handler body runs (`src/core/all.rs:1334`), so+ // `parse_value`'s own "invalid params: …" is unreachable over RPC.+ let missing_text = rpc(+ &harness.rpc_base,+ 41_104,+ "openhuman.memory_goals_add",+ json!({}),+ )+ .await;+ assert!(+ error_message(&missing_text, "memory_goals_add without text")+ .contains("missing required param 'text'"),+ "a missing required field is refused by name before the handler runs: {missing_text}"+ );++ // Unknown ids on both mutators.+ for (id, method, context) in [+ (41_105_i64, "openhuman.memory_goals_edit", "edit"),+ (41_106, "openhuman.memory_goals_delete", "delete"),+ ] {+ let mut params = json!({ "id": "g-e2e-never-allocated" });+ if method.ends_with("edit") {+ params+ .as_object_mut()+ .expect("params object")+ .insert("text".into(), json!("anything at all"));+ }+ let response = rpc(&harness.rpc_base, id, method, params).await;+ let message = error_message(&response, context);+ assert!(+ message.contains("g-e2e-never-allocated"),+ "{context} on an unknown id must name it, got: {message}"+ );+ }++ harness.join.abort();+}++/// `memory_goals.reflect` runs the enrichment agent on demand. With no+/// reachable provider it must report the failure **in band** — `ran: false`+/// plus a summary — and still hand back the current list, because the caller+/// asked for the list and a second failure reading it back must not replace the+/// report of the first.+#[tokio::test]+async fn memory_goals_reflect_reports_a_failed_run_without_losing_the_list() {+ let _lock = env_lock();+ let harness = setup().await;++ let reflected = rpc(+ &harness.rpc_base,+ 41_201,+ "openhuman.memory_goals_reflect",+ json!({ "context": "e2e-goals-reflect: review nothing in particular" }),+ )+ .await;+ let reflected = payload(&reflected, "memory_goals_reflect");++ assert!(+ reflected.get("ran").and_then(Value::as_bool).is_some(),+ "reflect must always report whether the agent ran: {reflected}"+ );+ assert!(+ reflected+ .get("summary")+ .and_then(Value::as_str)+ .is_some_and(|s| !s.is_empty()),+ "reflect must always carry a human-readable summary: {reflected}"+ );+ // The list comes back either way — that is the whole point of the shape.+ assert!(+ reflected+ .get("goals")+ .and_then(|g| g.get("items"))+ .and_then(Value::as_array)+ .is_some(),+ "reflect must return the goals list alongside its outcome: {reflected}"+ );++ if reflected.get("ran").and_then(Value::as_bool) == Some(false) {+ assert!(+ reflected+ .get("summary")+ .and_then(Value::as_str)+ .is_some_and(|s| s.contains("enrichment failed")),+ "a failed run must say so rather than reporting a bland summary: {reflected}"+ );+ }++ harness.join.abort();+}++// ── people ────────────────────────────────────────────────────────────────++/// The people surface over RPC: minting a person from a handle, resolving that+/// handle again to the same id, scoring them, and finding them in the ranked+/// list.+#[tokio::test]+async fn people_resolve_mints_then_score_and_list_agree_on_the_person() {+ let _lock = env_lock();+ let harness = setup().await;++ let handle = "[email protected]";++ // ── resolve without create_if_missing: an unknown handle is not minted ──+ let unknown = rpc(+ &harness.rpc_base,+ 42_001,+ "openhuman.people_resolve",+ json!({ "kind": "email", "value": handle }),+ )+ .await;+ let unknown = payload(&unknown, "people_resolve without create");+ assert_eq!(+ unknown.get("created").and_then(Value::as_bool),+ Some(false),+ "resolve must not mint unless asked: {unknown}"+ );+ assert_eq!(+ unknown.get("person_id"),+ Some(&Value::Null),+ "an unresolved handle answers a null id, not an error: {unknown}"+ );++ // ── resolve with create_if_missing: mints once ──+ let minted = rpc(+ &harness.rpc_base,+ 42_002,+ "openhuman.people_resolve",+ json!({ "kind": "email", "value": handle, "create_if_missing": true }),+ )+ .await;+ let minted = payload(&minted, "people_resolve create");+ let person_id = minted+ .get("person_id")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("minting must return an id: {minted}"))+ .to_string();+ assert!(+ uuid_shaped(&person_id),+ "a PersonId is a UUID, got {person_id}"+ );+ assert_eq!(+ minted.get("created").and_then(Value::as_bool),+ Some(true),+ "the first resolve-with-create reports the mint: {minted}"+ );++ // ── resolving again is idempotent: same id, not created twice ──+ let again = rpc(+ &harness.rpc_base,+ 42_003,+ "openhuman.people_resolve",+ json!({ "kind": "email", "value": handle, "create_if_missing": true }),+ )+ .await;+ let again = payload(&again, "people_resolve idempotent");+ assert_eq!(+ again.get("person_id").and_then(Value::as_str),+ Some(person_id.as_str()),+ "the same handle must always resolve to the same person: {again}"+ );+ assert_eq!(+ again.get("created").and_then(Value::as_bool),+ Some(false),+ "a second resolve must not report a mint: {again}"+ );++ // ── score: the composite and its four components are in range ──+ let scored = rpc(+ &harness.rpc_base,+ 42_004,+ "openhuman.people_score",+ json!({ "person_id": person_id }),+ )+ .await;+ let scored = payload(&scored, "people_score");+ assert_eq!(+ scored.get("person_id").and_then(Value::as_str),+ Some(person_id.as_str()),+ "score echoes the id it scored: {scored}"+ );+ let composite = scored+ .get("score")+ .and_then(Value::as_f64)+ .unwrap_or_else(|| panic!("score must report a composite: {scored}"));+ assert!(+ (0.0..=1.0).contains(&composite),+ "the composite score is documented as [0,1], got {composite}"+ );+ let components = scored+ .get("components")+ .unwrap_or_else(|| panic!("score must break down by component: {scored}"));+ for component in ["recency", "frequency", "reciprocity", "depth"] {+ let value = components+ .get(component)+ .and_then(Value::as_f64)+ .unwrap_or_else(|| panic!("missing component {component}: {scored}"));+ assert!(+ (0.0..=1.0).contains(&value),+ "component {component} is documented as [0,1], got {value}"+ );+ }+ assert_eq!(+ scored.get("interaction_count").and_then(Value::as_u64),+ Some(0),+ "a person minted from a bare handle has no observed interactions: {scored}"+ );++ // ── list: the minted person appears, carrying the handle it was minted from ──+ let listed = rpc(+ &harness.rpc_base,+ 42_005,+ "openhuman.people_list",+ json!({ "limit": 200 }),+ )+ .await;+ let listed = payload(&listed, "people_list");+ let people = listed+ .get("people")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("people_list returns a people array: {listed}"));+ let row = people+ .iter()+ .find(|p| p.get("person_id").and_then(Value::as_str) == Some(person_id.as_str()))+ .unwrap_or_else(|| panic!("the minted person must be listed: {listed}"));+ let handles = row+ .get("handles")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("a listed person carries its handles: {row}"));+ assert!(+ handles.iter().any(|h| {+ h.get("kind").and_then(Value::as_str) == Some("email")+ && h.get("value")+ .and_then(Value::as_str)+ .is_some_and(|v| v.eq_ignore_ascii_case(handle))+ }),+ "the handle the person was minted from must be on the row: {row}"+ );+ assert!(+ row.get("components").is_some(),+ "the ranked list carries the same component breakdown as `score`: {row}"+ );++ harness.join.abort();+}++fn uuid_shaped(value: &str) -> bool {+ value.len() == 36 && value.split('-').map(str::len).eq([8, 4, 4, 4, 12])+}++/// The people validation boundary: the handle kind is a closed set, a+/// malformed `person_id` is refused by name, and `list`'s `limit` is typed.+#[tokio::test]+async fn people_reject_unknown_handle_kinds_and_malformed_ids() {+ let _lock = env_lock();+ let harness = setup().await;++ let bad_kind = rpc(+ &harness.rpc_base,+ 42_101,+ "openhuman.people_resolve",+ json!({ "kind": "carrier_pigeon", "value": "someone" }),+ )+ .await;+ let message = error_message(&bad_kind, "people_resolve bad kind");+ assert!(+ message.contains("carrier_pigeon")+ && message.contains("imessage")+ && message.contains("email")+ && message.contains("display_name"),+ "the refusal must name the offending kind and the accepted set, got: {message}"+ );++ let no_value = rpc(+ &harness.rpc_base,+ 42_102,+ "openhuman.people_resolve",+ json!({ "kind": "email" }),+ )+ .await;+ assert!(+ error_message(&no_value, "people_resolve without value")+ .contains("missing required param 'value'"),+ "the refusal must name the param: {no_value}"+ );++ let wrong_type = rpc(+ &harness.rpc_base,+ 42_103,+ "openhuman.people_resolve",+ json!({ "kind": "email", "value": 42 }),+ )+ .await;+ let wrong_type_message = error_message(&wrong_type, "people_resolve numeric value");+ assert!(+ wrong_type_message.contains("expected string") && wrong_type_message.contains("number"),+ "the refusal must name both the expected and the actual type, got: {wrong_type_message}"+ );++ // `person_id` is parsed as a UUID host-side so a typo fails with the param+ // name rather than as an opaque driver error.+ let bad_id = rpc(+ &harness.rpc_base,+ 42_104,+ "openhuman.people_score",+ json!({ "person_id": "not-a-uuid" }),+ )+ .await;+ let bad_id_message = error_message(&bad_id, "people_score bad id");+ assert!(+ bad_id_message.contains("person_id") && bad_id_message.contains("not-a-uuid"),+ "the refusal must name the param and the value, got: {bad_id_message}"+ );++ // A well-formed UUID that names nobody: the id parses, so the refusal has+ // to come from the driver — and it must still identify what was not found.+ let no_such_person = rpc(+ &harness.rpc_base,+ 42_105,+ "openhuman.people_score",+ json!({ "person_id": "00000000-0000-4000-8000-000000000000" }),+ )+ .await;+ let no_such_message = error_message(&no_such_person, "people_score unknown uuid");+ assert!(+ no_such_message.contains("00000000-0000-4000-8000-000000000000"),+ "the refusal must name the person that was not found, got: {no_such_message}"+ );++ let bad_limit = rpc(+ &harness.rpc_base,+ 42_106,+ "openhuman.people_list",+ json!({ "limit": "lots" }),+ )+ .await;+ assert!(+ error_message(&bad_limit, "people_list string limit").contains("unsigned integer"),+ "a non-numeric limit must be refused: {bad_limit}"+ );++ harness.join.abort();+}++/// `people.refresh_address_book` seeds from the system address book. On a CI+/// host with no address book — or no Contacts permission — the contract is+/// `seeded: 0`, deliberately *not* a distinct error, and `permission_denied`+/// can no longer become true.+#[tokio::test]+async fn people_refresh_address_book_reports_a_seed_count_not_a_permission_error() {+ let _lock = env_lock();+ let harness = setup().await;++ let refreshed = rpc(+ &harness.rpc_base,+ 42_201,+ "openhuman.people_refresh_address_book",+ json!({}),+ )+ .await;++ // A host that cannot read contacts at all may refuse at the driver; what it+ // must never do is report a permission problem through the retained field.+ if refreshed.get("error").is_some() {+ let message = error_message(&refreshed, "people_refresh_address_book");+ assert!(+ message.contains("address_book"),+ "a driver refusal must be attributed to the address book, got: {message}"+ );+ } else {+ let body = payload(&refreshed, "people_refresh_address_book");+ assert!(+ body.get("seeded").and_then(Value::as_u64).is_some(),+ "the outcome must carry a seed count: {body}"+ );+ assert!(+ body.get("skipped").and_then(Value::as_u64).is_some(),+ "the outcome must carry a skip count: {body}"+ );+ assert_eq!(+ body.get("permission_denied").and_then(Value::as_bool),+ Some(false),+ "the field is retained for wire compatibility and can no longer \+ become true — a host without permission reports seeded: 0: {body}"+ );+ }++ harness.join.abort();+}++// ── tree_summarizer ───────────────────────────────────────────────────────++/// `tree_summarizer.status` and `.query` over a namespace with no tree.+///+/// `status` answers a well-formed empty status; `query` refuses, because a node+/// that is not there is the caller asking for something specific that does not+/// exist — the asymmetry is the contract, and it is what these assertions pin.+#[tokio::test]+async fn tree_summarizer_status_is_empty_and_query_refuses_an_absent_node() {+ let _lock = env_lock();+ let harness = setup().await;++ let namespace = "e2e_tree_summarizer_empty";++ let status = rpc(+ &harness.rpc_base,+ 43_001,+ "openhuman.tree_summarizer_status",+ json!({ "namespace": namespace }),+ )+ .await;+ let status = payload(&status, "tree_summarizer_status");+ assert_eq!(+ status.get("namespace").and_then(Value::as_str),+ Some(namespace),+ "status echoes the namespace it describes: {status}"+ );+ assert_eq!(+ status.get("total_nodes").and_then(Value::as_u64),+ Some(0),+ "a namespace with no tree has no nodes: {status}"+ );+ assert_eq!(+ status.get("depth").and_then(Value::as_u64),+ Some(0),+ "and therefore no depth: {status}"+ );+ assert_eq!(+ status.get("newest_entry"),+ Some(&Value::Null),+ "with no entries the timestamps are null, not epoch: {status}"+ );++ // `query` defaults to the root node, which does not exist yet.+ let query = rpc(+ &harness.rpc_base,+ 43_002,+ "openhuman.tree_summarizer_query",+ json!({ "namespace": namespace }),+ )+ .await;+ let message = error_message(&query, "tree_summarizer_query root");+ assert!(+ message.contains("node 'root' not found") && message.contains(namespace),+ "the refusal must name both the node and the namespace, got: {message}"+ );++ // An explicit node id is reported by that id, not silently rewritten to root.+ let dated = rpc(+ &harness.rpc_base,+ 43_003,+ "openhuman.tree_summarizer_query",+ json!({ "namespace": namespace, "node_id": "2026/09/07/12" }),+ )+ .await;+ let dated_message = error_message(&dated, "tree_summarizer_query node");+ assert!(+ dated_message.contains("2026/09/07/12"),+ "the refusal must name the node that was asked for, got: {dated_message}"+ );++ harness.join.abort();+}++/// The consent gate on the two passes that spend on a model.+///+/// `run` and `rebuild` resolve a summarization provider **before** any driver+/// work begins, purely so an opted-out user's memory summaries cannot be sent+/// to a cloud provider by a route that knows nothing about the opt-in. With+/// local AI off and `memory_tree.cloud_summarization_opt_in = false` — the+/// shipped default — both must refuse with an error that names the setting.+#[tokio::test]+async fn tree_summarizer_run_and_rebuild_refuse_without_summarization_consent() {+ let _lock = env_lock();+ let harness = setup().await;++ let namespace = "e2e_tree_summarizer_consent";++ for (id, method, context) in [+ (43_101_i64, "openhuman.tree_summarizer_run", "run"),+ (43_102, "openhuman.tree_summarizer_rebuild", "rebuild"),+ ] {+ let response = rpc(&harness.rpc_base, id, method, json!({ "namespace": namespace })).await;+ let message = error_message(&response, context);+ assert!(+ message.contains("no summarization provider"),+ "{context} must refuse before doing any work, got: {message}"+ );+ assert!(+ message.contains("local AI")+ && message.contains("memory_tree.cloud_summarization_opt_in"),+ "the refusal must name both ways out, so it is actionable — got: {message}"+ );+ }++ // Missing `namespace` is refused by name on every controller in the family.+ for (id, method, context) in [+ (43_103_i64, "openhuman.tree_summarizer_status", "status"),+ (43_104, "openhuman.tree_summarizer_query", "query"),+ (43_105, "openhuman.tree_summarizer_run", "run"),+ (43_106, "openhuman.tree_summarizer_rebuild", "rebuild"),+ ] {+ let response = rpc(&harness.rpc_base, id, method, json!({})).await;+ assert!(+ error_message(&response, context).contains("missing required param 'namespace'"),+ "{context} must name the missing param: {response}"+ );+ }++ // A wrong-typed namespace is a type error, not a stringified number.+ let wrong_type = rpc(+ &harness.rpc_base,+ 43_107,+ "openhuman.tree_summarizer_status",+ json!({ "namespace": 7 }),+ )+ .await;+ assert!(+ error_message(&wrong_type, "tree_summarizer_status numeric namespace")+ .contains("invalid type for param 'namespace' in tree_summarizer.status"),+ "the refusal must name the param, the controller, and both types: {wrong_type}"+ );++ harness.join.abort();+}diff --git a/tests/raw_coverage/session_store_e2e.rs b/tests/raw_coverage/session_store_e2e.rsnew file mode 100644index 0000000000..afe8bb5c82--- /dev/null+++ b/tests/raw_coverage/session_store_e2e.rs@@ -0,0 +1,1286 @@+//! JSON-RPC E2E coverage for the session / artifact / compression store domains:+//! `session_db`, `session_import`, `tokenjuice` (compress + retrieve), `ai`+//! (artifact CRUD) and `test_support`.+//!+//! Every case boots the real axum JSON-RPC router (`build_core_http_router`)+//! against a per-test temp workspace, dispatches over HTTP, and+//! asserts on response *content*. Each namespace gets at least one failure+//! path, because that is where these handlers actually branch.+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target, not a+//! target of its own — `build.rs` globs `tests/raw_coverage/` and generates the+//! `mod` list. Run with:+//! `~/tinyhuman/ci-slot.sh cargo test --test raw_coverage_all \+//! --features "$(bash scripts/ci/product-features.sh)" -- session_store`+//!+//! Because every suite in that binary shares one process, this file takes the+//! crate-wide `SHARED_ENV_LOCK` around each case and reads the live RPC bearer+//! back rather than assuming its own — see `env_lock` and `rpc_bearer`.+//!+//! ## Two things this file documents rather than asserts as correct+//!+//! 1. **`session_db` reads a table the product never writes.** Nothing under+//! `src/` calls `tinyagents_session::record_session_start` / `record_message`+//! / `record_tool_call`; the host only uses the sibling `run_ledger`. So the+//! six `session_db.*` controllers are permanently empty in production. The+//! cases below therefore assert the empty-store contract and the failure+//! paths, which is the whole of the behaviour that is reachable.+//! See `~/tinyhuman/bugs/e2e-wave-session_db-never-written.md`.+//!+//! 2. **`test_support.*` is gated behind `e2e-test-support`,** which is not in+//! `scripts/ci/product-features.sh`. Under the product feature set those+//! five controllers must be *absent* — that gate is the reason the+//! destructive `test_reset` never ships — so the case here asserts the+//! absence, and the positive path is compiled in only when the feature is.++use std::net::SocketAddr;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};++use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;++/// Preferred bearer for this suite. It is only the *actual* bearer when this+/// module happens to be the first in the aggregated binary to initialise auth —+/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and first writer wins.+/// Never send this constant; send [`rpc_bearer`], which reads back whichever+/// token the process really validates.+const PREFERRED_RPC_TOKEN: &str = "session-store-e2e-token";++static AUTH_INIT: OnceLock<()> = OnceLock::new();++/// The crate-wide env lock. A lock private to this module would isolate+/// nothing: every `tests/raw_coverage/` suite is a module in the one+/// `raw_coverage_all` binary, so libtest runs them concurrently in one process+/// and only the shared mutex actually excludes another suite's `set_var`.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++// ── Env isolation ─────────────────────────────────────────────────────────++struct EnvVarGuard {+ key: &'static str,+ old: Option<String>,+}++impl EnvVarGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, path.as_os_str());+ Self { key, old }+ }++ fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, value);+ Self { key, old }+ }++ fn unset(key: &'static str) -> Self {+ let old = std::env::var(key).ok();+ std::env::remove_var(key);+ Self { key, old }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+}++/// `HOME` / `OPENHUMAN_WORKSPACE` are process-global, so every case in this+/// binary is serialised behind one lock.+fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++fn ensure_rpc_auth() {+ AUTH_INIT.get_or_init(|| {+ std::env::set_var(CORE_TOKEN_ENV_VAR, PREFERRED_RPC_TOKEN);+ let token_dir = std::env::temp_dir().join("openhuman-session-store-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+}++/// The bearer the running process actually validates.+///+/// `init_rpc_token` is idempotent on a process-global `OnceLock`, so in the+/// aggregated binary a sibling suite may have seeded a different token before+/// this module's first case ran. Hard-coding `PREFERRED_RPC_TOKEN` into the+/// header would then 401 every request here for a reason that has nothing to do+/// with the controller under test. Read the live value instead.+fn rpc_bearer() -> &'static str {+ ensure_rpc_auth();+ openhuman_core::core::auth::get_rpc_token()+ .expect("the RPC token must be initialised before a request is signed")+}++/// Write `config.toml` into `dir` — the workspace's parent, which is where+/// `resolve_config_dir_for_workspace` resolves it from `OPENHUMAN_WORKSPACE`.+fn write_min_config(dir: &Path) {+ std::fs::create_dir_all(dir).expect("create config dir");+ let cfg = r#"api_url = "http://127.0.0.1:9"+default_model = "e2e-model"+default_temperature = 0.2++[secrets]+encrypt = false++[local_ai]+enabled = false++[memory_tree]+embedding_strict = false+"#;+ std::fs::write(dir.join("config.toml"), cfg).expect("write config.toml");+ let _: openhuman_core::openhuman::config::Config =+ toml::from_str(cfg).expect("test config must match schema");+}++struct Harness {+ _tmp: TempDir,+ _guards: Vec<EnvVarGuard>,+ workspace: PathBuf,+ rpc_base: String,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++async fn serve_rpc() -> (+ SocketAddr,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let join = tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });+ (addr, join)+}++/// A fresh temp workspace per case, named through `OPENHUMAN_WORKSPACE` so the+/// test can seed files on disk (artifacts, `session_raw/` JSONL) at exactly the+/// path the handlers will read from. Each of the domains here keys on+/// `config.workspace_dir` alone, so a per-case workspace is safe — unlike the+/// memory-family suites, nothing in this file is bound once per process.+///+/// **`HOME` is deliberately left alone.** Loadable modules install under+/// `dirs::cache_dir()`, i.e. `$HOME/Library/Caches/openhuman/modules` on macOS+/// (`modules::ops::install_dir`), so repointing `HOME` at a tempdir would miss+/// the already-verified `tinyjuice` artifact and send the tokenjuice cases to+/// the network for a module the machine already has. The config is written+/// beside the workspace instead, which is where+/// `resolve_config_dir_for_workspace` looks when `OPENHUMAN_WORKSPACE` is set.+async fn setup() -> Harness {+ let tmp = tempdir().expect("tempdir");+ let workspace = tmp.path().join("workspace");+ std::fs::create_dir_all(&workspace).expect("create workspace");+ write_min_config(tmp.path());++ let guards = vec![+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ ];++ let (addr, join) = serve_rpc().await;+ Harness {+ _tmp: tmp,+ _guards: guards,+ workspace,+ rpc_base: format!("http://{addr}"),+ join,+ }+}++// ── RPC helpers ───────────────────────────────────────────────────────────++async fn rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("client");+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", rpc_bearer()))+ .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+}++#[allow(dead_code)]+async fn schema_catalog(rpc_base: &str) -> Value {+ let url = format!("{}/schema", rpc_base.trim_end_matches('/'));+ reqwest::get(&url)+ .await+ .unwrap_or_else(|err| panic!("GET {url}: {err}"))+ .json::<Value>()+ .await+ .expect("schema json")+}++#[allow(dead_code)]+fn catalog_has(catalog: &Value, method: &str) -> bool {+ catalog+ .get("methods")+ .and_then(Value::as_array)+ .expect("schema methods array")+ .iter()+ .any(|entry| entry.get("method").and_then(Value::as_str) == Some(method))+}++/// The payload of a successful dispatch, unwrapping the `RpcOutcome`+/// `{ result, logs }` envelope when the handler produced one.+fn payload(value: &Value, context: &str) -> Value {+ if let Some(error) = value.get("error") {+ panic!("{context}: unexpected JSON-RPC error: {error}");+ }+ let outer = value+ .get("result")+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"));+ match outer.get("result") {+ Some(inner) => inner.clone(),+ None => outer.clone(),+ }+}++fn error_message(value: &Value, context: &str) -> String {+ value+ .get("error")+ .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}"))+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{context}: error object has no message: {value}"))+ .to_string()+}++// ── session_db ────────────────────────────────────────────────────────────++/// The six `session_db.*` reads over a workspace with no session database yet.+///+/// This is the only state the product ever puts them in — see the module docs+/// and the bug file — so the empty-store contract *is* the contract: the schema+/// is created on first read, `list`/`search` answer a well-formed empty page+/// rather than erroring, and the per-session reads answer empty collections for+/// an id that does not exist.+#[tokio::test]+async fn session_db_reads_answer_a_wellformed_empty_store() {+ let _lock = env_lock();+ let harness = setup().await;++ let list = rpc(&harness.rpc_base, 30_001, "openhuman.session_db_list", json!({})).await;+ let list = payload(&list, "session_db_list");+ assert_eq!(+ list.get("sessions").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "a fresh workspace has no sessions: {list}"+ );+ assert_eq!(+ list.get("total").and_then(Value::as_u64),+ Some(0),+ "total must be present and zero: {list}"+ );++ // The read created the database — proof the handler reached storage and+ // applied migrations rather than short-circuiting on a missing file. The+ // path is `tinyagents_session::store::db_path`'s, spelled out because that+ // crate is a normal dependency and an integration test cannot name it.+ let db = harness.workspace.join("session_db").join("sessions.db");+ assert!(+ db.exists(),+ "a session-db read must materialise {:?}; workspace holds: {:?}",+ db,+ std::fs::read_dir(&harness.workspace)+ .map(|rd| rd+ .filter_map(Result::ok)+ .map(|e| e.file_name())+ .collect::<Vec<_>>())+ .unwrap_or_default()+ );++ let search = rpc(+ &harness.rpc_base,+ 30_002,+ "openhuman.session_db_search",+ json!({ "query": "nothing-matches-this", "limit": 10 }),+ )+ .await;+ let search = payload(&search, "session_db_search");+ assert_eq!(+ search.get("sessions").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "search over an empty store returns no rows: {search}"+ );+ assert_eq!(search.get("total").and_then(Value::as_u64), Some(0));++ // The per-session reads take an unknown id and answer empty collections,+ // NOT an error — the store has no row to refuse over.+ for (id, method, context) in [+ (30_003_i64, "openhuman.session_db_get_messages", "get_messages"),+ (30_004, "openhuman.session_db_get_tool_calls", "get_tool_calls"),+ ] {+ let response = rpc(+ &harness.rpc_base,+ id,+ method,+ json!({ "sessionId": "no-such-session" }),+ )+ .await;+ let body = payload(&response, context);+ let rows = body+ .as_array()+ .unwrap_or_else(|| panic!("{context} must return an array, got: {body}"));+ assert!(rows.is_empty(), "{context} for an unknown session: {body}");+ }++ let children = rpc(+ &harness.rpc_base,+ 30_005,+ "openhuman.session_db_get_children",+ json!({ "sessionId": "no-such-session" }),+ )+ .await;+ let children = payload(&children, "session_db_get_children");+ assert_eq!(+ children.as_array().map(Vec::len),+ Some(0),+ "an unknown parent has no children: {children}"+ );++ harness.join.abort();+}++/// Failure paths: a missing required param is refused by name, and `get` for an+/// absent id is an error rather than a null row.+///+/// The wording is `core::all::validate_params`' — the schema gate at+/// `src/core/all.rs:1334` refuses on required-presence and declared type before+/// any handler body runs, so the handlers' own "missing required param: id"+/// strings never reach a caller over RPC.+#[tokio::test]+async fn session_db_rejects_missing_params_and_unknown_ids() {+ let _lock = env_lock();+ let harness = setup().await;++ let no_id = rpc(&harness.rpc_base, 30_101, "openhuman.session_db_get", json!({})).await;+ assert!(+ error_message(&no_id, "session_db_get without id").contains("missing required param 'id'"),+ "the refusal must name the param: {no_id}"+ );++ let no_session_id = rpc(+ &harness.rpc_base,+ 30_102,+ "openhuman.session_db_get_messages",+ json!({ "limit": 5 }),+ )+ .await;+ assert!(+ error_message(&no_session_id, "get_messages without sessionId")+ .contains("missing required param 'sessionId'"),+ "the refusal must name the param: {no_session_id}"+ );++ // `get` is the one read that resolves a single row, so absence is an error.+ let missing = rpc(+ &harness.rpc_base,+ 30_103,+ "openhuman.session_db_get",+ json!({ "id": "session-that-was-never-recorded" }),+ )+ .await;+ let message = error_message(&missing, "session_db_get for an unknown id");+ assert!(+ message.to_lowercase().contains("not found")+ || message.contains("session-that-was-never-recorded"),+ "the error must identify the missing session, got: {message}"+ );++ harness.join.abort();+}++// ── session_import ────────────────────────────────────────────────────────++/// `session_import.run` over a seeded legacy `session_raw/` directory:+/// dry-run plans without writing, the real run imports, and a second run is+/// idempotent because the item ledger says the work is done.+#[tokio::test]+async fn session_import_plans_imports_then_skips_on_rerun() {+ let _lock = env_lock();+ let harness = setup().await;++ let raw_dir = harness.workspace.join("session_raw");+ std::fs::create_dir_all(&raw_dir).expect("create session_raw");++ // The reader requires the first non-empty line to be the `_meta` header —+ // a transcript that starts with a message is rejected outright, so this+ // fixture is shaped like a real one rather than like a bare message log.+ let mut lines = vec![json!({+ "_meta": {+ "version": 1,+ "agent": "orchestrator",+ "dispatcher": "e2e",+ "created": "2026-09-07T10:00:00Z",+ "updated": "2026-09-07T10:05:00Z",+ "turn_count": 2,+ "input_tokens": 40,+ "output_tokens": 20,+ "cached_input_tokens": 0,+ "charged_amount_usd": 0.0,+ "thread_id": "e2e-session-import-thread",+ }+ })];+ for (role, content) in [+ ("user", "what is the capital of France?"),+ ("assistant", "Paris."),+ ("user", "and of Japan?"),+ ("assistant", "Tokyo."),+ ] {+ lines.push(json!({ "role": role, "content": content }));+ }+ let transcript = lines+ .iter()+ .map(Value::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ std::fs::write(raw_dir.join("20260907_capitals.jsonl"), transcript)+ .expect("write legacy transcript");++ // ── dry run: plans the work and writes nothing ──+ let planned = rpc(+ &harness.rpc_base,+ 31_001,+ "openhuman.session_import_run",+ json!({ "dry_run": true }),+ )+ .await;+ let planned = payload(&planned, "session_import_run dry");+ assert_eq!(planned.get("dry_run").and_then(Value::as_bool), Some(true));+ assert_eq!(+ planned.get("scanned").and_then(Value::as_u64),+ Some(1),+ "the seeded transcript must be discovered: {planned}"+ );+ assert_eq!(+ planned.get("messages_written").and_then(Value::as_u64),+ Some(0),+ "a dry run writes no messages: {planned}"+ );+ let planned_item = planned+ .get("items")+ .and_then(Value::as_array)+ .and_then(|items| items.first())+ .unwrap_or_else(|| panic!("dry run must report the item: {planned}"))+ .clone();+ assert_eq!(+ planned_item.get("action").and_then(Value::as_str),+ Some("would_import"),+ "dry-run action: {planned_item}"+ );+ // A dry run must not write the global marker either — proved below by the+ // real run still having work to do. Asserting on the store *directory* would+ // be wrong: `run_import` opens the stores before it decides to plan only.++ // ── real run: writes the messages into the TinyAgents store ──+ let imported = rpc(+ &harness.rpc_base,+ 31_002,+ "openhuman.session_import_run",+ json!({}),+ )+ .await;+ let imported = payload(&imported, "session_import_run");+ assert_eq!(imported.get("dry_run").and_then(Value::as_bool), Some(false));+ assert_eq!(+ imported.get("imported").and_then(Value::as_u64),+ Some(1),+ "one source imported: {imported}"+ );+ assert_eq!(+ imported.get("failed").and_then(Value::as_u64),+ Some(0),+ "no failures: {imported}"+ );+ assert_eq!(+ imported.get("messages_written").and_then(Value::as_u64),+ Some(4),+ "the four message lines are written; the `_meta` header is not a message: {imported}"+ );+ let item = imported+ .get("items")+ .and_then(Value::as_array)+ .and_then(|items| items.first())+ .unwrap_or_else(|| panic!("the real run must report the item: {imported}"))+ .clone();+ assert_eq!(item.get("action").and_then(Value::as_str), Some("imported"));+ assert_eq!(+ item.get("messages").and_then(Value::as_u64),+ Some(4),+ "the per-item count must agree with the run total: {item}"+ );+ assert_eq!(+ item.get("thread_id").and_then(Value::as_str),+ Some("e2e-session-import-thread"),+ "the thread id must come from the transcript's `_meta`, not be synthesized: {item}"+ );+ assert_eq!(+ item.get("stream").and_then(Value::as_str),+ Some("session.20260907_capitals.messages"),+ "messages go to a per-session journal stream named from the stem: {item}"+ );+ assert!(+ harness.workspace.join("tinyagents_store").exists(),+ "the real run must create the store"+ );++ // ── re-run: idempotent ──+ let again = rpc(+ &harness.rpc_base,+ 31_003,+ "openhuman.session_import_run",+ json!({}),+ )+ .await;+ let again = payload(&again, "session_import_run rerun");+ assert_eq!(+ again.get("messages_written").and_then(Value::as_u64),+ Some(0),+ "a second run must write nothing: {again}"+ );+ assert!(+ again.get("already_done").and_then(Value::as_bool) == Some(true)+ || again.get("skipped").and_then(Value::as_u64) == Some(1),+ "the re-run must be short-circuited by the marker or the item ledger: {again}"+ );++ harness.join.abort();+}++/// Failure path: `dry_run` is declared `Option<Bool>` in the schema, so the+/// dispatcher's type check refuses a string before `run_import` opens a store or+/// scans a directory.+#[tokio::test]+async fn session_import_rejects_malformed_params() {+ let _lock = env_lock();+ let harness = setup().await;++ let bad = rpc(+ &harness.rpc_base,+ 31_101,+ "openhuman.session_import_run",+ json!({ "dry_run": "yes-please" }),+ )+ .await;+ assert!(+ error_message(&bad, "session_import_run with a string dry_run")+ .contains("invalid type for param 'dry_run' in session_import.run"),+ "a wrong-typed param must be refused by name, with both types: {bad}"+ );++ harness.join.abort();+}++// ── tokenjuice ────────────────────────────────────────────────────────────++/// `tokenjuice.detect` → `.compress` → `.retrieve`: the full CCR round trip,+/// plus the invariants that must hold whichever branch the router takes.+///+/// A 400-row JSON array is the fixture because it is the one kind the existing+/// `json_rpc_e2e` coverage already pins `detect` on, so the cross-controller+/// assertion below rests on a classification asserted independently elsewhere.+/// In practice it compresses ~19× and takes the lossy path, so the `retrieve`+/// leg runs for real and the original is compared byte for byte.+///+/// **The lossy branch is guarded rather than assumed, and that is deliberate.**+/// Whether the router compresses is its own decision under a hint this RPC+/// cannot fully steer: `handle_compress` builds `ContentHint` from `tool_name`+/// alone (`inference/tokenjuice/schemas.rs:241-248`), leaving `explicit`,+/// `mime`, `extension` and `query` unreachable. Asserting `lossy == true`+/// unconditionally would pin a detector heuristic, not a contract — and the+/// same controller passes a 16 KB uniform *log* straight through untouched, so+/// the heuristic is not a stable thing to assert on. See+/// `~/tinyhuman/bugs/e2e-wave-tokenjuice-compress-drops-most-of-the-content-hint.md`.+///+/// What is asserted unconditionally is what must hold on every branch:+///+/// 1. `compress` and `detect` agree on the content kind — two controllers, one+/// classifier, and nothing else checks they stay in step;+/// 2. the reported byte counts describe the actual strings, not estimates;+/// 3. **nothing is lost**: a lossy compaction is recoverable through the token+/// byte-for-byte, and a pass-through returns the input unchanged.+#[tokio::test]+async fn tokenjuice_compress_agrees_with_detect_and_never_loses_content() {+ let _lock = env_lock();+ let harness = setup().await;++ // A JSON array: the one kind the existing `json_rpc_e2e` coverage already+ // pins `detect` on, so the cross-controller assertion below rests on a+ // classification that is independently asserted elsewhere.+ let rows: Vec<Value> = (0..400)+ .map(|i| json!({ "id": i, "name": format!("row-{i}"), "status": "ok", "score": i * 3 }))+ .collect();+ let content = Value::Array(rows).to_string();+ assert!(+ content.len() > 8_000,+ "the fixture must clear the 2048-byte compression floor with margin"+ );++ let detected = rpc(+ &harness.rpc_base,+ 32_001,+ "openhuman.tokenjuice_detect",+ json!({ "content": content }),+ )+ .await;+ let detected_kind = payload(&detected, "tokenjuice_detect")+ .get("kind")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("detect must report a kind: {detected}"))+ .to_string();+ assert_eq!(+ detected_kind, "json",+ "a JSON array must classify as json: {detected}"+ );++ let compressed = rpc(+ &harness.rpc_base,+ 32_002,+ "openhuman.tokenjuice_compress",+ json!({ "content": content, "tool_name": "session_store_e2e" }),+ )+ .await;+ let compressed = payload(&compressed, "tokenjuice_compress");++ // (1) One classifier, two controllers.+ assert_eq!(+ compressed.get("kind").and_then(Value::as_str),+ Some(detected_kind.as_str()),+ "compress must route on the same kind detect reports: {compressed}"+ );++ // (2) The byte counts describe the actual strings.+ let text = compressed+ .get("text")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("compress must return the routed text: {compressed}"));+ assert_eq!(+ compressed.get("originalBytes").and_then(Value::as_u64),+ Some(content.len() as u64),+ "originalBytes must be the byte length handed in: {compressed}"+ );+ assert_eq!(+ compressed.get("compactedBytes").and_then(Value::as_u64),+ Some(text.len() as u64),+ "compactedBytes is documented as the byte length of `text`: {compressed}"+ );++ // (3) Nothing is lost, on whichever branch the router took.+ let applied = compressed+ .get("applied")+ .and_then(Value::as_bool)+ .unwrap_or_else(|| panic!("compress must report whether it changed the content: {compressed}"));+ let lossy = compressed+ .get("lossy")+ .and_then(Value::as_bool)+ .unwrap_or_else(|| panic!("compress must report whether it dropped data: {compressed}"));++ if !applied {+ assert!(!lossy, "a pass-through cannot be lossy: {compressed}");+ assert_eq!(+ text, content,+ "a pass-through must return the input unchanged — byte for byte"+ );+ assert_eq!(+ compressed.get("compressor").and_then(Value::as_str),+ Some("none"),+ "a pass-through must name no compressor: {compressed}"+ );+ assert_eq!(+ compressed.get("ccrToken"),+ Some(&Value::Null),+ "nothing was offloaded, so there is no token to hand back: {compressed}"+ );+ } else {+ assert!(+ text.len() < content.len(),+ "an applied compaction must shrink the payload: {compressed}"+ );+ assert_ne!(+ compressed.get("compressor").and_then(Value::as_str),+ Some("none"),+ "an applied compaction must name the compressor that fired: {compressed}"+ );+ }++ if lossy {+ let token = compressed+ .get("ccrToken")+ .and_then(Value::as_str)+ .unwrap_or_else(|| {+ panic!("a lossy compaction over the CCR threshold must be recoverable: {compressed}")+ })+ .to_string();++ let retrieved = rpc(+ &harness.rpc_base,+ 32_003,+ "openhuman.tokenjuice_retrieve",+ json!({ "token": token }),+ )+ .await;+ let retrieved = payload(&retrieved, "tokenjuice_retrieve");+ assert_eq!(+ retrieved.get("found").and_then(Value::as_bool),+ Some(true),+ "the token minted by compress must resolve: {retrieved}"+ );+ assert_eq!(+ retrieved.get("content").and_then(Value::as_str),+ Some(content.as_str()),+ "retrieve must return the original verbatim — a compaction that \+ cannot be undone byte-for-byte has lost data"+ );+ }++ harness.join.abort();+}++/// Failure paths: `compress` needs content, and `retrieve` of a token that was+/// never minted is a clean `found: false` rather than an error.+#[tokio::test]+async fn tokenjuice_refuses_empty_input_and_misses_cleanly() {+ let _lock = env_lock();+ let harness = setup().await;++ let no_content = rpc(+ &harness.rpc_base,+ 32_101,+ "openhuman.tokenjuice_compress",+ json!({ "tool_name": "session_store_e2e" }),+ )+ .await;+ assert!(+ error_message(&no_content, "tokenjuice_compress without content").contains("content"),+ "the refusal must name the missing field: {no_content}"+ );++ let miss = rpc(+ &harness.rpc_base,+ 32_102,+ "openhuman.tokenjuice_retrieve",+ json!({ "token": "ccr:definitely-not-a-real-token" }),+ )+ .await;+ let miss = payload(&miss, "tokenjuice_retrieve miss");+ assert_eq!(+ miss.get("found").and_then(Value::as_bool),+ Some(false),+ "an unknown token is a miss, not an error: {miss}"+ );+ assert_eq!(+ miss.get("content"),+ Some(&Value::Null),+ "a miss carries no content: {miss}"+ );++ let no_token = rpc(+ &harness.rpc_base,+ 32_103,+ "openhuman.tokenjuice_retrieve",+ json!({}),+ )+ .await;+ assert!(+ error_message(&no_token, "tokenjuice_retrieve without token").contains("token"),+ "the refusal must name the missing field: {no_token}"+ );++ harness.join.abort();+}++// ── ai (artifacts) ────────────────────────────────────────────────────────++/// Write a `meta.json` for one artifact directly into the workspace, the way+/// the producer tools do, and return its id.+fn seed_artifact(+ workspace: &Path,+ id: &str,+ kind: &str,+ title: &str,+ created_at: &str,+ thread_id: Option<&str>,+) {+ let dir = workspace.join("artifacts").join(id);+ std::fs::create_dir_all(&dir).expect("create artifact dir");+ let body = format!("{title} body");+ let filename = format!("{id}.md");+ std::fs::write(dir.join(&filename), &body).expect("write artifact file");++ let mut meta = json!({+ "id": id,+ "kind": kind,+ "title": title,+ "path": format!("{id}/{filename}"),+ "size_bytes": body.len(),+ "status": "ready",+ "created_at": created_at,+ });+ if let Some(tid) = thread_id {+ meta.as_object_mut()+ .expect("meta object")+ .insert("thread_id".into(), json!(tid));+ }+ std::fs::write(+ dir.join("meta.json"),+ serde_json::to_string_pretty(&meta).expect("serialize meta"),+ )+ .expect("write meta.json");+}++/// The artifact read/delete surface over three seeded artifacts: newest-first+/// ordering, per-thread filtering that also narrows `total`, pagination, `get`+/// resolving an absolute path, and `delete` actually removing the row.+#[tokio::test]+async fn ai_artifacts_list_filter_get_and_delete() {+ let _lock = env_lock();+ let harness = setup().await;++ seed_artifact(+ &harness.workspace,+ "artifact-oldest",+ "document",+ "Oldest note",+ "2026-01-01T00:00:00Z",+ Some("thread-alpha"),+ );+ seed_artifact(+ &harness.workspace,+ "artifact-middle",+ "presentation",+ "Q2 deck",+ "2026-05-01T00:00:00Z",+ None,+ );+ seed_artifact(+ &harness.workspace,+ "artifact-newest",+ "document",+ "Newest note",+ "2026-09-01T00:00:00Z",+ Some("thread-alpha"),+ );++ // ── list: newest first, total is the workspace count ──+ let list = rpc(+ &harness.rpc_base,+ 33_001,+ "openhuman.ai_list_artifacts",+ json!({}),+ )+ .await;+ let list = payload(&list, "ai_list_artifacts");+ assert_eq!(list.get("total").and_then(Value::as_u64), Some(3));+ assert_eq!(list.get("limit").and_then(Value::as_u64), Some(50));+ let ids: Vec<&str> = list+ .get("artifacts")+ .and_then(Value::as_array)+ .expect("artifacts array")+ .iter()+ .filter_map(|a| a.get("id").and_then(Value::as_str))+ .collect();+ assert_eq!(+ ids,+ vec!["artifact-newest", "artifact-middle", "artifact-oldest"],+ "artifacts must be sorted by created_at descending"+ );++ // ── thread filter: narrows the page AND the total ──+ let filtered = rpc(+ &harness.rpc_base,+ 33_002,+ "openhuman.ai_list_artifacts",+ json!({ "thread_id": "thread-alpha" }),+ )+ .await;+ let filtered = payload(&filtered, "ai_list_artifacts filtered");+ assert_eq!(+ filtered.get("total").and_then(Value::as_u64),+ Some(2),+ "total must reflect the filtered set, not the workspace: {filtered}"+ );+ let filtered_ids: Vec<&str> = filtered+ .get("artifacts")+ .and_then(Value::as_array)+ .expect("artifacts array")+ .iter()+ .filter_map(|a| a.get("id").and_then(Value::as_str))+ .collect();+ assert_eq!(filtered_ids, vec!["artifact-newest", "artifact-oldest"]);++ // ── pagination: offset skips into the sorted list ──+ let page = rpc(+ &harness.rpc_base,+ 33_003,+ "openhuman.ai_list_artifacts",+ json!({ "offset": 1, "limit": 1 }),+ )+ .await;+ let page = payload(&page, "ai_list_artifacts paged");+ assert_eq!(page.get("total").and_then(Value::as_u64), Some(3));+ assert_eq!(page.get("offset").and_then(Value::as_u64), Some(1));+ let paged_ids: Vec<&str> = page+ .get("artifacts")+ .and_then(Value::as_array)+ .expect("artifacts array")+ .iter()+ .filter_map(|a| a.get("id").and_then(Value::as_str))+ .collect();+ assert_eq!(paged_ids, vec!["artifact-middle"]);++ // ── get: returns the meta plus a resolved absolute path ──+ let got = rpc(+ &harness.rpc_base,+ 33_004,+ "openhuman.ai_get_artifact",+ json!({ "artifact_id": "artifact-middle" }),+ )+ .await;+ let got = payload(&got, "ai_get_artifact");+ assert_eq!(got.get("title").and_then(Value::as_str), Some("Q2 deck"));+ assert_eq!(got.get("kind").and_then(Value::as_str), Some("presentation"));+ let absolute = got+ .get("absolute_path")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("get must add absolute_path: {got}"));+ assert!(+ Path::new(absolute).exists(),+ "absolute_path must point at the file on disk: {absolute}"+ );++ // ── delete: removes it from the listing ──+ let deleted = rpc(+ &harness.rpc_base,+ 33_005,+ "openhuman.ai_delete_artifact",+ json!({ "artifact_id": "artifact-oldest" }),+ )+ .await;+ let deleted = payload(&deleted, "ai_delete_artifact");+ assert_eq!(deleted.get("deleted").and_then(Value::as_bool), Some(true));+ assert_eq!(+ deleted.get("artifact_id").and_then(Value::as_str),+ Some("artifact-oldest")+ );++ let after = rpc(+ &harness.rpc_base,+ 33_006,+ "openhuman.ai_list_artifacts",+ json!({}),+ )+ .await;+ let after = payload(&after, "ai_list_artifacts after delete");+ assert_eq!(+ after.get("total").and_then(Value::as_u64),+ Some(2),+ "the deleted artifact must be gone: {after}"+ );+ assert!(+ !harness+ .workspace+ .join("artifacts")+ .join("artifact-oldest")+ .exists(),+ "delete must remove the directory too"+ );++ harness.join.abort();+}++/// Failure paths for the artifact surface: a traversal id is refused before+/// any filesystem access, an absent id is an error, and `regenerate` refuses+/// both a non-presentation artifact and a call with no routing context.+#[tokio::test]+async fn ai_artifacts_reject_traversal_absence_and_unregenerable_kinds() {+ let _lock = env_lock();+ let harness = setup().await;++ seed_artifact(+ &harness.workspace,+ "artifact-doc",+ "document",+ "A document",+ "2026-03-01T00:00:00Z",+ None,+ );++ let traversal = rpc(+ &harness.rpc_base,+ 33_101,+ "openhuman.ai_get_artifact",+ json!({ "artifact_id": "../../etc/passwd" }),+ )+ .await;+ assert!(+ error_message(&traversal, "ai_get_artifact traversal").contains("must not contain '/'"),+ "an id with a path separator must be refused by the validator: {traversal}"+ );++ let empty = rpc(+ &harness.rpc_base,+ 33_102,+ "openhuman.ai_delete_artifact",+ json!({ "artifact_id": " " }),+ )+ .await;+ assert!(+ error_message(&empty, "ai_delete_artifact blank id").contains("must not be empty"),+ "a whitespace-only id trims to empty and must be refused: {empty}"+ );++ let missing = rpc(+ &harness.rpc_base,+ 33_103,+ "openhuman.ai_get_artifact",+ json!({ "artifact_id": "artifact-that-does-not-exist" }),+ )+ .await;+ assert!(+ error_message(&missing, "ai_get_artifact absent").contains("artifact-that-does-not-exist"),+ "the error must identify the artifact: {missing}"+ );++ // regenerate needs routing context for the socket events it triggers.+ let no_routing = rpc(+ &harness.rpc_base,+ 33_104,+ "openhuman.ai_regenerate",+ json!({ "artifact_id": "artifact-doc", "thread_id": "", "client_id": "" }),+ )+ .await;+ assert!(+ error_message(&no_routing, "ai_regenerate without routing")+ .contains("thread_id + client_id"),+ "regenerate must refuse without event routing: {no_routing}"+ );++ // Only presentations persist the args a re-dispatch needs.+ let wrong_kind = rpc(+ &harness.rpc_base,+ 33_105,+ "openhuman.ai_regenerate",+ json!({+ "artifact_id": "artifact-doc",+ "thread_id": "thread-alpha",+ "client_id": "client-1",+ }),+ )+ .await;+ let message = error_message(&wrong_kind, "ai_regenerate on a document");+ assert!(+ message.contains("only supported for presentations") && message.contains("document"),+ "the refusal must name the rule and the actual kind, got: {message}"+ );++ harness.join.abort();+}++// ── test_support ──────────────────────────────────────────────────────────++/// The `test_support.*` controllers are compiled in only under+/// `e2e-test-support`, which the product feature set deliberately omits — that+/// gate is what keeps the destructive `openhuman.test_reset` out of shipped+/// binaries. Under the product features the five methods must be absent from+/// the schema catalog *and* unroutable, and this case fails if either the+/// `#[cfg]` at `src/core/all.rs` or the feature list stops holding that line.+#[cfg(not(feature = "e2e-test-support"))]+#[tokio::test]+async fn test_support_controllers_are_absent_without_their_feature() {+ let _lock = env_lock();+ let harness = setup().await;++ let catalog = schema_catalog(&harness.rpc_base).await;+ for method in [+ "openhuman.test_support_workspace_root",+ "openhuman.test_support_list_workspace_files",+ "openhuman.test_support_read_workspace_file",+ "openhuman.test_support_in_flight_chats",+ "openhuman.test_support_wallet_prepared_quotes",+ "openhuman.test_reset",+ ] {+ assert!(+ !catalog_has(&catalog, method),+ "{method} must not be advertised in a product-feature build"+ );++ let response = rpc(&harness.rpc_base, 34_001, method, json!({})).await;+ let message = error_message(&response, method);+ assert!(+ message.contains("unknown method"),+ "{method} must be unroutable, got: {message}"+ );+ }++ // The catalog is not empty — proof the assertions above are about these+ // methods specifically and not about a router that advertises nothing.+ assert!(+ catalog_has(&catalog, "openhuman.ai_list_artifacts"),+ "the schema catalog must still advertise the ungated controllers"+ );++ harness.join.abort();+}++/// The positive side of the same gate: with `e2e-test-support` on, the+/// introspection controllers resolve the live workspace, list and read files+/// inside it, refuse a path that escapes it, and report the two in-process+/// snapshots as empty for a process that has run no chat and prepared no quote.+#[cfg(feature = "e2e-test-support")]+#[tokio::test]+async fn test_support_introspection_reads_the_live_workspace() {+ let _lock = env_lock();+ let harness = setup().await;++ std::fs::create_dir_all(harness.workspace.join("notes")).expect("create notes dir");+ std::fs::write(harness.workspace.join("notes/readme.md"), "hello workspace")+ .expect("write fixture file");++ let root = rpc(+ &harness.rpc_base,+ 34_101,+ "openhuman.test_support_workspace_root",+ json!({}),+ )+ .await;+ let root = payload(&root, "test_support_workspace_root");+ assert_eq!(root.get("exists").and_then(Value::as_bool), Some(true));+ let reported = root+ .get("path")+ .and_then(Value::as_str)+ .expect("workspace_root returns a path");+ assert!(+ Path::new(reported).ends_with("workspace"),+ "workspace_root must name the configured workspace, got {reported}"+ );++ let listing = rpc(+ &harness.rpc_base,+ 34_102,+ "openhuman.test_support_list_workspace_files",+ json!({ "rel_root": "notes", "max_depth": 1 }),+ )+ .await;+ let listing = payload(&listing, "test_support_list_workspace_files");+ assert_eq!(listing.get("truncated").and_then(Value::as_bool), Some(false));+ let entries = listing+ .get("entries")+ .and_then(Value::as_array)+ .expect("entries array");+ assert!(+ entries+ .iter()+ .any(|e| e.get("rel_path").and_then(Value::as_str) == Some("readme.md")),+ "the seeded file must be listed: {listing}"+ );++ let read = rpc(+ &harness.rpc_base,+ 34_103,+ "openhuman.test_support_read_workspace_file",+ json!({ "rel_path": "notes/readme.md" }),+ )+ .await;+ let read = payload(&read, "test_support_read_workspace_file");+ assert_eq!(+ read.get("content_utf8").and_then(Value::as_str),+ Some("hello workspace")+ );+ assert_eq!(read.get("truncated").and_then(Value::as_bool), Some(false));++ // max_bytes truncates on a byte boundary and says so.+ let clipped = rpc(+ &harness.rpc_base,+ 34_104,+ "openhuman.test_support_read_workspace_file",+ json!({ "rel_path": "notes/readme.md", "max_bytes": 5 }),+ )+ .await;+ let clipped = payload(&clipped, "test_support_read_workspace_file clipped");+ assert_eq!(clipped.get("truncated").and_then(Value::as_bool), Some(true));+ assert_eq!(clipped.get("returned_bytes").and_then(Value::as_u64), Some(5));+ assert_eq!(+ clipped.get("content_utf8").and_then(Value::as_str),+ Some("hello")+ );++ // Failure path: a relative path that resolves outside the workspace root.+ let escape = rpc(+ &harness.rpc_base,+ 34_105,+ "openhuman.test_support_read_workspace_file",+ json!({ "rel_path": "../config.toml" }),+ )+ .await;+ assert!(+ error_message(&escape, "read_workspace_file escape").contains("escapes workspace root"),+ "a path resolving outside the workspace must be refused: {escape}"+ );++ // The two in-process snapshots: this process has run no chat turn and+ // prepared no wallet quote, so both must report an empty, well-formed view.+ let chats = rpc(+ &harness.rpc_base,+ 34_106,+ "openhuman.test_support_in_flight_chats",+ json!({}),+ )+ .await;+ let chats = payload(&chats, "test_support_in_flight_chats");+ assert_eq!(+ chats.get("entries").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "no chat is in flight in this process: {chats}"+ );++ let quotes = rpc(+ &harness.rpc_base,+ 34_107,+ "openhuman.test_support_wallet_prepared_quotes",+ json!({}),+ )+ .await;+ let quotes = payload("es, "test_support_wallet_prepared_quotes");+ assert_eq!(quotes.get("count").and_then(Value::as_u64), Some(0));+ assert_eq!(+ quotes.get("quotes").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "no prepared quote has been minted: {quotes}"+ );++ harness.join.abort();+}