Skip to content

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

test(e2e): cover 32 untouched RPC controllers across skills, MCP, medulla and todos\n\nNine namespaces went from 0% or partial to 100% on\n`scripts/check-domain-e2e-coverage.mjs`: skill_runtime (0/6), mcp_setup (0/6),\nmcp_audit (0/1), medulla (0/9), javascript (0/2), plus the uncovered halves of\nskills (4/10), mcp_clients (12/16), skill_registry (6/7) and todos (6/13).\n\nFour suites under `tests/raw_coverage/`, so they compile as modules of the\nexisting `raw_coverage_all` target rather than four new binaries each relinking\nthe ~936 MB openhuman rlib. 20 cases, 43 methods dispatched over the real axum\nJSON-RPC router.\n\nHermetic by construction — a planted skill and planted run logs on disk, a\nloopback MCP registry behind `MCP_OFFICIAL_REGISTRY_BASE`, a loopback Medulla\nbackend behind `OPENHUMAN_MEDULLA_BASE_URL`, and a session token planted through\n`AuthService` (production's own read path). Nothing leaves the machine.\n\nEvery case asserts on response content and covers at least one failure path.\nVerified by fault injection: four faults, one per suite, each tripping its own\nnamed assertion and nothing else.\n\n medulla list_messages drops the `after` cursor\n -> "only seq 3 is newer than 2"\n official registry stops filtering un-installable rows\n -> "the row declaring neither a remote nor a package must be dropped"\n run_log scanner stops parsing the footer duration\n -> "the footer's `duration: <n> ms` must be parsed to a number"\n todos_clear returns the board instead of emptying it\n -> "clear must return an empty board"\n\nClean 20/20, faulted 16/20 with exactly those four red, restored 20/20.\n\nThe `test` namespace is deliberately left at 0%. `test_support` registers behind\n`#[cfg(feature = "e2e-test-support")]` (src/core/all.rs:875), a gate in neither\n`[features] default` nor `scripts/ci/product-features.txt`, so under the product\nfeature string the reset answers `unknown method` and no `tests/**/*_e2e.rs`\ntarget can reach it. An honest 0% beats a hollow test.\n\nSix contract defects found on the way are written up for triage rather than\nfixed here; this PR changes no production code.\n\nClaude-Session: https://claude.ai/code/session_01Rx5Fzc5keoeUQB3MwMFqMM\n

M3gA-Mind283a548a4fd4
diff --git a/tests/raw_coverage/mcp_setup_clients_e2e.rs b/tests/raw_coverage/mcp_setup_clients_e2e.rs
new file mode 100644
index 0000000000..a497e09fce
--- /dev/null
+++ b/tests/raw_coverage/mcp_setup_clients_e2e.rs
@@ -0,0 +1,1132 @@
+//! JSON-RPC E2E coverage for the MCP guided-setup surface (`mcp_setup_*`), the
+//! four uncovered `mcp_clients_*` controllers, and `mcp_audit_list`.
+//!
+//! Run:
+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" mcp_setup_clients_e2e`
+//!
+//! ## The registry is a loopback fixture, not the live catalog
+//!
+//! `mcp_setup_search` / `mcp_setup_get` / `mcp_clients_registry_get` read the
+//! official `modelcontextprotocol/registry` — `GET /v0/servers` to list, `GET
+//! /v0/servers/{name}/versions` for detail
+//! (`vendor/tinymcp/.../registry/sources/official/mod.rs:1-6`). Its base is
+//! overridable via `MCP_OFFICIAL_REGISTRY_BASE` (`:353-360`), so this suite
+//! stands up an axum server speaking that shape and points the resolver at it.
+//! Nothing leaves the machine.
+//!
+//! Smithery, the second source, stays off: it is opt-in on an API key and this
+//! suite configures none, so search resolves the official source alone and the
+//! result set is exactly the fixture's (`sources/mod.rs:9-19`).
+//!
+//! ## The secret vault is driven through both of its RPCs at once
+//!
+//! `mcp_setup_request_secret` **blocks** until a UI answers — up to five
+//! minutes — and only then returns the ref. The ref reaches the UI over the
+//! event bus as `McpSetupSecretRequested`, so the pair can only be exercised
+//! together: this suite initialises the in-process bus, subscribes, issues
+//! `request_secret` on one task, reads the ref off the bus, and fulfils it with
+//! `mcp_setup_submit_secret` from another. That is the real shape of the flow,
+//! not a simulation of it.
+
+use std::net::SocketAddr;
+use std::path::Path;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+use axum::extract::Path as AxumPath;
+use axum::http::header::AUTHORIZATION;
+use axum::routing::get;
+use axum::{Json, Router};
+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::events::DomainEvent;
+use openhuman_core::core::jsonrpc::build_core_http_router;
+
+/// The bearer this suite *proposes*. It is only used if this suite happens to
+/// be the first in the aggregated binary to initialise the token subsystem —
+/// see `rpc_token()` below, which is what actually gets sent.
+const PROPOSED_RPC_TOKEN: &str = "mcp-setup-clients-e2e-token";
+
+static AUTH_INIT: OnceLock<()> = OnceLock::new();
+
+/// The crate-wide env lock, not a private one.
+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 plumbing ────────────────────────────────────────────────────────────
+
+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),
+ }
+ }
+}
+
+/// The bearer the running process will actually validate.
+///
+/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token`
+/// returns early once it is set. Every `tests/raw_coverage/` suite now shares
+/// one process, so the FIRST suite to initialise pins the token for all of
+/// them; a suite that sent its own hard-coded literal would get 401 whenever it
+/// lost that race, in an order that depends on libtest scheduling and load.
+///
+/// So: propose a token, initialise, then ask what the process settled on and
+/// send that. Correct whether this suite wins the race or loses it.
+fn rpc_token() -> &'static str {
+ AUTH_INIT.get_or_init(|| {
+ if std::env::var(CORE_TOKEN_ENV_VAR)
+ .map(|v| v.trim().is_empty())
+ .unwrap_or(true)
+ {
+ std::env::set_var(CORE_TOKEN_ENV_VAR, PROPOSED_RPC_TOKEN);
+ }
+ let token_dir = std::env::temp_dir().join("openhuman-mcp-setup-clients-e2e-auth");
+ std::fs::create_dir_all(&token_dir).expect("token dir");
+ init_rpc_token(&token_dir).expect("init rpc auth token");
+ });
+ openhuman_core::core::auth::get_rpc_token()
+ .expect("the token subsystem is initialised by the line above")
+}
+
+// ── Harness ─────────────────────────────────────────────────────────────────
+
+const MIN_CONFIG: &str = r#"api_url = "http://127.0.0.1:9"
+default_model = "mcp-e2e-model"
+
+[secrets]
+encrypt = false
+
+[local_ai]
+enabled = false
+
+[memory]
+provider = "none"
+embedding_provider = "none"
+embedding_model = "none"
+embedding_dimensions = 0
+
+[memory_tree]
+embedding_strict = false
+"#;
+
+struct Harness {
+ _tmp: TempDir,
+ _guards: Vec<EnvVarGuard>,
+ workspace: std::path::PathBuf,
+ rpc_base: String,
+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,
+}
+
+async fn setup(extra: Vec<EnvVarGuard>) -> Harness {
+ let _ = rpc_token();
+
+ let tmp = tempdir().expect("tempdir");
+ let home = tmp.path();
+ let openhuman_home = home.join(".openhuman");
+ std::fs::create_dir_all(&openhuman_home).expect("create .openhuman");
+ std::fs::write(openhuman_home.join("config.toml"), MIN_CONFIG).expect("write config.toml");
+ let _: openhuman_core::openhuman::config::Config =
+ toml::from_str(MIN_CONFIG).expect("test config must match the config schema");
+
+ let workspace = home.join("workspace");
+ std::fs::create_dir_all(&workspace).expect("create workspace");
+
+ let mut guards = vec![
+ EnvVarGuard::set_to_path("HOME", home),
+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),
+ EnvVarGuard::unset("BACKEND_URL"),
+ EnvVarGuard::unset("VITE_BACKEND_URL"),
+ EnvVarGuard::unset("OPENHUMAN_API_URL"),
+ // No Smithery key: the second registry source stays off, so the fixture
+ // below is the only catalog in play.
+ EnvVarGuard::unset("SMITHERY_API_KEY"),
+ EnvVarGuard::unset("MCP_OFFICIAL_REGISTRY_TOKEN"),
+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),
+ ];
+ guards.extend(extra);
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind rpc listener");
+ let addr: SocketAddr = listener.local_addr().expect("rpc listener addr");
+ let router = build_core_http_router(false);
+ let join = tokio::spawn(async move { axum::serve(listener, router).await });
+
+ Harness {
+ _tmp: tmp,
+ _guards: guards,
+ workspace,
+ rpc_base: format!("http://{addr}"),
+ join,
+ }
+}
+
+async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(120))
+ .build()
+ .expect("build client");
+ let url = format!("{}/rpc", base.trim_end_matches('/'));
+ let response = client
+ .post(&url)
+ .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))
+ .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))
+ .send()
+ .await
+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));
+ assert!(
+ response.status().is_success(),
+ "HTTP {} for {method}",
+ response.status()
+ );
+ response
+ .json::<Value>()
+ .await
+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))
+}
+
+fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {
+ if let Some(error) = value.get("error") {
+ panic!("{context}: unexpected JSON-RPC error: {error}");
+ }
+ value
+ .get("result")
+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"))
+}
+
+fn error_message<'a>(value: &'a Value, context: &str) -> &'a str {
+ 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 carries no message: {value}"))
+}
+
+// ── The fixture registry ────────────────────────────────────────────────────
+
+/// The two names the fixture catalog serves.
+const INSTALLABLE: &str = "io.github.e2e/planted-server";
+/// Declares neither a remote nor a package, so `is_installable()` is false and
+/// the list adapter must drop it.
+const UNINSTALLABLE: &str = "io.github.e2e/shell-only-row";
+
+fn fixture_server_record(name: &str, installable: bool) -> Value {
+ let mut record = json!({
+ "name": name,
+ "title": "Planted E2E Server",
+ "description": "A planted MCP server record for the e2e suite.",
+ "websiteUrl": "https://example.invalid/planted",
+ "remotes": [],
+ "packages": []
+ });
+ if installable {
+ record["packages"] = json!([{
+ "registryType": "npm",
+ "identifier": "@e2e/planted-server",
+ "environmentVariables": [
+ {
+ "name": "PLANTED_API_KEY",
+ "description": "The credential the planted server needs.",
+ "isRequired": true,
+ "isSecret": true
+ }
+ ]
+ }]);
+ }
+ record
+}
+
+/// An axum server speaking the official registry's list + versions shapes.
+async fn serve_fixture_registry() -> (
+ SocketAddr,
+ tokio::task::JoinHandle<Result<(), std::io::Error>>,
+) {
+ async fn list() -> Json<Value> {
+ Json(json!({
+ "servers": [
+ { "server": fixture_server_record(INSTALLABLE, true) },
+ { "server": fixture_server_record(UNINSTALLABLE, false) }
+ ],
+ // Empty next cursor: the adapter treats it as absent, so the page
+ // bound stays at the current page rather than paging forever.
+ "metadata": { "nextCursor": "" }
+ }))
+ }
+
+ async fn versions(AxumPath(name): AxumPath<String>) -> Json<Value> {
+ if name == INSTALLABLE {
+ Json(json!({
+ "servers": [{ "server": fixture_server_record(INSTALLABLE, true) }]
+ }))
+ } else {
+ // The registry lists no version of it — the adapter's
+ // `Error::UnknownServer` path.
+ Json(json!({ "servers": [] }))
+ }
+ }
+
+ let app = Router::new()
+ .route("/v0/servers", get(list))
+ .route("/v0/servers/{name}/versions", get(versions));
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind fixture registry");
+ let addr = listener.local_addr().expect("fixture registry addr");
+ let join = tokio::spawn(async move { axum::serve(listener, app).await });
+ (addr, join)
+}
+
+// ── mcp_setup: the catalog half ─────────────────────────────────────────────
+
+/// `mcp_setup_search` and `mcp_setup_get` against the fixture registry.
+#[tokio::test]
+async fn mcp_setup_search_and_get_read_the_configured_registry() {
+ let _lock = env_lock();
+ let (registry_addr, registry_join) = serve_fixture_registry().await;
+ let harness = setup(vec![EnvVarGuard::set(
+ "MCP_OFFICIAL_REGISTRY_BASE",
+ &format!("http://{registry_addr}"),
+ )])
+ .await;
+
+ let found = rpc(
+ &harness.rpc_base,
+ 200,
+ "openhuman.mcp_setup_search",
+ json!({ "query": "planted", "page": 1, "page_size": 10 }),
+ )
+ .await;
+ let found = ok(&found, "mcp_setup_search");
+ let servers = found
+ .get("servers")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("search has no `servers` array: {found}"));
+
+ // Exactly one row: the un-installable record must be filtered out rather
+ // than shown as a dead end the user can only discover by trying.
+ assert_eq!(
+ servers.len(),
+ 1,
+ "the row declaring neither a remote nor a package must be dropped: {found}"
+ );
+ let row = &servers[0];
+ assert_eq!(
+ row.get("qualified_name").and_then(Value::as_str),
+ Some(INSTALLABLE),
+ "the surviving row must be the installable one: {row}"
+ );
+ assert_eq!(
+ row.get("source").and_then(Value::as_str),
+ Some("mcp_official"),
+ "every row must be tagged with the registry it came from: {row}"
+ );
+ assert_eq!(
+ row.get("display_name").and_then(Value::as_str),
+ Some("Planted E2E Server"),
+ "the declared title must win over the derived one: {row}"
+ );
+ assert_eq!(
+ row.get("auth_kind").and_then(Value::as_str),
+ Some("api_key"),
+ "a package declaring an `isSecret` env var must be badged as needing a key: {row}"
+ );
+ assert_eq!(
+ found.get("page").and_then(Value::as_u64),
+ Some(1),
+ "the requested page must be echoed: {found}"
+ );
+ assert_eq!(
+ found.get("total_pages").and_then(Value::as_u64),
+ Some(1),
+ "an empty nextCursor means this is the last page: {found}"
+ );
+
+ // `get` adds `required_env_keys`, which is the whole reason the setup
+ // dialog calls it rather than reading the search row.
+ let detail = rpc(
+ &harness.rpc_base,
+ 201,
+ "openhuman.mcp_setup_get",
+ json!({ "qualified_name": INSTALLABLE }),
+ )
+ .await;
+ let detail = ok(&detail, "mcp_setup_get");
+ let server = detail
+ .get("server")
+ .unwrap_or_else(|| panic!("get has no `server`: {detail}"));
+ assert_eq!(
+ server.get("qualified_name").and_then(Value::as_str),
+ Some(INSTALLABLE)
+ );
+ assert_eq!(
+ server
+ .get("required_env_keys")
+ .and_then(Value::as_array)
+ .map(|keys| keys.iter().filter_map(Value::as_str).collect::<Vec<_>>()),
+ Some(vec!["PLANTED_API_KEY"]),
+ "the declared secret env var must be injected as a required key: {server}"
+ );
+ // The package became a stdio connection with a worked example.
+ let connections = server
+ .get("connections")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("detail has no `connections`: {server}"));
+ assert_eq!(
+ connections.len(),
+ 1,
+ "one package, one connection: {server}"
+ );
+ assert_eq!(
+ connections[0].get("type").and_then(Value::as_str),
+ Some("stdio"),
+ "an npm package must become a stdio connection: {server}"
+ );
+
+ // Failure path 1: a blank name is refused by the shared identifier guard,
+ // before any network call.
+ let blank = rpc(
+ &harness.rpc_base,
+ 202,
+ "openhuman.mcp_setup_get",
+ json!({ "qualified_name": " " }),
+ )
+ .await;
+ assert!(
+ error_message(&blank, "mcp_setup_get blank").contains("qualified_name must not be empty"),
+ "a blank qualified_name must be named in the refusal: {blank}"
+ );
+
+ // Failure path 2: the param is absent entirely — a different error from a
+ // blank one, and it must stay different.
+ let absent = rpc(&harness.rpc_base, 203, "openhuman.mcp_setup_get", json!({})).await;
+ assert!(
+ error_message(&absent, "mcp_setup_get absent").contains("missing required param"),
+ "an absent qualified_name must be a missing-param error: {absent}"
+ );
+
+ // Failure path 3: a name the registry lists no version of.
+ let unknown = rpc(
+ &harness.rpc_base,
+ 204,
+ "openhuman.mcp_setup_get",
+ json!({ "qualified_name": UNINSTALLABLE }),
+ )
+ .await;
+ assert!(
+ unknown.get("error").is_some(),
+ "a name with no published version must error, not return an empty detail: {unknown}"
+ );
+
+ registry_join.abort();
+ harness.join.abort();
+}
+
+// ── mcp_setup: the secret half ──────────────────────────────────────────────
+
+/// `mcp_setup_request_secret` + `mcp_setup_submit_secret`, driven as the pair
+/// they actually are.
+///
+/// `request_secret` blocks on the vault until a UI answers, publishing the ref
+/// on the event bus on the way in. This case plays both halves: one task issues
+/// the request, and the ref that comes back over the bus is what the other task
+/// submits. Asserting only one half would assert nothing — the request never
+/// returns without the submit, and the submit has no ref without the request.
+#[tokio::test]
+async fn mcp_setup_secret_request_blocks_until_the_matching_submit_lands() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ openhuman_core::core::bus::init().await.expect("bus init");
+
+ // Capture the ref the flow publishes for the UI.
+ struct RefCatcher {
+ tx: tokio::sync::mpsc::UnboundedSender<(String, String, String)>,
+ }
+
+ #[async_trait::async_trait]
+ impl tinybus::EventHandler<DomainEvent> for RefCatcher {
+ fn name(&self) -> &str {
+ "mcp-setup-e2e::ref-catcher"
+ }
+
+ async fn handle(&self, event: &DomainEvent) {
+ if let DomainEvent::McpSetupSecretRequested {
+ ref_id,
+ key_name,
+ prompt,
+ } = event
+ {
+ let _ = self
+ .tx
+ .send((ref_id.clone(), key_name.clone(), prompt.clone()));
+ }
+ }
+ }
+
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+ let _subscription = openhuman_core::core::bus::BUS
+ .subscribe(Arc::new(RefCatcher { tx }))
+ .expect("the in-process bus accepts a subscriber once init() has run");
+
+ let base = harness.rpc_base.clone();
+ let request = tokio::spawn(async move {
+ rpc(
+ &base,
+ 210,
+ "openhuman.mcp_setup_request_secret",
+ json!({ "key_name": "PLANTED_API_KEY", "prompt": "Paste the planted key." }),
+ )
+ .await
+ });
+
+ let (ref_id, key_name, prompt) = tokio::time::timeout(Duration::from_secs(30), rx.recv())
+ .await
+ .expect("the request must publish its ref promptly")
+ .expect("the ref-catcher channel stays open");
+ assert_eq!(
+ key_name, "PLANTED_API_KEY",
+ "the published event must carry the requested key name"
+ );
+ assert_eq!(
+ prompt, "Paste the planted key.",
+ "the published event must carry the prompt the UI renders"
+ );
+ assert!(
+ ref_id.starts_with("secret://"),
+ "the minted handle must be an opaque `secret://` ref, got {ref_id}"
+ );
+
+ // The request is still blocked: nothing has answered it yet. Proving that
+ // is the point — a `request_secret` that returned early would hand the
+ // agent a ref with no value behind it.
+ assert!(
+ !request.is_finished(),
+ "request_secret must not return before a value is submitted"
+ );
+
+ let submitted = rpc(
+ &harness.rpc_base,
+ 211,
+ "openhuman.mcp_setup_submit_secret",
+ json!({ "ref_id": ref_id, "value": "planted-secret-value" }),
+ )
+ .await;
+ let submitted = ok(&submitted, "mcp_setup_submit_secret");
+ assert_eq!(
+ submitted.get("ref").and_then(Value::as_str),
+ Some(ref_id.as_str()),
+ "submit must echo the ref it fulfilled: {submitted}"
+ );
+ assert_eq!(
+ submitted.get("fulfilled").and_then(Value::as_bool),
+ Some(true),
+ "a first submit must report fulfilled: {submitted}"
+ );
+
+ // Now the blocked request completes, returning the ref — and never the
+ // value, which is the security property the whole indirection exists for.
+ let requested = tokio::time::timeout(Duration::from_secs(30), request)
+ .await
+ .expect("request_secret must return once the submit lands")
+ .expect("request task must not panic");
+ let requested = ok(&requested, "mcp_setup_request_secret");
+ assert_eq!(
+ requested.get("ref").and_then(Value::as_str),
+ Some(ref_id.as_str()),
+ "request_secret returns the same ref it published: {requested}"
+ );
+ assert_eq!(
+ requested.get("key_name").and_then(Value::as_str),
+ Some("PLANTED_API_KEY")
+ );
+ assert!(
+ !requested.to_string().contains("planted-secret-value"),
+ "the raw secret must NEVER cross the model-facing surface: {requested}"
+ );
+
+ // A second submit against the same ref is refused — the ref is single-use.
+ let replay = rpc(
+ &harness.rpc_base,
+ 212,
+ "openhuman.mcp_setup_submit_secret",
+ json!({ "ref_id": ref_id, "value": "a-different-value" }),
+ )
+ .await;
+ let message = error_message(&replay, "mcp_setup_submit_secret replay");
+ assert!(
+ message.contains("unknown or already submitted"),
+ "replaying a ref must be refused, got: {message}"
+ );
+
+ // A syntactically invalid ref never reaches the vault.
+ let malformed = rpc(
+ &harness.rpc_base,
+ 213,
+ "openhuman.mcp_setup_submit_secret",
+ json!({ "ref_id": "../../etc/passwd", "value": "nope" }),
+ )
+ .await;
+ assert!(
+ error_message(&malformed, "mcp_setup_submit_secret malformed").contains("invalid ref_id"),
+ "a malformed ref must be refused by the parser: {malformed}"
+ );
+
+ // And the request half validates its own inputs before touching the vault.
+ let blank_key = rpc(
+ &harness.rpc_base,
+ 214,
+ "openhuman.mcp_setup_request_secret",
+ json!({ "key_name": " ", "prompt": "anything" }),
+ )
+ .await;
+ assert!(
+ error_message(&blank_key, "request_secret blank key")
+ .contains("key_name must not be empty"),
+ "a blank key_name must be refused without blocking for five minutes: {blank_key}"
+ );
+
+ harness.join.abort();
+}
+
+// ── mcp_setup: the install half ─────────────────────────────────────────────
+
+/// `mcp_setup_test_connection` and `mcp_setup_install_and_connect`.
+///
+/// Both take `{ENV_KEY: secret://…}` handles, and both parse those handles
+/// before doing anything else — which is the boundary this case asserts, since
+/// spawning a real candidate server would need a registry-resolvable package
+/// and a subprocess.
+///
+/// `test_connection` is additionally documented to report a failed dial as
+/// `ok: false` **with the reason**, rather than raising — that contract is what
+/// lets the setup agent retry instead of aborting, and it is asserted here
+/// against a name the fixture registry does not publish.
+#[tokio::test]
+async fn mcp_setup_install_paths_validate_handles_and_report_dial_failure_in_band() {
+ let _lock = env_lock();
+ let (registry_addr, registry_join) = serve_fixture_registry().await;
+ let harness = setup(vec![EnvVarGuard::set(
+ "MCP_OFFICIAL_REGISTRY_BASE",
+ &format!("http://{registry_addr}"),
+ )])
+ .await;
+
+ // A handle that is not a `secret://<hex>` ref is rejected by the parser,
+ // for both methods, before any dial.
+ for (id, method) in [
+ (220, "openhuman.mcp_setup_test_connection"),
+ (221, "openhuman.mcp_setup_install_and_connect"),
+ ] {
+ let bad_handle = rpc(
+ &harness.rpc_base,
+ id,
+ method,
+ json!({
+ "qualified_name": INSTALLABLE,
+ "env_refs": { "PLANTED_API_KEY": "not-a-ref!!" }
+ }),
+ )
+ .await;
+ assert!(
+ error_message(&bad_handle, method).contains("invalid ref_id"),
+ "{method} must refuse a malformed handle: {bad_handle}"
+ );
+ }
+
+ // A blank qualified_name is refused ahead of the handles.
+ let blank = rpc(
+ &harness.rpc_base,
+ 222,
+ "openhuman.mcp_setup_test_connection",
+ json!({ "qualified_name": "", "env_refs": {} }),
+ )
+ .await;
+ assert!(
+ error_message(&blank, "test_connection blank name")
+ .contains("qualified_name must not be empty"),
+ "a blank name must be refused: {blank}"
+ );
+
+ // `env_refs` is required, not defaulted — omitting it must not silently
+ // dial with no credentials.
+ let no_refs = rpc(
+ &harness.rpc_base,
+ 223,
+ "openhuman.mcp_setup_install_and_connect",
+ json!({ "qualified_name": INSTALLABLE }),
+ )
+ .await;
+ assert!(
+ error_message(&no_refs, "install_and_connect no env_refs").contains("env_refs"),
+ "an absent env_refs must be named in the refusal: {no_refs}"
+ );
+
+ // The in-band failure contract: a dial that cannot happen is reported as
+ // `ok: false` with a reason, NOT as a JSON-RPC error.
+ let dial = rpc(
+ &harness.rpc_base,
+ 224,
+ "openhuman.mcp_setup_test_connection",
+ json!({ "qualified_name": UNINSTALLABLE, "env_refs": {} }),
+ )
+ .await;
+ let dial = ok(
+ &dial,
+ "mcp_setup_test_connection must not raise on a failed dial",
+ );
+ assert_eq!(
+ dial.get("ok").and_then(Value::as_bool),
+ Some(false),
+ "a dial that could not succeed must report ok:false: {dial}"
+ );
+ assert!(
+ dial.get("error")
+ .and_then(Value::as_str)
+ .is_some_and(|e| !e.trim().is_empty()),
+ "ok:false must carry a non-empty reason the agent can act on: {dial}"
+ );
+ assert!(
+ dial.get("tools").is_none_or(Value::is_null),
+ "`tools` must be absent when the dial failed: {dial}"
+ );
+
+ // `install_and_connect` on the same name does NOT get the in-band
+ // treatment — it maps the failure to an RPC error. Pinned because the
+ // schema claims otherwise: it declares a `status` output of `connected` |
+ // `installed_disconnected`, and the handler emits no `status` field at all
+ // and cannot produce the second value. See
+ // `~/tinyhuman/bugs/e2e-wave-mcp-setup-install-status-field-never-emitted.md`.
+ let install = rpc(
+ &harness.rpc_base,
+ 225,
+ "openhuman.mcp_setup_install_and_connect",
+ json!({ "qualified_name": UNINSTALLABLE, "env_refs": {} }),
+ )
+ .await;
+ assert!(
+ install.get("error").is_some(),
+ "install_and_connect raises where test_connection reports in band; if this \
+ starts returning a result the two have been reconciled and the bug note \
+ needs updating: {install}"
+ );
+
+ registry_join.abort();
+ harness.join.abort();
+}
+
+// ── mcp_clients ─────────────────────────────────────────────────────────────
+
+/// The four uncovered `mcp_clients_*` controllers.
+///
+/// `registry_get` reads the fixture catalog; `detect_auth` and `oauth_begin`
+/// address an *installed* server by UUID, so with nothing installed the
+/// interesting assertion is that they refuse a name they cannot resolve rather
+/// than dialling something arbitrary. `config_assist` needs both the catalog
+/// and an inference turn, so it is asserted at its catalog boundary.
+#[tokio::test]
+async fn mcp_clients_registry_get_and_the_per_server_controllers() {
+ let _lock = env_lock();
+ let (registry_addr, registry_join) = serve_fixture_registry().await;
+ let harness = setup(vec![EnvVarGuard::set(
+ "MCP_OFFICIAL_REGISTRY_BASE",
+ &format!("http://{registry_addr}"),
+ )])
+ .await;
+
+ // `mcp_clients_registry_get` — the install dialog's one round trip, which
+ // must carry the credential names alongside the detail.
+ let detail = rpc(
+ &harness.rpc_base,
+ 230,
+ "openhuman.mcp_clients_registry_get",
+ json!({ "qualified_name": INSTALLABLE }),
+ )
+ .await;
+ let detail = ok(&detail, "mcp_clients_registry_get");
+ let server = detail
+ .get("server")
+ .unwrap_or_else(|| panic!("no `server` in registry_get: {detail}"));
+ assert_eq!(
+ server.get("qualified_name").and_then(Value::as_str),
+ Some(INSTALLABLE)
+ );
+ assert_eq!(
+ server
+ .get("required_env_keys")
+ .and_then(Value::as_array)
+ .map(|k| k.iter().filter_map(Value::as_str).collect::<Vec<_>>()),
+ Some(vec!["PLANTED_API_KEY"]),
+ "registry_get must inject the credential names, not make the dialog \
+ fetch them separately: {server}"
+ );
+ assert_eq!(
+ server.get("source").and_then(Value::as_str),
+ Some("mcp_official"),
+ "the detail must name the registry it came from so an install can route \
+ its lookup back: {server}"
+ );
+
+ let blank = rpc(
+ &harness.rpc_base,
+ 231,
+ "openhuman.mcp_clients_registry_get",
+ json!({ "qualified_name": " " }),
+ )
+ .await;
+ assert!(
+ error_message(&blank, "registry_get blank").contains("qualified_name must not be empty"),
+ "a blank name must be refused: {blank}"
+ );
+
+ // `detect_auth` / `oauth_begin` address an installed server by id. Nothing
+ // is installed, so both must refuse — and refuse *by name*, so an operator
+ // can tell "no such server" from "the probe failed".
+ for (id, method) in [
+ (232, "openhuman.mcp_clients_detect_auth"),
+ (233, "openhuman.mcp_clients_oauth_begin"),
+ ] {
+ let blank_id = rpc(&harness.rpc_base, id, method, json!({ "server_id": " " })).await;
+ assert!(
+ error_message(&blank_id, method).contains("server_id must not be empty"),
+ "{method} must refuse a blank server_id: {blank_id}"
+ );
+
+ let unknown = rpc(
+ &harness.rpc_base,
+ id + 100,
+ method,
+ json!({ "server_id": "00000000-0000-4000-8000-000000000000" }),
+ )
+ .await;
+ assert!(
+ unknown.get("error").is_some(),
+ "{method} against an uninstalled server id must error rather than \
+ probing something arbitrary: {unknown}"
+ );
+ // A UUID that resolves to nothing must not come back as a usable
+ // authorize URL — that would be an open redirect waiting to happen.
+ assert!(
+ unknown.get("result").is_none(),
+ "{method} must not return a result for an unknown server: {unknown}"
+ );
+ }
+
+ // `config_assist` validates its identifier, then needs the catalog detail
+ // before it can build a prompt. A name the registry cannot resolve fails at
+ // that fetch, with the message saying so.
+ let assist_blank = rpc(
+ &harness.rpc_base,
+ 240,
+ "openhuman.mcp_clients_config_assist",
+ json!({ "qualified_name": "", "user_message": "how do I set this up?" }),
+ )
+ .await;
+ assert!(
+ error_message(&assist_blank, "config_assist blank")
+ .contains("qualified_name must not be empty"),
+ "config_assist must refuse a blank name: {assist_blank}"
+ );
+
+ let assist_unknown = rpc(
+ &harness.rpc_base,
+ 241,
+ "openhuman.mcp_clients_config_assist",
+ json!({ "qualified_name": UNINSTALLABLE, "user_message": "how do I set this up?" }),
+ )
+ .await;
+ let message = error_message(&assist_unknown, "config_assist unknown server");
+ assert!(
+ message.contains("Failed to fetch registry detail"),
+ "config_assist must say the catalog lookup is what failed, not surface a \
+ bare transport error, got: {message}"
+ );
+
+ // `user_message` is required — a caller that forgets it must be told, not
+ // handed an assistant turn on an empty question.
+ let assist_no_message = rpc(
+ &harness.rpc_base,
+ 242,
+ "openhuman.mcp_clients_config_assist",
+ json!({ "qualified_name": INSTALLABLE }),
+ )
+ .await;
+ assert!(
+ error_message(&assist_no_message, "config_assist no message").contains("user_message"),
+ "an absent user_message must be named: {assist_no_message}"
+ );
+
+ registry_join.abort();
+ harness.join.abort();
+}
+
+// ── mcp_audit ───────────────────────────────────────────────────────────────
+
+/// `mcp_audit_list` — the write-audit log's only reader, exercised over rows
+/// this case records through the audit API so the content is knowable.
+#[tokio::test]
+async fn mcp_audit_list_filters_and_orders_the_write_log() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+
+ // Empty first: an audit log with no rows must read as an empty list, not
+ // as an error — an operator opening the panel on a fresh install sees this.
+ let empty = rpc(
+ &harness.rpc_base,
+ 250,
+ "openhuman.mcp_audit_list",
+ json!({}),
+ )
+ .await;
+ assert_eq!(
+ ok(&empty, "mcp_audit_list empty")
+ .get("records")
+ .and_then(Value::as_array)
+ .map(Vec::len),
+ Some(0),
+ "a fresh workspace must list zero records: {empty}"
+ );
+
+ // Seed three rows: two clients, two tools, one failure.
+ let config = openhuman_core::openhuman::config::Config {
+ workspace_dir: harness.workspace.clone(),
+ ..openhuman_core::openhuman::config::Config::default()
+ };
+ use openhuman_core::openhuman::mcp::audit::{record_write, NewMcpWriteRecord};
+ for (ts, client, tool, success, error) in [
+ (1_000_i64, "mcp:claude-desktop", "memory.store", true, None),
+ (
+ 2_000,
+ "mcp:claude-desktop",
+ "memory.delete",
+ false,
+ Some("denied by policy"),
+ ),
+ (3_000, "mcp:some-other-client", "memory.store", true, None),
+ ] {
+ record_write(
+ &config,
+ NewMcpWriteRecord {
+ timestamp_ms: ts,
+ client_info: client.to_string(),
+ tool_name: tool.to_string(),
+ args_summary: json!({ "keys": ["a", "b"] }),
+ resulting_chunk_id: None,
+ success,
+ error_message: error.map(str::to_string),
+ },
+ )
+ .expect("record an audit row");
+ }
+
+ let all = rpc(
+ &harness.rpc_base,
+ 251,
+ "openhuman.mcp_audit_list",
+ json!({}),
+ )
+ .await;
+ let all = ok(&all, "mcp_audit_list all");
+ let records = all
+ .get("records")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("no `records` array: {all}"));
+ assert_eq!(records.len(), 3, "all three rows must come back: {all}");
+ assert_eq!(
+ records
+ .iter()
+ .filter_map(|r| r.get("timestamp_ms").and_then(Value::as_i64))
+ .collect::<Vec<_>>(),
+ vec![3_000, 2_000, 1_000],
+ "records must be ordered newest-first, as the schema documents: {all}"
+ );
+ // The failed attempt is retained, with its reason — an audit log that kept
+ // only successes would be useless for the thing it exists for.
+ let failed = records
+ .iter()
+ .find(|r| r.get("success").and_then(Value::as_bool) == Some(false))
+ .unwrap_or_else(|| panic!("the rejected write must be retained: {all}"));
+ assert_eq!(
+ failed.get("error_message").and_then(Value::as_str),
+ Some("denied by policy"),
+ "a failed write must keep its reason: {failed}"
+ );
+ assert_eq!(
+ failed.get("tool_name").and_then(Value::as_str),
+ Some("memory.delete")
+ );
+
+ // Each filter narrows, and they are exact matches rather than substrings.
+ let by_client = rpc(
+ &harness.rpc_base,
+ 252,
+ "openhuman.mcp_audit_list",
+ json!({ "client_filter": "mcp:some-other-client" }),
+ )
+ .await;
+ let by_client = ok(&by_client, "mcp_audit_list client_filter");
+ let rows = by_client
+ .get("records")
+ .and_then(Value::as_array)
+ .expect("records");
+ assert_eq!(
+ rows.len(),
+ 1,
+ "the client filter must narrow to one: {by_client}"
+ );
+ assert_eq!(
+ rows[0].get("client_info").and_then(Value::as_str),
+ Some("mcp:some-other-client")
+ );
+
+ let by_tool = rpc(
+ &harness.rpc_base,
+ 253,
+ "openhuman.mcp_audit_list",
+ json!({ "tool_filter": "memory.store" }),
+ )
+ .await;
+ assert_eq!(
+ ok(&by_tool, "mcp_audit_list tool_filter")
+ .get("records")
+ .and_then(Value::as_array)
+ .map(Vec::len),
+ Some(2),
+ "the tool filter must match exactly two: {by_tool}"
+ );
+
+ // `memory.` is a prefix of both tool names — an exact filter must match
+ // neither, which is what stops a filter quietly widening.
+ let prefix = rpc(
+ &harness.rpc_base,
+ 254,
+ "openhuman.mcp_audit_list",
+ json!({ "tool_filter": "memory." }),
+ )
+ .await;
+ assert_eq!(
+ ok(&prefix, "mcp_audit_list prefix filter")
+ .get("records")
+ .and_then(Value::as_array)
+ .map(Vec::len),
+ Some(0),
+ "the tool filter is exact, not a prefix match: {prefix}"
+ );
+
+ let successes = rpc(
+ &harness.rpc_base,
+ 255,
+ "openhuman.mcp_audit_list",
+ json!({ "success_only": true }),
+ )
+ .await;
+ let successes = ok(&successes, "mcp_audit_list success_only");
+ let rows = successes
+ .get("records")
+ .and_then(Value::as_array)
+ .expect("records");
+ assert_eq!(
+ rows.len(),
+ 2,
+ "success_only must drop the failure: {successes}"
+ );
+ assert!(
+ rows.iter()
+ .all(|r| r.get("success").and_then(Value::as_bool) == Some(true)),
+ "success_only must return only successes: {successes}"
+ );
+
+ let since = rpc(
+ &harness.rpc_base,
+ 256,
+ "openhuman.mcp_audit_list",
+ json!({ "since_ms": 2_000 }),
+ )
+ .await;
+ assert_eq!(
+ ok(&since, "mcp_audit_list since_ms")
+ .get("records")
+ .and_then(Value::as_array)
+ .map(Vec::len),
+ Some(2),
+ "since_ms is inclusive of its own boundary: {since}"
+ );
+
+ // Paging: limit then offset walk the newest-first set without overlap.
+ let page_one = rpc(
+ &harness.rpc_base,
+ 257,
+ "openhuman.mcp_audit_list",
+ json!({ "limit": 1 }),
+ )
+ .await;
+ let page_two = rpc(
+ &harness.rpc_base,
+ 258,
+ "openhuman.mcp_audit_list",
+ json!({ "limit": 1, "offset": 1 }),
+ )
+ .await;
+ let first = ok(&page_one, "audit page one")
+ .get("records")
+ .and_then(Value::as_array)
+ .expect("records")
+ .clone();
+ let second = ok(&page_two, "audit page two")
+ .get("records")
+ .and_then(Value::as_array)
+ .expect("records")
+ .clone();
+ assert_eq!(first.len(), 1, "limit 1 returns one row: {page_one}");
+ assert_eq!(
+ second.len(),
+ 1,
+ "limit 1 offset 1 returns one row: {page_two}"
+ );
+ assert_eq!(
+ first[0].get("timestamp_ms").and_then(Value::as_i64),
+ Some(3_000)
+ );
+ assert_eq!(
+ second[0].get("timestamp_ms").and_then(Value::as_i64),
+ Some(2_000),
+ "offset must skip from the newest end, not restart: {page_two}"
+ );
+
+ harness.join.abort();
+}
diff --git a/tests/raw_coverage/medulla_session_e2e.rs b/tests/raw_coverage/medulla_session_e2e.rs
new file mode 100644
index 0000000000..2545293017
--- /dev/null
+++ b/tests/raw_coverage/medulla_session_e2e.rs
@@ -0,0 +1,1129 @@
+//! JSON-RPC E2E coverage for the `openhuman.medulla_*` namespace — all nine
+//! controllers, which had none.
+//!
+//! Run:
+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" medulla_session_e2e`
+//!
+//! ## What is being tested, and against what
+//!
+//! `openhuman::medulla` is OpenHuman acting as a **client** of the Medulla
+//! orchestration backend — outbound HTTP to `/medulla/v1/*`, unwrapping a
+//! `{success, data}` envelope (`client/mod.rs:118-159`). Do not confuse it with
+//! `platform::socket::medulla`, which is the inbound worker side; they share a
+//! product name and nothing else (`medulla/mod.rs:13-21`).
+//!
+//! Every case here runs against a loopback axum server speaking that envelope,
+//! selected with `OPENHUMAN_MEDULLA_BASE_URL` — the documented override for
+//! pointing a host at a different deployment (`resolve.rs:12-19`). Nothing
+//! leaves the machine.
+//!
+//! ## Two preconditions, and both are worth asserting in their own right
+//!
+//! `resolve::client` needs a base URL **and** a session token, and reports the
+//! two failures with distinct `data.kind` discriminators so a host can render
+//! "sign in" separately from "misconfigured" (`ops.rs:189-201`). This suite
+//! plants a session token through `AuthService` — the same store
+//! `get_session_token` reads — and also covers the signed-out path, because a
+//! signed-out host is the state most installs are in when they first touch this
+//! surface.
+//!
+//! ## Feature note
+//!
+//! The `medulla` gate is default-ON but deliberately **not** forwarded to the
+//! desktop shell (allow-listed in `INTENTIONALLY_NOT_FORWARDED` — the app never
+//! dials a Medulla backend; the Medulla TUI embeds this crate instead). The
+//! product feature string does not turn defaults off, so these controllers are
+//! present in this binary.
+
+use std::net::SocketAddr;
+use std::path::Path;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+use axum::extract::{Path as AxumPath, Query, State};
+use axum::http::header::AUTHORIZATION;
+use axum::http::HeaderMap;
+use axum::routing::{get, post};
+use axum::{Json, Router};
+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;
+
+/// The bearer this suite *proposes*. It is only used if this suite happens to
+/// be the first in the aggregated binary to initialise the token subsystem —
+/// see `rpc_token()` below, which is what actually gets sent.
+const PROPOSED_RPC_TOKEN: &str = "medulla-session-e2e-token";
+/// The session token this suite plants and the fixture backend demands.
+const SESSION_JWT: &str = "planted-medulla-session-jwt";
+
+static AUTH_INIT: OnceLock<()> = OnceLock::new();
+
+/// The crate-wide env lock, not a private one.
+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 plumbing ────────────────────────────────────────────────────────────
+
+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),
+ }
+ }
+}
+
+/// The bearer the running process will actually validate.
+///
+/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token`
+/// returns early once it is set. Every `tests/raw_coverage/` suite now shares
+/// one process, so the FIRST suite to initialise pins the token for all of
+/// them; a suite that sent its own hard-coded literal would get 401 whenever it
+/// lost that race, in an order that depends on libtest scheduling and load.
+///
+/// So: propose a token, initialise, then ask what the process settled on and
+/// send that. Correct whether this suite wins the race or loses it.
+fn rpc_token() -> &'static str {
+ AUTH_INIT.get_or_init(|| {
+ if std::env::var(CORE_TOKEN_ENV_VAR)
+ .map(|v| v.trim().is_empty())
+ .unwrap_or(true)
+ {
+ std::env::set_var(CORE_TOKEN_ENV_VAR, PROPOSED_RPC_TOKEN);
+ }
+ let token_dir = std::env::temp_dir().join("openhuman-medulla-session-e2e-auth");
+ std::fs::create_dir_all(&token_dir).expect("token dir");
+ init_rpc_token(&token_dir).expect("init rpc auth token");
+ });
+ openhuman_core::core::auth::get_rpc_token()
+ .expect("the token subsystem is initialised by the line above")
+}
+
+// ── The fixture Medulla backend ─────────────────────────────────────────────
+
+/// Records what the backend was asked, so the suite can assert the client sent
+/// the right thing rather than only that it parsed the reply.
+#[derive(Default)]
+struct BackendState {
+ /// `(method, path, query)` for every request that arrived.
+ seen: Mutex<Vec<(String, String, String)>>,
+ /// Bodies of the message posts.
+ bodies: Mutex<Vec<Value>>,
+}
+
+impl BackendState {
+ fn record(&self, method: &str, path: &str, query: &str) {
+ self.seen.lock().unwrap_or_else(|p| p.into_inner()).push((
+ method.to_string(),
+ path.to_string(),
+ query.to_string(),
+ ));
+ }
+
+ fn queries_for(&self, path: &str) -> Vec<String> {
+ self.seen
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .iter()
+ .filter(|(_, p, _)| p == path)
+ .map(|(_, _, q)| q.clone())
+ .collect()
+ }
+}
+
+fn envelope(data: Value) -> Json<Value> {
+ Json(json!({ "success": true, "data": data }))
+}
+
+/// Reject anything not carrying the planted bearer token.
+///
+/// Every session method must attach it (`client/mod.rs:108-115`); a method that
+/// forgot would sail past a fixture that did not check.
+fn authed(headers: &HeaderMap) -> bool {
+ headers
+ .get(AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v == format!("Bearer {SESSION_JWT}"))
+}
+
+async fn serve_fixture_backend() -> (
+ SocketAddr,
+ Arc<BackendState>,
+ tokio::task::JoinHandle<Result<(), std::io::Error>>,
+) {
+ let state = Arc::new(BackendState::default());
+
+ async fn list_sessions(
+ State(state): State<Arc<BackendState>>,
+ headers: HeaderMap,
+ ) -> Json<Value> {
+ state.record("GET", "/medulla/v1/sessions", "");
+ if !authed(&headers) {
+ return Json(
+ json!({ "success": false, "error": "unauthorized", "errorCode": "Unauthorized" }),
+ );
+ }
+ envelope(json!([
+ {
+ "sessionId": "sess-alpha",
+ "title": "Planted alpha",
+ "lastActiveAt": 1_700_000_000_000_i64,
+ "status": "active",
+ "lastSeq": 7
+ },
+ {
+ "sessionId": "sess-beta",
+ "title": null,
+ "status": "idle",
+ "lastSeq": 0
+ }
+ ]))
+ }
+
+ async fn create_session(
+ State(state): State<Arc<BackendState>>,
+ headers: HeaderMap,
+ Json(body): Json<Value>,
+ ) -> Json<Value> {
+ state.record("POST", "/medulla/v1/sessions", "");
+ state
+ .bodies
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .push(body.clone());
+ if !authed(&headers) {
+ return Json(json!({ "success": false, "error": "unauthorized" }));
+ }
+ // Echo the title back through the id so the test can prove the body
+ // travelled rather than being dropped on the floor.
+ let suffix = body
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("untitled");
+ envelope(json!({ "sessionId": format!("sess-new-{suffix}") }))
+ }
+
+ async fn get_session(
+ State(state): State<Arc<BackendState>>,
+ AxumPath(id): AxumPath<String>,
+ headers: HeaderMap,
+ ) -> Json<Value> {
+ state.record("GET", "/medulla/v1/sessions/:id", &id);
+ if !authed(&headers) {
+ return Json(json!({ "success": false, "error": "unauthorized" }));
+ }
+ if id == "sess-missing" {
+ // A backend refusal carrying its own vocabulary — `errorCode` is
+ // what the host branches on.
+ return Json(json!({
+ "success": false,
+ "error": "no such session",
+ "errorCode": "SessionNotFound"
+ }));
+ }
+ envelope(json!({
+ "sessionId": id,
+ "status": "active",
+ "lastCycleId": "cycle-9",
+ "lastSeq": 12,
+ "eventSeq": 30
+ }))
+ }
+
+ async fn send_message(
+ State(state): State<Arc<BackendState>>,
+ AxumPath(id): AxumPath<String>,
+ Query(query): Query<std::collections::HashMap<String, String>>,
+ headers: HeaderMap,
+ Json(body): Json<Value>,
+ ) -> Json<Value> {
+ let sync = query.get("sync").cloned().unwrap_or_default();
+ state.record("POST", "/medulla/v1/sessions/:id/messages", &sync);
+ state
+ .bodies
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .push(body.clone());
+ if !authed(&headers) {
+ return Json(json!({ "success": false, "error": "unauthorized" }));
+ }
+ // The two documented shapes: 202 async carries {cycleId, seq}; the
+ // sync form adds `reply`.
+ if sync == "1" {
+ envelope(json!({ "cycleId": "cycle-sync", "seq": 42, "reply": "PLANTED_SYNC_REPLY" }))
+ } else {
+ envelope(json!({ "cycleId": "cycle-async", "seq": 41 }))
+ }
+ }
+
+ async fn list_messages(
+ State(state): State<Arc<BackendState>>,
+ AxumPath(id): AxumPath<String>,
+ Query(query): Query<std::collections::HashMap<String, String>>,
+ headers: HeaderMap,
+ ) -> Json<Value> {
+ let after = query.get("after").cloned().unwrap_or_default();
+ state.record("GET", "/medulla/v1/sessions/:id/messages", &after);
+ let _ = id;
+ if !authed(&headers) {
+ return Json(json!({ "success": false, "error": "unauthorized" }));
+ }
+ // Honour the cursor, so "replays only what is new" is a property the
+ // test can actually observe rather than assume.
+ let all = vec![
+ json!({ "seq": 1, "role": "user", "body": "first", "ts": 1_700_000_000_000_i64, "cycleId": "cycle-1" }),
+ json!({ "seq": 2, "role": "assistant", "body": "second", "cycleId": "cycle-1" }),
+ json!({ "seq": 3, "role": "user", "body": "third" }),
+ ];
+ let cursor: i64 = after.parse().unwrap_or(0);
+ envelope(Value::Array(
+ all.into_iter()
+ .filter(|m| m["seq"].as_i64().unwrap_or(0) > cursor)
+ .collect(),
+ ))
+ }
+
+ async fn list_events(
+ State(state): State<Arc<BackendState>>,
+ AxumPath(id): AxumPath<String>,
+ Query(query): Query<std::collections::HashMap<String, String>>,
+ headers: HeaderMap,
+ ) -> Json<Value> {
+ let after = query.get("after").cloned().unwrap_or_default();
+ state.record("GET", "/medulla/v1/sessions/:id/events", &after);
+ let _ = id;
+ if !authed(&headers) {
+ return Json(json!({ "success": false, "error": "unauthorized" }));
+ }
+ // NOTE the shape. There are TWO `EventEnvelope` types in this domain and
+ // they are not the same on the wire:
+ //
+ // * `medulla::events::EventEnvelope` — `{seq, at, event: SessionEvent}`,
+ // the contract type, publicly re-exported by `medulla/mod.rs`.
+ // * `medulla::client::types::event::EventEnvelope` — `{seq?, at,
+ // sessionId, cycleId?, event: Value}`, the wire type.
+ //
+ // `ops::list_events` returns the **client** one, so `sessionId` is
+ // required and `event` stays raw JSON. Reading the domain's public
+ // re-export and assuming it describes the RPC response is the trap; it
+ // cost this suite one red run. See
+ // `~/tinyhuman/bugs/e2e-wave-medulla-two-eventenvelope-types.md`.
+ let all = vec![
+ json!({ "seq": 1, "at": 1_700_000_000_000_u64, "sessionId": "sess-alpha", "cycleId": "cycle-1",
+ "event": { "kind": "cycle_start", "cycleId": "cycle-1" } }),
+ json!({ "seq": 2, "at": 1_700_000_000_100_u64, "sessionId": "sess-alpha",
+ "event": { "kind": "assistant_delta", "delta": "hi" } }),
+ // A kind this build does not model: it must survive rather than
+ // dropping the row.
+ json!({ "seq": 3, "at": 1_700_000_000_200_u64, "sessionId": "sess-alpha",
+ "event": { "kind": "some_future_kind", "whatever": 1 } }),
+ ];
+ let cursor: i64 = after.parse().unwrap_or(0);
+ envelope(Value::Array(
+ all.into_iter()
+ .filter(|e| e["seq"].as_i64().unwrap_or(0) > cursor)
+ .collect(),
+ ))
+ }
+
+ async fn abort(
+ State(state): State<Arc<BackendState>>,
+ AxumPath(id): AxumPath<String>,
+ headers: HeaderMap,
+ ) -> Json<Value> {
+ state.record("POST", "/medulla/v1/sessions/:id/abort", &id);
+ if !authed(&headers) {
+ return Json(json!({ "success": false, "error": "unauthorized" }));
+ }
+ envelope(json!({ "sessionId": id, "aborted": true }))
+ }
+
+ async fn roster(State(state): State<Arc<BackendState>>, headers: HeaderMap) -> Json<Value> {
+ state.record("GET", "/medulla/v1/roster", "");
+ if !authed(&headers) {
+ return Json(json!({ "success": false, "error": "unauthorized" }));
+ }
+ // Note the wrapper: `roster()` unwraps `{workers: [...]}` out of `data`.
+ // `selected` is the one non-defaulted bool on `RosterWorker`
+ // (`client/program/types.rs`) — every other optional field carries
+ // `#[serde(default)]`, so omitting it is the single way to make this
+ // decode fail. It did, on the first run of this suite.
+ envelope(json!({
+ "workers": [
+ {
+ "registryId": "worker-1",
+ "label": "Planted worker",
+ "description": "Does planted things.",
+ "availability": "idle",
+ "harness": "tinyagents",
+ "address": "127.0.0.1:0",
+ "selected": true
+ }
+ ]
+ }))
+ }
+
+ let app = Router::new()
+ .route(
+ "/medulla/v1/sessions",
+ get(list_sessions).post(create_session),
+ )
+ .route("/medulla/v1/sessions/{id}", get(get_session))
+ .route(
+ "/medulla/v1/sessions/{id}/messages",
+ get(list_messages).post(send_message),
+ )
+ .route("/medulla/v1/sessions/{id}/events", get(list_events))
+ .route("/medulla/v1/sessions/{id}/abort", post(abort))
+ .route("/medulla/v1/roster", get(roster))
+ .with_state(Arc::clone(&state));
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind fixture backend");
+ let addr = listener.local_addr().expect("fixture backend addr");
+ let join = tokio::spawn(async move { axum::serve(listener, app).await });
+ (addr, state, join)
+}
+
+// ── Harness ─────────────────────────────────────────────────────────────────
+
+const MIN_CONFIG: &str = r#"api_url = "http://127.0.0.1:9"
+default_model = "medulla-e2e-model"
+
+[secrets]
+encrypt = false
+
+[local_ai]
+enabled = false
+
+[memory]
+provider = "none"
+embedding_provider = "none"
+embedding_model = "none"
+embedding_dimensions = 0
+
+[memory_tree]
+embedding_strict = false
+"#;
+
+struct Harness {
+ _tmp: TempDir,
+ _guards: Vec<EnvVarGuard>,
+ rpc_base: String,
+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,
+}
+
+/// `plant_session` decides whether `resolve::client` will find a token, which
+/// is the difference between the configured and signed-out cases below.
+async fn setup(extra: Vec<EnvVarGuard>, plant_session: bool) -> Harness {
+ let _ = rpc_token();
+
+ let tmp = tempdir().expect("tempdir");
+ let home = tmp.path();
+ let openhuman_home = home.join(".openhuman");
+ std::fs::create_dir_all(&openhuman_home).expect("create .openhuman");
+ std::fs::write(openhuman_home.join("config.toml"), MIN_CONFIG).expect("write config.toml");
+ let _: openhuman_core::openhuman::config::Config =
+ toml::from_str(MIN_CONFIG).expect("test config must match the config schema");
+
+ let workspace = home.join("workspace");
+ std::fs::create_dir_all(&workspace).expect("create workspace");
+
+ let mut guards = vec![
+ EnvVarGuard::set_to_path("HOME", home),
+ 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"),
+ ];
+ guards.extend(extra);
+
+ if plant_session {
+ // Write into the same profile store `get_session_token` reads
+ // (`session_support.rs:243-248` → `AuthService::get_profile`), so the
+ // token resolves through production's own path rather than a test seam.
+ use openhuman_core::openhuman::security::credentials::{
+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
+ };
+ let config = openhuman_core::openhuman::config::Config::load_or_init()
+ .await
+ .expect("load config for session planting");
+ AuthService::from_config(&config)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ SESSION_JWT,
+ std::collections::HashMap::new(),
+ true,
+ )
+ .expect("plant an app-session token");
+ }
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind rpc listener");
+ let addr: SocketAddr = listener.local_addr().expect("rpc listener addr");
+ let router = build_core_http_router(false);
+ let join = tokio::spawn(async move { axum::serve(listener, router).await });
+
+ Harness {
+ _tmp: tmp,
+ _guards: guards,
+ rpc_base: format!("http://{addr}"),
+ join,
+ }
+}
+
+async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(60))
+ .build()
+ .expect("build client");
+ let url = format!("{}/rpc", base.trim_end_matches('/'));
+ let response = client
+ .post(&url)
+ .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))
+ .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))
+ .send()
+ .await
+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));
+ assert!(
+ response.status().is_success(),
+ "HTTP {} for {method}",
+ response.status()
+ );
+ response
+ .json::<Value>()
+ .await
+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))
+}
+
+fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {
+ if let Some(error) = value.get("error") {
+ panic!("{context}: unexpected JSON-RPC error: {error}");
+ }
+ value
+ .get("result")
+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"))
+}
+
+fn err<'a>(value: &'a Value, context: &str) -> &'a Value {
+ value
+ .get("error")
+ .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}"))
+}
+
+/// The `data.kind` discriminator hosts branch on.
+///
+/// `medulla`'s ops encode a `StructuredRpcError` into the controller error
+/// channel, and the transport decodes it at the boundary into the JSON-RPC
+/// `error.data` — deliberately without branching on the method name
+/// (`core/jsonrpc.rs:86-99`). Reading `data.kind` rather than matching the
+/// message is the whole point of that machinery: the message is prose and may
+/// be reworded, the discriminator is the contract.
+fn error_kind(value: &Value, context: &str) -> String {
+ let error = err(value, context);
+ error
+ .get("data")
+ .and_then(|d| d.get("kind"))
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .unwrap_or_else(|| {
+ panic!("{context}: the error carries no structured `data.kind`: {error}")
+ })
+}
+
+// ── status ──────────────────────────────────────────────────────────────────
+
+/// `medulla_status` is deliberately infallible — "not configured" is a state to
+/// render, not an error to raise — and it must never leak the token.
+#[tokio::test]
+async fn medulla_status_reports_readiness_without_dialling_anything() {
+ let _lock = env_lock();
+ // Point at a port nothing is listening on: `status` must still answer,
+ // because it reports resolvability and makes no network call.
+ let harness = setup(
+ vec![EnvVarGuard::set(
+ "OPENHUMAN_MEDULLA_BASE_URL",
+ "http://127.0.0.1:9/",
+ )],
+ true,
+ )
+ .await;
+
+ let status = rpc(
+ &harness.rpc_base,
+ 300,
+ "openhuman.medulla_status",
+ json!({}),
+ )
+ .await;
+ let status = ok(&status, "medulla_status configured");
+ assert_eq!(
+ status.get("configured").and_then(Value::as_bool),
+ Some(true),
+ "a base URL plus a planted session token is the configured state: {status}"
+ );
+ assert_eq!(
+ status.get("hasSessionToken").and_then(Value::as_bool),
+ Some(true),
+ "the planted token must be seen: {status}"
+ );
+ assert_eq!(
+ status.get("baseUrl").and_then(Value::as_str),
+ Some("http://127.0.0.1:9"),
+ "the resolved base URL is surfaced, with its trailing slash trimmed: {status}"
+ );
+ assert!(
+ status.get("reason").is_none_or(Value::is_null),
+ "a configured host must carry no reason discriminator: {status}"
+ );
+ assert!(
+ !status.to_string().contains(SESSION_JWT),
+ "the session token must NEVER be returned: {status}"
+ );
+
+ harness.join.abort();
+}
+
+/// The signed-out host: `status` says so with a stable discriminator, and every
+/// other method in the namespace refuses with the matching structured error.
+///
+/// This is the state a fresh install is in, and the `expected_user_state` flag
+/// on these errors is what keeps them out of crash reporting — so it matters
+/// that the discriminator is right and not merely that something failed.
+#[tokio::test]
+async fn medulla_signed_out_host_refuses_every_call_with_one_discriminator() {
+ let _lock = env_lock();
+ let (backend_addr, _state, backend_join) = serve_fixture_backend().await;
+ let harness = setup(
+ vec![EnvVarGuard::set(
+ "OPENHUMAN_MEDULLA_BASE_URL",
+ &format!("http://{backend_addr}"),
+ )],
+ // No session planted: signed out.
+ false,
+ )
+ .await;
+
+ let status = rpc(
+ &harness.rpc_base,
+ 310,
+ "openhuman.medulla_status",
+ json!({}),
+ )
+ .await;
+ let status = ok(&status, "medulla_status signed out");
+ assert_eq!(
+ status.get("configured").and_then(Value::as_bool),
+ Some(false),
+ "a host with no session token is not configured: {status}"
+ );
+ assert_eq!(
+ status.get("hasSessionToken").and_then(Value::as_bool),
+ Some(false),
+ "and it must say the token specifically is what is missing: {status}"
+ );
+ assert_eq!(
+ status.get("reason").and_then(Value::as_str),
+ Some("MedullaNoSessionToken"),
+ "the reason must be the stable discriminator, not prose: {status}"
+ );
+ // The base URL still resolves — that is the point of reporting them
+ // separately, so a UI can say "sign in" rather than "misconfigured".
+ assert!(
+ status
+ .get("baseUrl")
+ .and_then(Value::as_str)
+ .is_some_and(|u| u.contains(&backend_addr.to_string())),
+ "a signed-out host still reports the base URL it would use: {status}"
+ );
+
+ // Every network-backed method refuses identically.
+ for (id, method, params) in [
+ (311, "openhuman.medulla_list_sessions", json!({})),
+ (312, "openhuman.medulla_create_session", json!({})),
+ (
+ 313,
+ "openhuman.medulla_get_session",
+ json!({ "sessionId": "sess-alpha" }),
+ ),
+ (
+ 314,
+ "openhuman.medulla_send_message",
+ json!({ "sessionId": "sess-alpha", "body": "hi" }),
+ ),
+ (
+ 315,
+ "openhuman.medulla_abort",
+ json!({ "sessionId": "sess-alpha" }),
+ ),
+ (
+ 316,
+ "openhuman.medulla_list_messages",
+ json!({ "sessionId": "sess-alpha" }),
+ ),
+ (
+ 317,
+ "openhuman.medulla_list_events",
+ json!({ "sessionId": "sess-alpha" }),
+ ),
+ (318, "openhuman.medulla_roster", json!({})),
+ ] {
+ let refused = rpc(&harness.rpc_base, id, method, params).await;
+ assert_eq!(
+ error_kind(&refused, method),
+ "MedullaNoSessionToken",
+ "{method} must refuse a signed-out host with the same discriminator \
+ `status` reported: {refused}"
+ );
+ }
+
+ backend_join.abort();
+ harness.join.abort();
+}
+
+// ── the session lifecycle ───────────────────────────────────────────────────
+
+/// The full durable-session arc against the fixture backend:
+/// create → list → get → send (async and sync) → abort.
+#[tokio::test]
+async fn medulla_session_lifecycle_round_trips_through_the_backend() {
+ let _lock = env_lock();
+ let (backend_addr, state, backend_join) = serve_fixture_backend().await;
+ let harness = setup(
+ vec![EnvVarGuard::set(
+ "OPENHUMAN_MEDULLA_BASE_URL",
+ &format!("http://{backend_addr}"),
+ )],
+ true,
+ )
+ .await;
+
+ // ── create ──────────────────────────────────────────────────────────────
+ let created = rpc(
+ &harness.rpc_base,
+ 320,
+ "openhuman.medulla_create_session",
+ json!({ "title": "planted" }),
+ )
+ .await;
+ assert_eq!(
+ ok(&created, "medulla_create_session")
+ .get("sessionId")
+ .and_then(Value::as_str),
+ Some("sess-new-planted"),
+ "the title must reach the backend, not be dropped: {created}"
+ );
+
+ // Omitting the title is legal — the backend names an untitled session
+ // itself rather than this host inventing one.
+ let untitled = rpc(
+ &harness.rpc_base,
+ 321,
+ "openhuman.medulla_create_session",
+ json!({}),
+ )
+ .await;
+ assert_eq!(
+ ok(&untitled, "medulla_create_session untitled")
+ .get("sessionId")
+ .and_then(Value::as_str),
+ Some("sess-new-untitled"),
+ "an absent title must send no title, not an empty one: {untitled}"
+ );
+
+ // ── list ────────────────────────────────────────────────────────────────
+ let listed = rpc(
+ &harness.rpc_base,
+ 322,
+ "openhuman.medulla_list_sessions",
+ json!({}),
+ )
+ .await;
+ let listed = ok(&listed, "medulla_list_sessions");
+ let sessions = listed
+ .as_array()
+ .unwrap_or_else(|| panic!("list_sessions must return an array: {listed}"));
+ assert_eq!(sessions.len(), 2, "both fixture sessions: {listed}");
+ assert_eq!(
+ sessions[0].get("sessionId").and_then(Value::as_str),
+ Some("sess-alpha")
+ );
+ assert_eq!(
+ sessions[0].get("status").and_then(Value::as_str),
+ Some("active"),
+ "the wire status must round-trip through the modelled enum: {listed}"
+ );
+ assert_eq!(
+ sessions[0].get("lastSeq").and_then(Value::as_i64),
+ Some(7),
+ "the replay cursor must survive: {listed}"
+ );
+ // The second row omits `lastActiveAt` entirely; an absent optional must
+ // stay absent rather than becoming a fabricated zero.
+ assert!(
+ sessions[1].get("lastActiveAt").is_none_or(Value::is_null),
+ "an unreported lastActiveAt must not be invented: {listed}"
+ );
+
+ // ── get ─────────────────────────────────────────────────────────────────
+ let detail = rpc(
+ &harness.rpc_base,
+ 323,
+ "openhuman.medulla_get_session",
+ json!({ "sessionId": "sess-alpha" }),
+ )
+ .await;
+ let detail = ok(&detail, "medulla_get_session");
+ assert_eq!(
+ detail.get("sessionId").and_then(Value::as_str),
+ Some("sess-alpha")
+ );
+ assert_eq!(
+ detail.get("lastCycleId").and_then(Value::as_str),
+ Some("cycle-9")
+ );
+ assert_eq!(detail.get("eventSeq").and_then(Value::as_i64), Some(30));
+
+ // ── send, both modes ────────────────────────────────────────────────────
+ let async_send = rpc(
+ &harness.rpc_base,
+ 324,
+ "openhuman.medulla_send_message",
+ json!({ "sessionId": "sess-alpha", "body": "async turn" }),
+ )
+ .await;
+ let async_send = ok(&async_send, "medulla_send_message async");
+ assert_eq!(
+ async_send.get("cycleId").and_then(Value::as_str),
+ Some("cycle-async"),
+ "omitting `sync` must take the non-blocking path a UI wants: {async_send}"
+ );
+ assert!(
+ async_send.get("reply").is_none_or(Value::is_null),
+ "the async form carries no reply: {async_send}"
+ );
+
+ let sync_send = rpc(
+ &harness.rpc_base,
+ 325,
+ "openhuman.medulla_send_message",
+ json!({ "sessionId": "sess-alpha", "body": "sync turn", "sync": true }),
+ )
+ .await;
+ let sync_send = ok(&sync_send, "medulla_send_message sync");
+ assert_eq!(
+ sync_send.get("cycleId").and_then(Value::as_str),
+ Some("cycle-sync")
+ );
+ assert_eq!(
+ sync_send.get("reply").and_then(Value::as_str),
+ Some("PLANTED_SYNC_REPLY"),
+ "the sync form must surface the backend's reply: {sync_send}"
+ );
+
+ // The `sync` flag must reach the wire as the backend's `0`/`1`, not as a
+ // JSON boolean — that translation is the client's job.
+ let sync_flags = state.queries_for("/medulla/v1/sessions/:id/messages");
+ assert_eq!(
+ sync_flags,
+ vec!["0".to_string(), "1".to_string()],
+ "the two sends must have carried sync=0 then sync=1: {sync_flags:?}"
+ );
+ let bodies = state
+ .bodies
+ .lock()
+ .unwrap_or_else(|p| p.into_inner())
+ .clone();
+ assert!(
+ bodies
+ .iter()
+ .any(|b| b.get("body").and_then(Value::as_str) == Some("async turn")),
+ "the message body must reach the backend: {bodies:?}"
+ );
+
+ // ── abort ───────────────────────────────────────────────────────────────
+ let aborted = rpc(
+ &harness.rpc_base,
+ 326,
+ "openhuman.medulla_abort",
+ json!({ "sessionId": "sess-alpha" }),
+ )
+ .await;
+ let aborted = ok(&aborted, "medulla_abort");
+ assert_eq!(
+ aborted.get("aborted").and_then(Value::as_bool),
+ Some(true),
+ "abort must report whether it actually aborted: {aborted}"
+ );
+ assert_eq!(
+ aborted.get("sessionId").and_then(Value::as_str),
+ Some("sess-alpha")
+ );
+
+ // ── a backend refusal keeps the backend's own vocabulary ────────────────
+ let missing = rpc(
+ &harness.rpc_base,
+ 327,
+ "openhuman.medulla_get_session",
+ json!({ "sessionId": "sess-missing" }),
+ )
+ .await;
+ assert_eq!(
+ error_kind(&missing, "medulla_get_session missing"),
+ "SessionNotFound",
+ "the backend's `errorCode` must become `data.kind`, so a host branches \
+ on its vocabulary rather than on prose: {missing}"
+ );
+
+ // ── params validation ───────────────────────────────────────────────────
+ let no_id = rpc(
+ &harness.rpc_base,
+ 328,
+ "openhuman.medulla_get_session",
+ json!({}),
+ )
+ .await;
+ assert!(
+ err(&no_id, "medulla_get_session no id")
+ .to_string()
+ .contains("sessionId"),
+ "an absent sessionId must be named: {no_id}"
+ );
+
+ let no_body = rpc(
+ &harness.rpc_base,
+ 329,
+ "openhuman.medulla_send_message",
+ json!({ "sessionId": "sess-alpha" }),
+ )
+ .await;
+ assert!(
+ err(&no_body, "medulla_send_message no body")
+ .to_string()
+ .contains("body"),
+ "an absent message body must be named: {no_body}"
+ );
+
+ backend_join.abort();
+ harness.join.abort();
+}
+
+// ── replay + roster ─────────────────────────────────────────────────────────
+
+/// `medulla_list_messages` / `medulla_list_events` are cursors, not page
+/// offsets: passing the last seq already seen must return only what is newer.
+/// That property is what makes a reconnect cheap, and it is asserted here by
+/// replaying the same session twice with different cursors.
+#[tokio::test]
+async fn medulla_replay_is_a_cursor_and_tolerates_unmodelled_event_kinds() {
+ let _lock = env_lock();
+ let (backend_addr, state, backend_join) = serve_fixture_backend().await;
+ let harness = setup(
+ vec![EnvVarGuard::set(
+ "OPENHUMAN_MEDULLA_BASE_URL",
+ &format!("http://{backend_addr}"),
+ )],
+ true,
+ )
+ .await;
+
+ // No cursor: everything.
+ let all = rpc(
+ &harness.rpc_base,
+ 330,
+ "openhuman.medulla_list_messages",
+ json!({ "sessionId": "sess-alpha" }),
+ )
+ .await;
+ let all = ok(&all, "medulla_list_messages all");
+ let messages = all
+ .as_array()
+ .unwrap_or_else(|| panic!("list_messages must return an array: {all}"));
+ assert_eq!(messages.len(), 3, "the whole history: {all}");
+ assert_eq!(
+ messages[0].get("role").and_then(Value::as_str),
+ Some("user"),
+ "roles must round-trip lowercase through the modelled enum: {all}"
+ );
+ assert_eq!(
+ messages[1].get("role").and_then(Value::as_str),
+ Some("assistant")
+ );
+ assert_eq!(
+ messages[0].get("body").and_then(Value::as_str),
+ Some("first")
+ );
+
+ // With a cursor: only what is newer. This is the assertion that separates
+ // a cursor from an offset — an offset of 2 would return one row, a cursor
+ // of 2 returns exactly the rows with seq > 2.
+ let tail = rpc(
+ &harness.rpc_base,
+ 331,
+ "openhuman.medulla_list_messages",
+ json!({ "sessionId": "sess-alpha", "after": 2 }),
+ )
+ .await;
+ let tail = ok(&tail, "medulla_list_messages after");
+ let tail_messages = tail.as_array().expect("array");
+ assert_eq!(tail_messages.len(), 1, "only seq 3 is newer than 2: {tail}");
+ assert_eq!(
+ tail_messages[0].get("seq").and_then(Value::as_i64),
+ Some(3),
+ "the cursor must be exclusive of its own value: {tail}"
+ );
+
+ // The cursor must actually have travelled to the backend as `after=2` —
+ // filtering client-side would look identical from here.
+ let message_cursors = state.queries_for("/medulla/v1/sessions/:id/messages");
+ assert_eq!(
+ message_cursors,
+ vec![String::new(), "2".to_string()],
+ "an absent cursor must send no `after` param at all, and a present one \
+ must send its value: {message_cursors:?}"
+ );
+
+ // Events: same cursor semantics, plus forward compatibility.
+ let events = rpc(
+ &harness.rpc_base,
+ 332,
+ "openhuman.medulla_list_events",
+ json!({ "sessionId": "sess-alpha" }),
+ )
+ .await;
+ let events = ok(&events, "medulla_list_events");
+ let envelopes = events
+ .as_array()
+ .unwrap_or_else(|| panic!("list_events must return an array: {events}"));
+ assert_eq!(
+ envelopes.len(),
+ 3,
+ "an unmodelled event kind must NOT be dropped — a newer backend would \
+ silently lose rows: {events}"
+ );
+ assert_eq!(envelopes[0].get("seq").and_then(Value::as_u64), Some(1));
+ assert_eq!(
+ envelopes[0].get("at").and_then(Value::as_u64),
+ Some(1_700_000_000_000),
+ "the wall-clock stamp must survive: {events}"
+ );
+ assert_eq!(
+ envelopes[0].get("sessionId").and_then(Value::as_str),
+ Some("sess-alpha"),
+ "the wire envelope's required sessionId must round-trip: {events}"
+ );
+ assert_eq!(
+ envelopes[0]
+ .get("event")
+ .and_then(|e| e.get("kind"))
+ .and_then(Value::as_str),
+ Some("cycle_start"),
+ "a modelled kind keeps its tag: {events}"
+ );
+ assert_eq!(
+ envelopes[1]
+ .get("event")
+ .and_then(|e| e.get("delta"))
+ .and_then(Value::as_str),
+ Some("hi"),
+ "a modelled kind keeps its payload: {events}"
+ );
+ // The unmodelled row survives, tagged with whatever the backend called it.
+ assert_eq!(
+ envelopes[2]
+ .get("event")
+ .and_then(|e| e.get("kind"))
+ .and_then(Value::as_str),
+ Some("some_future_kind"),
+ "an unknown kind must keep its own tag rather than being relabelled: {events}"
+ );
+
+ let events_tail = rpc(
+ &harness.rpc_base,
+ 333,
+ "openhuman.medulla_list_events",
+ json!({ "sessionId": "sess-alpha", "after": 1 }),
+ )
+ .await;
+ assert_eq!(
+ ok(&events_tail, "medulla_list_events after")
+ .as_array()
+ .map(Vec::len),
+ Some(2),
+ "the events cursor must drop what has already been seen: {events_tail}"
+ );
+
+ // ── roster ──────────────────────────────────────────────────────────────
+ // The backend wraps the list in `{workers: [...]}`; the controller unwraps
+ // it, so a caller gets the array and not the wrapper.
+ let roster = rpc(
+ &harness.rpc_base,
+ 334,
+ "openhuman.medulla_roster",
+ json!({}),
+ )
+ .await;
+ let roster = ok(&roster, "medulla_roster");
+ let workers = roster
+ .as_array()
+ .unwrap_or_else(|| panic!("roster must unwrap to a bare array, got: {roster}"));
+ assert_eq!(workers.len(), 1, "one planted worker: {roster}");
+ assert_eq!(
+ workers[0].get("registryId").and_then(Value::as_str),
+ Some("worker-1"),
+ "the worker's stable id must survive: {roster}"
+ );
+ assert_eq!(
+ workers[0].get("availability").and_then(Value::as_str),
+ Some("idle")
+ );
+ assert_eq!(
+ workers[0].get("harness").and_then(Value::as_str),
+ Some("tinyagents")
+ );
+ assert_eq!(
+ workers[0].get("selected").and_then(Value::as_bool),
+ Some(true),
+ "the roster's required `selected` flag must round-trip: {roster}"
+ );
+
+ backend_join.abort();
+ harness.join.abort();
+}
diff --git a/tests/raw_coverage/skill_runtime_e2e.rs b/tests/raw_coverage/skill_runtime_e2e.rs
new file mode 100644
index 0000000000..8a89ccd9f8
--- /dev/null
+++ b/tests/raw_coverage/skill_runtime_e2e.rs
@@ -0,0 +1,1409 @@
+//! JSON-RPC E2E coverage for the skill execution surface: `skill_runtime_*`,
+//! the uncovered half of `skills_*`, `skill_registry_categories`, and the
+//! `javascript_*` runtime bridge.
+//!
+//! Run:
+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" skill_runtime_e2e`
+//!
+//! ## Hermetic by construction
+//!
+//! Three fixtures, no network out:
+//!
+//! * A **planted skill** at `<workspace>/skills/<slug>/{SKILL.md,skill.toml}`.
+//! That directory is the legacy skill root — `discover_filtered` scans it with
+//! no trust marker required (`ops_discover.rs:250-261`), which makes it the
+//! cheapest honest way to give the registry something real to resolve.
+//! * **Planted run logs** in `<workspace>/skills/.runs/`, written in the exact
+//! `write_header` / `write_footer` format (`run_log.rs:146-172`, `:598-612`).
+//! `scan_runs` and `read_run_log_slice` parse those files, so a planted log is
+//! precisely what the code under test consumes.
+//! * A **loopback fixture catalog** for `skill_registry_categories` and the
+//! `skills_install_from_url` happy path, reached through the existing
+//! `OPENHUMAN_SKILL_REGISTRY_CATALOG_URL` /
+//! `OPENHUMAN_SKILL_INSTALL_ALLOW_LOCAL_HTTP` escape hatches.
+//!
+//! ## Why the live `run` arc is asserted at its validation boundary, not end to end
+//!
+//! `spawn_workflow_run_background` validates the skill id and its required
+//! inputs **synchronously**, then `tokio::spawn`s a detached orchestrator that
+//! writes the run-log header, calls `Config::load_or_init()` (reading
+//! process-global env), and drives a real agent turn
+//! (`run_machinery.rs:184-230`). Driving that here would (a) race the header
+//! write that a following `read_run_log` needs, and (b) leave a detached task
+//! reading `HOME` / `OPENHUMAN_WORKSPACE` after this case has released the env
+//! lock — which, now that all ~77 suites share one process, is contamination
+//! aimed at every other suite in the binary. So `run` is asserted on the two
+//! errors it raises before spawning, and the log-reading methods are asserted
+//! against planted logs where the content is knowable.
+
+use std::net::SocketAddr;
+use std::path::{Path, PathBuf};
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+use axum::http::header::AUTHORIZATION;
+use axum::routing::get;
+use axum::Router;
+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;
+
+/// The bearer this suite *proposes*. It is only used if this suite happens to
+/// be the first in the aggregated binary to initialise the token subsystem —
+/// see `rpc_token()` below, which is what actually gets sent.
+const PROPOSED_RPC_TOKEN: &str = "skill-runtime-e2e-token";
+
+static AUTH_INIT: OnceLock<()> = OnceLock::new();
+
+/// The crate-wide env lock, not a private one — every `tests/raw_coverage/`
+/// suite shares one process, so a file-local lock would isolate nothing.
+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 plumbing ────────────────────────────────────────────────────────────
+
+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),
+ }
+ }
+}
+
+/// The bearer the running process will actually validate.
+///
+/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token`
+/// returns early once it is set. Every `tests/raw_coverage/` suite now shares
+/// one process, so the FIRST suite to initialise pins the token for all of
+/// them; a suite that sent its own hard-coded literal would get 401 whenever it
+/// lost that race, in an order that depends on libtest scheduling and load.
+///
+/// So: propose a token, initialise, then ask what the process settled on and
+/// send that. Correct whether this suite wins the race or loses it.
+fn rpc_token() -> &'static str {
+ AUTH_INIT.get_or_init(|| {
+ if std::env::var(CORE_TOKEN_ENV_VAR)
+ .map(|v| v.trim().is_empty())
+ .unwrap_or(true)
+ {
+ std::env::set_var(CORE_TOKEN_ENV_VAR, PROPOSED_RPC_TOKEN);
+ }
+ let token_dir = std::env::temp_dir().join("openhuman-skill-runtime-e2e-auth");
+ std::fs::create_dir_all(&token_dir).expect("token dir");
+ init_rpc_token(&token_dir).expect("init rpc auth token");
+ });
+ openhuman_core::core::auth::get_rpc_token()
+ .expect("the token subsystem is initialised by the line above")
+}
+
+// ── Harness ─────────────────────────────────────────────────────────────────
+
+const MIN_CONFIG: &str = r#"api_url = "http://127.0.0.1:9"
+default_model = "skill-runtime-e2e-model"
+
+[secrets]
+encrypt = false
+
+[local_ai]
+enabled = false
+
+[memory]
+provider = "none"
+embedding_provider = "none"
+embedding_model = "none"
+embedding_dimensions = 0
+
+[memory_tree]
+embedding_strict = false
+"#;
+
+struct Harness {
+ _tmp: TempDir,
+ _guards: Vec<EnvVarGuard>,
+ workspace: PathBuf,
+ rpc_base: String,
+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,
+}
+
+async fn setup(extra: Vec<EnvVarGuard>) -> Harness {
+ let _ = rpc_token();
+
+ let tmp = tempdir().expect("tempdir");
+ let home = tmp.path();
+ let openhuman_home = home.join(".openhuman");
+ std::fs::create_dir_all(&openhuman_home).expect("create .openhuman");
+ std::fs::write(openhuman_home.join("config.toml"), MIN_CONFIG).expect("write config.toml");
+ let _: openhuman_core::openhuman::config::Config =
+ toml::from_str(MIN_CONFIG).expect("test config must match the config schema");
+
+ let workspace = home.join("workspace");
+ std::fs::create_dir_all(workspace.join("skills")).expect("create workspace skills dir");
+ // Inside the workspace on purpose. `file_read` resolves relative paths
+ // against `action_dir`, but `SecurityPolicy` jails the resolved path to
+ // `workspace_dir` — an action dir outside the workspace makes every read
+ // fail with `[policy-blocked] Resolved path escapes workspace`, which is
+ // exactly what the first run of this suite hit. The tool's own description
+ // ("your working directory (the action sandbox)") does not mention the
+ // second, tighter boundary.
+ let action_dir = workspace.join("actions");
+ std::fs::create_dir_all(&action_dir).expect("create action dir");
+
+ let mut guards = vec![
+ EnvVarGuard::set_to_path("HOME", home),
+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),
+ EnvVarGuard::set_to_path("OPENHUMAN_ACTION_DIR", &action_dir),
+ EnvVarGuard::unset("BACKEND_URL"),
+ EnvVarGuard::unset("VITE_BACKEND_URL"),
+ EnvVarGuard::unset("OPENHUMAN_API_URL"),
+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),
+ ];
+ guards.extend(extra);
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind rpc listener");
+ let addr: SocketAddr = listener.local_addr().expect("rpc listener addr");
+ let router = build_core_http_router(false);
+ let join = tokio::spawn(async move { axum::serve(listener, router).await });
+
+ Harness {
+ _tmp: tmp,
+ _guards: guards,
+ workspace,
+ rpc_base: format!("http://{addr}"),
+ join,
+ }
+}
+
+async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(120))
+ .build()
+ .expect("build client");
+ let url = format!("{}/rpc", base.trim_end_matches('/'));
+ let response = client
+ .post(&url)
+ .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))
+ .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))
+ .send()
+ .await
+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));
+ assert!(
+ response.status().is_success(),
+ "HTTP {} for {method}",
+ response.status()
+ );
+ response
+ .json::<Value>()
+ .await
+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))
+}
+
+fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {
+ if let Some(error) = value.get("error") {
+ panic!("{context}: unexpected JSON-RPC error: {error}");
+ }
+ value
+ .get("result")
+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"))
+}
+
+/// The controller payload, unwrapping the `{result, logs}` envelope when one
+/// is present.
+///
+/// `RpcOutcome::into_cli_compatible_json` (`src/rpc/mod.rs:54-62`) wraps the
+/// value in `{result, logs}` **only when the handler emitted at least one log
+/// line**, and returns it bare otherwise. So the response shape of a single
+/// namespace varies with whether its handler happened to log — `javascript_*`
+/// always logs and is always wrapped; the `skills_*` handlers pass
+/// `Vec::new()` and never are. A caller cannot write one parser for the RPC
+/// surface without knowing that. See
+/// `~/tinyhuman/bugs/e2e-wave-rpc-envelope-shape-varies-with-logging.md`.
+fn payload<'a>(value: &'a Value, context: &str) -> &'a Value {
+ let result = ok(value, context);
+ match (result.get("result"), result.get("logs")) {
+ (Some(inner), Some(_)) => inner,
+ _ => result,
+ }
+}
+
+fn error_message<'a>(value: &'a Value, context: &str) -> &'a str {
+ 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 carries no message: {value}"))
+}
+
+// ── Fixtures ────────────────────────────────────────────────────────────────
+
+/// Plant a runnable skill under the legacy `<workspace>/skills/` root.
+///
+/// `skill.toml` supplies the runnable id and the declared `[[inputs]]`;
+/// `SKILL.md` supplies the body that becomes the inline system prompt. The
+/// resource file is what `skills_read_resource` reads back.
+fn plant_skill(workspace: &Path, slug: &str, required_input: &str) -> PathBuf {
+ let dir = workspace.join("skills").join(slug);
+ std::fs::create_dir_all(dir.join("references")).expect("create skill dir");
+ std::fs::write(
+ dir.join("SKILL.md"),
+ format!(
+ "---\nname: {slug}\ndescription: A planted skill for the skill-runtime e2e suite.\n---\n\n\
+ # {slug}\n\nDo the planted thing.\n"
+ ),
+ )
+ .expect("write SKILL.md");
+ std::fs::write(
+ dir.join("skill.toml"),
+ format!(
+ "id = \"{slug}\"\nwhen_to_use = \"When the e2e suite says so.\"\n\n\
+ [[inputs]]\nname = \"{required_input}\"\ndescription = \"The one input this skill insists on.\"\n\
+ required = true\ntype = \"string\"\n"
+ ),
+ )
+ .expect("write skill.toml");
+ std::fs::write(
+ dir.join("references").join("note.md"),
+ "PLANTED_RESOURCE_BODY\n",
+ )
+ .expect("write resource");
+ dir
+}
+
+/// Write a run log in the on-disk format `write_header` / `write_footer`
+/// produce, so `scan_runs` / `read_run_log_slice` parse it exactly as they
+/// would a real run's.
+///
+/// `finished` controls whether the `--- result ---` footer lands, which is the
+/// single bit that separates a `RUNNING` run from a terminal one and drives the
+/// `complete` flag the frontend polls on.
+fn plant_run_log(
+ workspace: &Path,
+ workflow_id: &str,
+ run_id: &str,
+ started_rfc3339: &str,
+ finished: Option<(&str, u64, &str)>,
+) -> PathBuf {
+ let runs = workspace.join("skills").join(".runs");
+ std::fs::create_dir_all(&runs).expect("create runs dir");
+ let short = run_id.get(..8).unwrap_or(run_id);
+ let path = runs.join(format!("{workflow_id}_20260907T101010Z_{short}.log"));
+
+ let mut body = format!(
+ "==== workflow_run: {workflow_id} ====\n\
+ run_id : {run_id}\n\
+ started: {started_rfc3339} UTC\n\
+ inputs : {{}}\n\n\
+ --- task prompt ---\nplanted prompt\n\n\
+ --- steps ---\n"
+ );
+ if let Some((status, duration_ms, output)) = finished {
+ body.push_str(&format!(
+ "\n--- result ---\n\
+ status : {status}\n\
+ duration: {duration_ms} ms\n\
+ finished: 2026-09-07T10:20:10+00:00 UTC\n\n{output}\n"
+ ));
+ }
+ std::fs::write(&path, body).expect("write run log");
+ path
+}
+
+/// A loopback stand-in for the skill catalog + a downloadable `SKILL.md`.
+async fn serve_fixture_catalog() -> (
+ SocketAddr,
+ tokio::task::JoinHandle<Result<(), std::io::Error>>,
+) {
+ async fn catalog() -> axum::Json<Value> {
+ axum::Json(json!([
+ {
+ "name": "planted-git-helper",
+ "description": "Automate git triage.",
+ "category": "software-development",
+ "source": "fixture",
+ "tags": ["git"],
+ "platforms": ["linux", "macos"],
+ "envVars": [],
+ "commands": []
+ },
+ {
+ "name": "planted-notes-helper",
+ "description": "Summarize notes.",
+ "category": "productivity",
+ "source": "fixture",
+ "tags": ["notes"],
+ "platforms": ["linux", "macos"],
+ "envVars": [],
+ "commands": []
+ },
+ {
+ // Deliberately category-less: `list_categories` filters empty
+ // strings out, so this row must NOT contribute a category.
+ "name": "planted-uncategorised",
+ "description": "No category at all.",
+ "category": "",
+ "source": "fixture",
+ "tags": [],
+ "platforms": ["linux", "macos"],
+ "envVars": [],
+ "commands": []
+ }
+ ]))
+ }
+
+ async fn skill_md() -> &'static str {
+ "---\nname: url-installed-skill\ndescription: Installed over loopback HTTP by the e2e suite.\n---\n\n# URL Installed Skill\n\nBody.\n"
+ }
+
+ let app = Router::new()
+ .route("/skills.json", get(catalog))
+ .route("/skills/url-installed-skill/SKILL.md", get(skill_md));
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind fixture listener");
+ let addr = listener.local_addr().expect("fixture addr");
+ let join = tokio::spawn(async move { axum::serve(listener, app).await });
+ (addr, join)
+}
+
+// ── skill_runtime ───────────────────────────────────────────────────────────
+
+/// `skill_runtime_schemas` and `skill_runtime_resolve_runtimes` — the two
+/// methods the production smoke-script generator reads.
+///
+/// `schemas` must return the namespace's own six controllers with the right
+/// namespace stamped on each; a generator fed a truncated or mis-namespaced
+/// list emits scripts that call methods that do not exist.
+#[tokio::test]
+async fn skill_runtime_schemas_and_runtime_resolution() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+
+ let schemas = rpc(
+ &harness.rpc_base,
+ 100,
+ "openhuman.skill_runtime_schemas",
+ json!({}),
+ )
+ .await;
+ let schemas = ok(&schemas, "skill_runtime_schemas");
+ let listed = schemas
+ .get("schemas")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("schemas payload has no `schemas` array: {schemas}"));
+
+ let functions: Vec<&str> = listed
+ .iter()
+ .map(|entry| {
+ assert_eq!(
+ entry.get("namespace").and_then(Value::as_str),
+ Some("skill_runtime"),
+ "every returned schema must be stamped with its own namespace: {entry}"
+ );
+ entry
+ .get("function")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("schema entry without a `function`: {entry}"))
+ })
+ .collect();
+
+ for expected in [
+ "run",
+ "cancel",
+ "recent_runs",
+ "read_run_log",
+ "resolve_runtimes",
+ "schemas",
+ ] {
+ assert!(
+ functions.contains(&expected),
+ "skill_runtime_schemas must advertise `{expected}`, got {functions:?}"
+ );
+ }
+ assert_eq!(
+ functions.len(),
+ 6,
+ "the namespace has exactly six controllers; got {functions:?}"
+ );
+
+ // `resolve_runtimes` scoped to one runtime must return exactly that one,
+ // with the documented status fields present. Availability depends on the
+ // host toolchain, so the assertion is on shape and scoping, not on a
+ // machine-specific `available: true`.
+ let node_only = rpc(
+ &harness.rpc_base,
+ 101,
+ "openhuman.skill_runtime_resolve_runtimes",
+ json!({ "runtime": "node" }),
+ )
+ .await;
+ let node_only = ok(&node_only, "skill_runtime_resolve_runtimes node");
+ let runtimes = node_only
+ .get("runtimes")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("resolve_runtimes has no `runtimes` array: {node_only}"));
+ assert_eq!(
+ runtimes.len(),
+ 1,
+ "scoping to `node` must resolve only node: {node_only}"
+ );
+ assert_eq!(
+ runtimes[0].get("runtime").and_then(Value::as_str),
+ Some("node"),
+ "the single entry must be the node runtime: {node_only}"
+ );
+ for field in ["enabled", "available"] {
+ assert!(
+ runtimes[0].get(field).is_some_and(Value::is_boolean),
+ "`{field}` must be present and boolean: {node_only}"
+ );
+ }
+
+ // The default (`all`) resolves both slots.
+ let all = rpc(
+ &harness.rpc_base,
+ 102,
+ "openhuman.skill_runtime_resolve_runtimes",
+ json!({}),
+ )
+ .await;
+ let all_names: Vec<&str> = ok(&all, "skill_runtime_resolve_runtimes all")
+ .get("runtimes")
+ .and_then(Value::as_array)
+ .expect("runtimes array")
+ .iter()
+ .filter_map(|r| r.get("runtime").and_then(Value::as_str))
+ .collect();
+ assert!(
+ all_names.contains(&"node") && all_names.contains(&"python"),
+ "the default must resolve both runtimes, got {all_names:?}"
+ );
+
+ // Failure path: an unrecognised runtime is refused, and the error names the
+ // three that are accepted rather than failing opaquely.
+ let bogus = rpc(
+ &harness.rpc_base,
+ 103,
+ "openhuman.skill_runtime_resolve_runtimes",
+ json!({ "runtime": "brainfuck" }),
+ )
+ .await;
+ let message = error_message(&bogus, "skill_runtime_resolve_runtimes bogus");
+ assert!(
+ message.contains("brainfuck") && message.contains("node") && message.contains("python"),
+ "the refusal must name the bad value and the accepted ones, got: {message}"
+ );
+
+ harness.join.abort();
+}
+
+/// `skill_runtime_run`'s two synchronous refusals, then `recent_runs`,
+/// `read_run_log` and `cancel` against planted logs.
+#[tokio::test]
+async fn skill_runtime_run_validation_and_run_log_surface() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ plant_skill(&harness.workspace, "planted-runtime-skill", "target_repo");
+
+ // Refusal 1: an id no root resolves.
+ let unknown = rpc(
+ &harness.rpc_base,
+ 110,
+ "openhuman.skill_runtime_run",
+ json!({ "skill_id": "no-such-skill-anywhere" }),
+ )
+ .await;
+ let message = error_message(&unknown, "skill_runtime_run unknown skill");
+ assert!(
+ message.contains("unknown skill") && message.contains("no-such-skill-anywhere"),
+ "the refusal must name the unresolved skill, got: {message}"
+ );
+
+ // Refusal 2: the skill resolves, but a declared `required` input is absent.
+ // This is the assertion that proves the planted skill's `skill.toml` was
+ // actually parsed — a fallback SKILL.md-only definition declares no inputs
+ // and would have started a run instead.
+ let missing_input = rpc(
+ &harness.rpc_base,
+ 111,
+ "openhuman.skill_runtime_run",
+ json!({ "skill_id": "planted-runtime-skill" }),
+ )
+ .await;
+ let message = error_message(&missing_input, "skill_runtime_run missing input");
+ assert!(
+ message.contains("missing required inputs") && message.contains("target_repo"),
+ "the refusal must name the missing input, got: {message}"
+ );
+
+ // An explicit null is treated as absent, not as a supplied value.
+ let null_input = rpc(
+ &harness.rpc_base,
+ 112,
+ "openhuman.skill_runtime_run",
+ json!({ "skill_id": "planted-runtime-skill", "inputs": { "target_repo": null } }),
+ )
+ .await;
+ assert!(
+ error_message(&null_input, "skill_runtime_run null input").contains("target_repo"),
+ "a null input must count as missing: {null_input}"
+ );
+
+ // ── the run-log surface, against logs whose content is knowable ──────────
+ let running_id = "aaaaaaaa-1111-2222-3333-444444444444";
+ let done_id = "bbbbbbbb-1111-2222-3333-444444444444";
+ plant_run_log(
+ &harness.workspace,
+ "planted-runtime-skill",
+ running_id,
+ "2026-09-07T10:10:10+00:00",
+ None,
+ );
+ plant_run_log(
+ &harness.workspace,
+ "planted-runtime-skill",
+ done_id,
+ "2026-09-07T11:10:10+00:00",
+ Some(("DONE", 4242, "PLANTED_RUN_OUTPUT")),
+ );
+ // A third run, under a different skill, to prove the filter bites.
+ plant_run_log(
+ &harness.workspace,
+ "some-other-skill",
+ "cccccccc-1111-2222-3333-444444444444",
+ "2026-09-07T12:10:10+00:00",
+ Some(("FAILED", 7, "nope")),
+ );
+
+ let recent = rpc(
+ &harness.rpc_base,
+ 113,
+ "openhuman.skill_runtime_recent_runs",
+ json!({}),
+ )
+ .await;
+ let recent = ok(&recent, "skill_runtime_recent_runs");
+ let runs = recent
+ .get("runs")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("recent_runs has no `runs` array: {recent}"));
+ assert_eq!(
+ runs.len(),
+ 3,
+ "all three planted runs must be seen: {recent}"
+ );
+ // Sorted most-recent-first by `started`.
+ assert_eq!(
+ runs.iter()
+ .filter_map(|r| r.get("workflow_id").and_then(Value::as_str))
+ .collect::<Vec<_>>(),
+ vec![
+ "some-other-skill",
+ "planted-runtime-skill",
+ "planted-runtime-skill"
+ ],
+ "runs must come back newest-first by `started`: {recent}"
+ );
+
+ // The unfinished log has no footer, so its status is the RUNNING default
+ // and it carries no duration; the finished one carries both.
+ let by_id = |id: &str| -> Value {
+ runs.iter()
+ .find(|r| r.get("run_id").and_then(Value::as_str) == Some(id))
+ .unwrap_or_else(|| panic!("run {id} missing from {recent}"))
+ .clone()
+ };
+ let running = by_id(running_id);
+ assert_eq!(
+ running.get("status").and_then(Value::as_str),
+ Some("RUNNING"),
+ "a log with no `--- result ---` footer must read as RUNNING: {running}"
+ );
+ assert!(
+ running.get("duration_ms").is_none_or(Value::is_null),
+ "an unfinished run must not report a duration: {running}"
+ );
+ let done = by_id(done_id);
+ assert_eq!(
+ done.get("status").and_then(Value::as_str),
+ Some("DONE"),
+ "the footer's status word must be parsed out: {done}"
+ );
+ assert_eq!(
+ done.get("duration_ms").and_then(Value::as_u64),
+ Some(4242),
+ "the footer's `duration: <n> ms` must be parsed to a number: {done}"
+ );
+
+ // Filtering scopes to one skill.
+ let filtered = rpc(
+ &harness.rpc_base,
+ 114,
+ "openhuman.skill_runtime_recent_runs",
+ json!({ "skill_id": "some-other-skill" }),
+ )
+ .await;
+ let filtered = ok(&filtered, "skill_runtime_recent_runs filtered");
+ let filtered_runs = filtered
+ .get("runs")
+ .and_then(Value::as_array)
+ .expect("runs");
+ assert_eq!(
+ filtered_runs.len(),
+ 1,
+ "the skill_id filter must exclude the other two: {filtered}"
+ );
+ assert_eq!(
+ filtered_runs[0].get("workflow_id").and_then(Value::as_str),
+ Some("some-other-skill")
+ );
+
+ // `limit` is honoured and clamped.
+ let limited = rpc(
+ &harness.rpc_base,
+ 115,
+ "openhuman.skill_runtime_recent_runs",
+ json!({ "limit": 1 }),
+ )
+ .await;
+ assert_eq!(
+ ok(&limited, "skill_runtime_recent_runs limit")
+ .get("runs")
+ .and_then(Value::as_array)
+ .map(Vec::len),
+ Some(1),
+ "limit must cap the result: {limited}"
+ );
+
+ // ── read_run_log ────────────────────────────────────────────────────────
+ let slice = rpc(
+ &harness.rpc_base,
+ 116,
+ "openhuman.skill_runtime_read_run_log",
+ json!({ "run_id": done_id }),
+ )
+ .await;
+ let slice = ok(&slice, "skill_runtime_read_run_log");
+ let content = slice
+ .get("content")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("read_run_log has no `content`: {slice}"));
+ assert!(
+ content.contains("PLANTED_RUN_OUTPUT") && content.contains(done_id),
+ "the slice must contain the log's own body and run id: {content}"
+ );
+ assert_eq!(
+ slice.get("eof").and_then(Value::as_bool),
+ Some(true),
+ "a default 64 KiB read of a tiny log reaches EOF: {slice}"
+ );
+ assert_eq!(
+ slice.get("complete").and_then(Value::as_bool),
+ Some(true),
+ "a log carrying the footer must report complete: {slice}"
+ );
+ let end_offset = slice
+ .get("offset")
+ .and_then(Value::as_u64)
+ .expect("offset cursor");
+ assert_eq!(
+ slice.get("bytes_read").and_then(Value::as_u64),
+ Some(end_offset),
+ "reading from offset 0, the cursor must equal the bytes returned: {slice}"
+ );
+
+ // Tail-mode: re-issuing at the returned cursor yields nothing new but keeps
+ // reporting `complete`, which is what stops the frontend polling.
+ let tail = rpc(
+ &harness.rpc_base,
+ 117,
+ "openhuman.skill_runtime_read_run_log",
+ json!({ "run_id": done_id, "offset": end_offset }),
+ )
+ .await;
+ let tail = ok(&tail, "skill_runtime_read_run_log tail");
+ assert_eq!(tail.get("bytes_read").and_then(Value::as_u64), Some(0));
+ assert_eq!(tail.get("content").and_then(Value::as_str), Some(""));
+ assert_eq!(tail.get("complete").and_then(Value::as_bool), Some(true));
+
+ // A still-running log reports `complete: false` — the polling frontend
+ // depends on that bit exactly.
+ let running_slice = rpc(
+ &harness.rpc_base,
+ 118,
+ "openhuman.skill_runtime_read_run_log",
+ json!({ "run_id": running_id }),
+ )
+ .await;
+ assert_eq!(
+ ok(&running_slice, "read_run_log running")
+ .get("complete")
+ .and_then(Value::as_bool),
+ Some(false),
+ "a footer-less log must not claim completion: {running_slice}"
+ );
+
+ // Failure path: an unknown run id resolves to no path and is refused.
+ let unknown_run = rpc(
+ &harness.rpc_base,
+ 119,
+ "openhuman.skill_runtime_read_run_log",
+ json!({ "run_id": "ffffffff-0000-0000-0000-000000000000" }),
+ )
+ .await;
+ let message = error_message(&unknown_run, "read_run_log unknown run");
+ assert!(
+ message.contains("unknown run_id"),
+ "the refusal must say the run id is unknown, got: {message}"
+ );
+
+ // ── cancel ──────────────────────────────────────────────────────────────
+ // No live run holds a cancellation token, so this is the documented
+ // "already finished or never existed" answer: reported, not thrown.
+ let cancel = rpc(
+ &harness.rpc_base,
+ 120,
+ "openhuman.skill_runtime_cancel",
+ json!({ "run_id": done_id }),
+ )
+ .await;
+ let cancel = ok(&cancel, "skill_runtime_cancel");
+ assert_eq!(
+ cancel.get("run_id").and_then(Value::as_str),
+ Some(done_id),
+ "cancel must echo the requested run id: {cancel}"
+ );
+ assert_eq!(
+ cancel.get("cancelled").and_then(Value::as_bool),
+ Some(false),
+ "cancelling a run with no live token must report false, not error: {cancel}"
+ );
+
+ harness.join.abort();
+}
+
+// ── skills (the uncovered half) ─────────────────────────────────────────────
+
+/// `skills_run` / `skills_recent_runs` / `skills_read_run_log` / `skills_cancel`
+/// — the older namespace over the same machinery, asserted at the points where
+/// its wire shape differs from `skill_runtime_*`.
+#[tokio::test]
+async fn skills_run_and_log_surface_keeps_its_own_wire_shape() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ plant_skill(&harness.workspace, "planted-legacy-skill", "ticket");
+
+ let unknown = rpc(
+ &harness.rpc_base,
+ 130,
+ "openhuman.skills_run",
+ json!({ "workflow_id": "not-a-skill" }),
+ )
+ .await;
+ assert!(
+ error_message(&unknown, "skills_run unknown").contains("unknown skill"),
+ "skills_run must refuse an unresolved id: {unknown}"
+ );
+
+ // `skills_run` takes `workflow_id` where `skill_runtime_run` takes
+ // `skill_id`; sending the sibling's spelling is a params error, which is
+ // worth pinning because the two namespaces front the same machinery.
+ let wrong_param = rpc(
+ &harness.rpc_base,
+ 131,
+ "openhuman.skills_run",
+ json!({ "skill_id": "planted-legacy-skill" }),
+ )
+ .await;
+ assert!(
+ error_message(&wrong_param, "skills_run wrong param").contains("workflow_id"),
+ "skills_run must name the param it wanted: {wrong_param}"
+ );
+
+ let missing_input = rpc(
+ &harness.rpc_base,
+ 132,
+ "openhuman.skills_run",
+ json!({ "workflow_id": "planted-legacy-skill" }),
+ )
+ .await;
+ assert!(
+ error_message(&missing_input, "skills_run missing input").contains("ticket"),
+ "skills_run must name the missing required input: {missing_input}"
+ );
+
+ let run_id = "dddddddd-1111-2222-3333-444444444444";
+ plant_run_log(
+ &harness.workspace,
+ "planted-legacy-skill",
+ run_id,
+ "2026-09-07T13:10:10+00:00",
+ Some(("DEGENERATE", 99, "PLANTED_LEGACY_OUTPUT")),
+ );
+
+ let recent = rpc(
+ &harness.rpc_base,
+ 133,
+ "openhuman.skills_recent_runs",
+ json!({ "workflow_id": "planted-legacy-skill" }),
+ )
+ .await;
+ let recent = ok(&recent, "skills_recent_runs");
+ let runs = recent
+ .get("runs")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("skills_recent_runs has no `runs`: {recent}"));
+ assert_eq!(runs.len(), 1, "one planted run for this skill: {recent}");
+ assert_eq!(
+ runs[0].get("status").and_then(Value::as_str),
+ Some("DEGENERATE"),
+ "a DEGENERATE footer must survive the scan verbatim: {recent}"
+ );
+ assert_eq!(runs[0].get("run_id").and_then(Value::as_str), Some(run_id));
+
+ let slice = rpc(
+ &harness.rpc_base,
+ 134,
+ "openhuman.skills_read_run_log",
+ json!({ "run_id": run_id, "max_bytes": 32 }),
+ )
+ .await;
+ let slice = ok(&slice, "skills_read_run_log capped");
+ assert_eq!(
+ slice.get("bytes_read").and_then(Value::as_u64),
+ Some(32),
+ "an explicit max_bytes must cap the slice at exactly that many bytes: {slice}"
+ );
+ assert_eq!(
+ slice.get("eof").and_then(Value::as_bool),
+ Some(false),
+ "a capped read short of the file end must not claim EOF: {slice}"
+ );
+ assert!(
+ slice
+ .get("content")
+ .and_then(Value::as_str)
+ .is_some_and(|c| c.starts_with("==== workflow_run:")),
+ "a read from offset 0 must start at the header banner: {slice}"
+ );
+
+ let cancel = rpc(
+ &harness.rpc_base,
+ 135,
+ "openhuman.skills_cancel",
+ json!({ "run_id": "not-a-live-run" }),
+ )
+ .await;
+ let cancel = ok(&cancel, "skills_cancel");
+ assert_eq!(
+ cancel.get("cancelled").and_then(Value::as_bool),
+ Some(false),
+ "an unknown run id is reported as not-cancelled, not as an error: {cancel}"
+ );
+ assert_eq!(
+ cancel.get("run_id").and_then(Value::as_str),
+ Some("not-a-live-run")
+ );
+
+ harness.join.abort();
+}
+
+/// `skills_read_resource` — the happy read plus the traversal and symlink
+/// guards, which are the reason this controller has a hand-written path jail
+/// rather than a plain `fs::read`.
+#[tokio::test]
+async fn skills_read_resource_reads_a_bundle_file_and_refuses_escapes() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ plant_skill(&harness.workspace, "planted-resource-skill", "unused");
+
+ let read = rpc(
+ &harness.rpc_base,
+ 140,
+ "openhuman.skills_read_resource",
+ json!({ "workflow_id": "planted-resource-skill", "relative_path": "references/note.md" }),
+ )
+ .await;
+ let read = ok(&read, "skills_read_resource");
+ assert_eq!(
+ read.get("content").and_then(Value::as_str),
+ Some("PLANTED_RESOURCE_BODY\n"),
+ "the resource body must come back verbatim: {read}"
+ );
+ assert_eq!(
+ read.get("bytes").and_then(Value::as_u64),
+ Some("PLANTED_RESOURCE_BODY\n".len() as u64),
+ "`bytes` must be the on-disk size, not a rounded or char count: {read}"
+ );
+ assert_eq!(
+ read.get("relative_path").and_then(Value::as_str),
+ Some("references/note.md"),
+ "the request path must be echoed back: {read}"
+ );
+ assert_eq!(
+ read.get("workflow_id").and_then(Value::as_str),
+ Some("planted-resource-skill")
+ );
+
+ // Traversal: `..` is rejected on the component walk, before any filesystem
+ // call — so this must fail even though the target exists.
+ let traversal = rpc(
+ &harness.rpc_base,
+ 141,
+ "openhuman.skills_read_resource",
+ json!({ "workflow_id": "planted-resource-skill", "relative_path": "../../../etc/passwd" }),
+ )
+ .await;
+ let message = error_message(&traversal, "skills_read_resource traversal");
+ assert!(
+ message.contains(".."),
+ "the traversal refusal must name the offending component, got: {message}"
+ );
+
+ // An absolute path is a separate rejection from `..`.
+ let absolute = rpc(
+ &harness.rpc_base,
+ 142,
+ "openhuman.skills_read_resource",
+ json!({ "workflow_id": "planted-resource-skill", "relative_path": "/etc/passwd" }),
+ )
+ .await;
+ let message = error_message(&absolute, "skills_read_resource absolute");
+ assert!(
+ message.contains("relative"),
+ "an absolute path must be refused for being absolute, got: {message}"
+ );
+
+ // A symlinked leaf pointing outside the bundle is caught by the
+ // `symlink_metadata` pre-check, not followed.
+ #[cfg(unix)]
+ {
+ let outside = harness.workspace.join("outside-secret.txt");
+ std::fs::write(&outside, "SHOULD_NOT_BE_READABLE\n").expect("write outside file");
+ let link = harness
+ .workspace
+ .join("skills")
+ .join("planted-resource-skill")
+ .join("references")
+ .join("escape.md");
+ std::os::unix::fs::symlink(&outside, &link).expect("create symlink");
+
+ let symlinked = rpc(
+ &harness.rpc_base,
+ 143,
+ "openhuman.skills_read_resource",
+ json!({ "workflow_id": "planted-resource-skill", "relative_path": "references/escape.md" }),
+ )
+ .await;
+ let message = error_message(&symlinked, "skills_read_resource symlink");
+ assert!(
+ message.contains("symlink"),
+ "a symlinked leaf must be refused as a symlink, got: {message}"
+ );
+ assert!(
+ !message.contains("SHOULD_NOT_BE_READABLE"),
+ "the refusal must not leak the target's contents: {message}"
+ );
+ }
+
+ // An unknown skill id is refused before any path work.
+ let unknown = rpc(
+ &harness.rpc_base,
+ 144,
+ "openhuman.skills_read_resource",
+ json!({ "workflow_id": "no-such-skill", "relative_path": "references/note.md" }),
+ )
+ .await;
+ assert!(
+ unknown.get("error").is_some(),
+ "reading a resource of an unknown skill must error: {unknown}"
+ );
+
+ harness.join.abort();
+}
+
+/// `skills_install_from_url` — the SSRF guards it exists to enforce, then the
+/// loopback happy path behind the documented escape hatch.
+#[tokio::test]
+async fn skills_install_from_url_enforces_its_url_policy_then_installs() {
+ let _lock = env_lock();
+ let (fixture_addr, fixture_join) = serve_fixture_catalog().await;
+ let harness = setup(vec![EnvVarGuard::set(
+ "OPENHUMAN_SKILL_INSTALL_ALLOW_LOCAL_HTTP",
+ "1",
+ )])
+ .await;
+
+ // Guard 1: plain HTTP to a non-loopback host is refused even with the
+ // local-HTTP hatch open — the hatch is loopback-only.
+ let plain_http = rpc(
+ &harness.rpc_base,
+ 150,
+ "openhuman.skills_install_from_url",
+ json!({ "url": "http://example.com/skill.md" }),
+ )
+ .await;
+ let message = error_message(&plain_http, "install_from_url plain http");
+ assert!(
+ message.contains("https"),
+ "a non-loopback http URL must be refused for its scheme, got: {message}"
+ );
+
+ // Guard 2: an https URL whose host is a private/loopback literal is the
+ // SSRF vector this controller's host check exists for.
+ for host in ["127.0.0.1", "10.0.0.1", "169.254.169.254"] {
+ let private = rpc(
+ &harness.rpc_base,
+ 151,
+ "openhuman.skills_install_from_url",
+ json!({ "url": format!("https://{host}/skill.md") }),
+ )
+ .await;
+ let message = error_message(&private, "install_from_url private host");
+ assert!(
+ message.contains(host) && message.contains("not allowed"),
+ "https://{host} must be refused by name, got: {message}"
+ );
+ }
+
+ // Guard 3: an https URL that is not a single `.md` file.
+ let not_md = rpc(
+ &harness.rpc_base,
+ 152,
+ "openhuman.skills_install_from_url",
+ json!({ "url": "https://example.com/some/repo" }),
+ )
+ .await;
+ let message = error_message(&not_md, "install_from_url non-md");
+ assert!(
+ message.contains("unsupported url form"),
+ "a non-`.md` target must be refused as an unsupported form, got: {message}"
+ );
+
+ // Happy path: loopback HTTP with the hatch open, against the fixture.
+ let installed = rpc(
+ &harness.rpc_base,
+ 153,
+ "openhuman.skills_install_from_url",
+ json!({
+ "url": format!("http://127.0.0.1:{}/skills/url-installed-skill/SKILL.md", fixture_addr.port()),
+ "timeout_secs": 30
+ }),
+ )
+ .await;
+ let installed = ok(&installed, "skills_install_from_url happy path");
+ assert!(
+ installed
+ .get("url")
+ .and_then(Value::as_str)
+ .is_some_and(|u| u.contains("url-installed-skill")),
+ "the installed URL must be echoed: {installed}"
+ );
+ // NOTE the field name. The controller schema declares this output as
+ // `new_skills`; the handler emits `new_workflows`. See
+ // `~/tinyhuman/bugs/e2e-wave-skills-schema-output-name-drift.md`. Asserted
+ // against what the code does, and against what the frontend reads
+ // (`app/src/services/api/skillsApi.ts:400`).
+ let new_workflows = installed
+ .get("new_workflows")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("install result has no `new_workflows`: {installed}"));
+ assert!(
+ new_workflows
+ .iter()
+ .any(|s| s.as_str() == Some("url-installed-skill")),
+ "the freshly installed slug must appear in `new_workflows`: {installed}"
+ );
+ assert!(
+ installed.get("new_skills").is_none(),
+ "the schema's declared `new_skills` is NOT what the handler emits; if this \
+ starts passing the schema and the handler have been reconciled and this \
+ suite plus the bug note need updating: {installed}"
+ );
+
+ // Installing the same URL again is an idempotent success reporting no new
+ // slugs — not a duplicate-directory error.
+ let again = rpc(
+ &harness.rpc_base,
+ 154,
+ "openhuman.skills_install_from_url",
+ json!({
+ "url": format!("http://127.0.0.1:{}/skills/url-installed-skill/SKILL.md", fixture_addr.port())
+ }),
+ )
+ .await;
+ let again = ok(&again, "skills_install_from_url idempotent");
+ assert_eq!(
+ again
+ .get("new_workflows")
+ .and_then(Value::as_array)
+ .map(Vec::len),
+ Some(0),
+ "a repeat install must report zero new slugs: {again}"
+ );
+
+ fixture_join.abort();
+ harness.join.abort();
+}
+
+// ── skill_registry ──────────────────────────────────────────────────────────
+
+/// `skill_registry_categories` — the distinct, sorted, non-empty categories of
+/// the catalog.
+#[tokio::test]
+async fn skill_registry_categories_are_distinct_sorted_and_drop_the_blank() {
+ let _lock = env_lock();
+ let (fixture_addr, fixture_join) = serve_fixture_catalog().await;
+ let fixture_base = format!("http://{fixture_addr}");
+ let harness = setup(vec![
+ EnvVarGuard::set(
+ "OPENHUMAN_SKILL_REGISTRY_CATALOG_URL",
+ &format!("{fixture_base}/skills.json"),
+ ),
+ EnvVarGuard::set(
+ "OPENHUMAN_SKILL_REGISTRY_DOWNLOAD_BASE_URL",
+ &format!("{fixture_base}/skills"),
+ ),
+ ])
+ .await;
+
+ let response = rpc(
+ &harness.rpc_base,
+ 160,
+ "openhuman.skill_registry_categories",
+ json!({}),
+ )
+ .await;
+ let response = ok(&response, "skill_registry_categories");
+ let categories: Vec<&str> = response
+ .get("categories")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("no `categories` array: {response}"))
+ .iter()
+ .map(|c| {
+ c.as_str()
+ .unwrap_or_else(|| panic!("a category must be a string: {c}"))
+ })
+ .collect();
+
+ assert!(
+ categories.contains(&"software-development") && categories.contains(&"productivity"),
+ "both fixture categories must be present, got {categories:?}"
+ );
+ assert!(
+ !categories.iter().any(|c| c.is_empty()),
+ "the blank category must be filtered out, got {categories:?}"
+ );
+ let mut sorted = categories.clone();
+ sorted.sort_unstable();
+ assert_eq!(
+ categories, sorted,
+ "categories must come back sorted, got {categories:?}"
+ );
+ let mut deduped = sorted.clone();
+ deduped.dedup();
+ assert_eq!(
+ categories.len(),
+ deduped.len(),
+ "categories must be distinct, got {categories:?}"
+ );
+
+ fixture_join.abort();
+ harness.join.abort();
+}
+
+// ── javascript ──────────────────────────────────────────────────────────────
+
+/// `javascript_list_tools` and `javascript_execute_tool` — the runtime bridge
+/// the agent reaches its tool registry through.
+///
+/// The happy path executes a real tool (`file_read`) against a file this test
+/// wrote into the action sandbox, so it proves the whole chain: build the
+/// registry, resolve by name, execute, and wrap the result in the MCP-style
+/// envelope.
+#[tokio::test]
+async fn javascript_bridge_lists_and_executes_a_real_tool() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+
+ let listed = rpc(
+ &harness.rpc_base,
+ 170,
+ "openhuman.javascript_list_tools",
+ json!({}),
+ )
+ .await;
+ // Assert the envelope explicitly before unwrapping: this handler always
+ // logs, so it is always wrapped, and that is the shape a caller must parse.
+ let listed_raw = ok(&listed, "javascript_list_tools");
+ assert!(
+ listed_raw.get("logs").is_some_and(Value::is_array),
+ "a handler that logs must return the `{{result, logs}}` envelope: {listed_raw}"
+ );
+ let listed = payload(&listed, "javascript_list_tools");
+ let tools = listed
+ .get("tools")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("no `tools` array: {listed}"));
+ assert!(
+ !tools.is_empty(),
+ "the bridge must expose a non-empty tool registry: {listed}"
+ );
+
+ let file_read = tools
+ .iter()
+ .find(|t| t.get("name").and_then(Value::as_str) == Some("file_read"))
+ .unwrap_or_else(|| {
+ panic!(
+ "`file_read` must be in the registry; got {:?}",
+ tools
+ .iter()
+ .filter_map(|t| t.get("name").and_then(Value::as_str))
+ .collect::<Vec<_>>()
+ )
+ });
+ // The schema documents each summary's fields; a caller renders from them.
+ for field in ["description", "permission_level", "parameters"] {
+ assert!(
+ file_read.get(field).is_some(),
+ "a tool summary must carry `{field}`: {file_read}"
+ );
+ }
+ // Sorted by name, per `ops::list_tools`.
+ let names: Vec<&str> = tools
+ .iter()
+ .filter_map(|t| t.get("name").and_then(Value::as_str))
+ .collect();
+ let mut sorted = names.clone();
+ sorted.sort_unstable();
+ assert_eq!(names, sorted, "the tool list must be sorted by name");
+
+ // Happy path: read a file the action sandbox actually holds.
+ let action_dir = std::env::var("OPENHUMAN_ACTION_DIR").expect("action dir set by setup()");
+ std::fs::write(
+ Path::new(&action_dir).join("bridge-fixture.txt"),
+ "BRIDGE_FIXTURE_BODY\n",
+ )
+ .expect("write action-dir fixture");
+
+ let executed = rpc(
+ &harness.rpc_base,
+ 171,
+ "openhuman.javascript_execute_tool",
+ json!({ "tool_name": "file_read", "args": { "path": "bridge-fixture.txt" } }),
+ )
+ .await;
+ let executed = payload(&executed, "javascript_execute_tool file_read");
+ assert_eq!(
+ executed.get("tool_name").and_then(Value::as_str),
+ Some("file_read"),
+ "the executed tool name must be echoed: {executed}"
+ );
+ assert!(
+ executed.get("elapsed_ms").is_some_and(Value::is_number),
+ "`elapsed_ms` must be a number: {executed}"
+ );
+ let result = executed
+ .get("result")
+ .unwrap_or_else(|| panic!("no `result` envelope: {executed}"));
+ assert_eq!(
+ result.get("is_error").and_then(Value::as_bool),
+ Some(false),
+ "reading a file that exists must not be an error result: {result}"
+ );
+ assert!(
+ result.to_string().contains("BRIDGE_FIXTURE_BODY"),
+ "the tool's output must carry the file's contents: {result}"
+ );
+
+ // Failure path 1: a registered tool given bad args fails *inside* the
+ // envelope — `is_error: true`, not a JSON-RPC error.
+ let bad_args = rpc(
+ &harness.rpc_base,
+ 172,
+ "openhuman.javascript_execute_tool",
+ json!({ "tool_name": "file_read", "args": { "path": "definitely-not-here.txt" } }),
+ )
+ .await;
+ let bad_args = payload(&bad_args, "javascript_execute_tool bad args");
+ assert_eq!(
+ bad_args.get("tool_name").and_then(Value::as_str),
+ Some("file_read"),
+ "a failing execution still echoes the tool name: {bad_args}"
+ );
+ assert_eq!(
+ bad_args
+ .get("result")
+ .and_then(|r| r.get("is_error"))
+ .and_then(Value::as_bool),
+ Some(true),
+ "a tool-level failure must surface as `is_error` in the envelope, not as \
+ a transport error: {bad_args}"
+ );
+
+ // Failure path 2: a name the registry does not hold is a dispatch error,
+ // which is a different outcome from the above and must stay different.
+ let unknown = rpc(
+ &harness.rpc_base,
+ 173,
+ "openhuman.javascript_execute_tool",
+ json!({ "tool_name": "no_such_tool_anywhere", "args": {} }),
+ )
+ .await;
+ let message = error_message(&unknown, "javascript_execute_tool unknown tool");
+ assert!(
+ message.contains("unknown tool") && message.contains("no_such_tool_anywhere"),
+ "an unregistered name must be refused by name, got: {message}"
+ );
+
+ // Failure path 3: the required param is missing entirely.
+ let no_name = rpc(
+ &harness.rpc_base,
+ 174,
+ "openhuman.javascript_execute_tool",
+ json!({ "args": {} }),
+ )
+ .await;
+ assert!(
+ error_message(&no_name, "javascript_execute_tool no name").contains("tool_name"),
+ "an absent `tool_name` must be named in the error: {no_name}"
+ );
+
+ harness.join.abort();
+}
diff --git a/tests/raw_coverage/todos_lifecycle_e2e.rs b/tests/raw_coverage/todos_lifecycle_e2e.rs
new file mode 100644
index 0000000000..173908633e
--- /dev/null
+++ b/tests/raw_coverage/todos_lifecycle_e2e.rs
@@ -0,0 +1,705 @@
+//! JSON-RPC E2E coverage for the `openhuman.todos_*` board lifecycle.
+//!
+//! Run:
+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" todos_`
+//!
+//! Everything here is hermetic: the todo board is a workspace-local store, so a
+//! temp `HOME` + `OPENHUMAN_WORKSPACE` is the whole fixture. No network.
+//!
+//! ## Why the `test` namespace is NOT covered here
+//!
+//! The wave brief flagged the single-method `test` namespace as possibly
+//! deliberately untestable. It is, and more decisively than "nobody got round
+//! to it": the whole `test_support` module — its one `test`-namespaced reset
+//! method plus the five read-only `test_support_*` introspection methods — is
+//! registered behind `#[cfg(feature = "e2e-test-support")]` at
+//! `src/core/all.rs:875`. That gate is in neither `[features] default` nor
+//! `scripts/ci/product-features.txt`; only `app/scripts/e2e-build.sh` turns it
+//! on. Dispatching the reset under the product feature string this wave
+//! mandates returns `unknown method`, which is the core's uniform "suppressed"
+//! answer (see `docs/openhuman-core.md` — absence, not failure).
+//!
+//! So no `tests/**/*_e2e.rs` target can reach it without a bespoke feature
+//! string, which would thrash the shared target dir for every worker. The
+//! honest reading is 0%, and it is left at 0% deliberately. Note also that the
+//! coverage gate's own denominator counts it: the namespace is discovered from
+//! a `ControllerSchema` literal, and schema literals are not `#[cfg]`-gated
+//! even though their registration is — so the gate asks for coverage of a
+//! method that does not exist in the build it measures.
+
+use std::net::SocketAddr;
+use std::path::Path;
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+use axum::http::header::AUTHORIZATION;
+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;
+
+/// The bearer this suite *proposes*. It is only used if this suite happens to
+/// be the first in the aggregated binary to initialise the token subsystem —
+/// see `rpc_token()` below, which is what actually gets sent.
+const PROPOSED_RPC_TOKEN: &str = "todos-lifecycle-e2e-token";
+
+static AUTH_INIT: OnceLock<()> = OnceLock::new();
+
+/// The crate-wide env lock, not a private one.
+///
+/// Every suite under `tests/raw_coverage/` compiles into the single
+/// `raw_coverage_all` binary, so libtest runs them concurrently in one process
+/// and a lock local to this file would isolate nothing — it would pass alone
+/// and race another suite under load.
+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;
+
+// ── Env plumbing ────────────────────────────────────────────────────────────
+
+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),
+ }
+ }
+}
+
+/// Serializes every env mutation across the whole aggregated binary: `HOME` /
+/// `OPENHUMAN_WORKSPACE` are process-global, so two cases running at once would
+/// read one another's workspace. Poison is recovered so a panicking case cannot
+/// wedge the other seventy-odd suites.
+fn env_lock() -> std::sync::MutexGuard<'static, ()> {
+ ENV_LOCK
+ .get_or_init(|| Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+/// The bearer the running process will actually validate.
+///
+/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token`
+/// returns early once it is set. Every `tests/raw_coverage/` suite now shares
+/// one process, so the FIRST suite to initialise pins the token for all of
+/// them; a suite that sent its own hard-coded literal would get 401 whenever it
+/// lost that race, in an order that depends on libtest scheduling and load.
+///
+/// So: propose a token, initialise, then ask what the process settled on and
+/// send that. Correct whether this suite wins the race or loses it.
+fn rpc_token() -> &'static str {
+ AUTH_INIT.get_or_init(|| {
+ if std::env::var(CORE_TOKEN_ENV_VAR)
+ .map(|v| v.trim().is_empty())
+ .unwrap_or(true)
+ {
+ std::env::set_var(CORE_TOKEN_ENV_VAR, PROPOSED_RPC_TOKEN);
+ }
+ let token_dir = std::env::temp_dir().join("openhuman-todos-lifecycle-e2e-auth");
+ std::fs::create_dir_all(&token_dir).expect("token dir");
+ init_rpc_token(&token_dir).expect("init rpc auth token");
+ });
+ openhuman_core::core::auth::get_rpc_token()
+ .expect("the token subsystem is initialised by the line above")
+}
+
+// ── Harness ─────────────────────────────────────────────────────────────────
+
+const MIN_CONFIG: &str = r#"api_url = "http://127.0.0.1:9"
+default_model = "todos-e2e-model"
+
+[secrets]
+encrypt = false
+
+[local_ai]
+enabled = false
+
+[memory]
+provider = "none"
+embedding_provider = "none"
+embedding_model = "none"
+embedding_dimensions = 0
+
+[memory_tree]
+embedding_strict = false
+"#;
+
+struct Harness {
+ _tmp: TempDir,
+ _guards: Vec<EnvVarGuard>,
+ rpc_base: String,
+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,
+}
+
+async fn setup(extra: Vec<EnvVarGuard>) -> Harness {
+ let _ = rpc_token();
+
+ let tmp = tempdir().expect("tempdir");
+ let home = tmp.path();
+ let openhuman_home = home.join(".openhuman");
+ std::fs::create_dir_all(&openhuman_home).expect("create .openhuman");
+ std::fs::write(openhuman_home.join("config.toml"), MIN_CONFIG).expect("write config.toml");
+ // Parsed here so a schema drift fails as a config error rather than as a
+ // baffling handler error three calls later.
+ let _: openhuman_core::openhuman::config::Config =
+ toml::from_str(MIN_CONFIG).expect("test config must match the config schema");
+
+ let workspace = home.join("workspace");
+ std::fs::create_dir_all(&workspace).expect("create workspace");
+
+ let mut guards = vec![
+ EnvVarGuard::set_to_path("HOME", home),
+ 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"),
+ ];
+ guards.extend(extra);
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind rpc listener");
+ let addr: SocketAddr = listener.local_addr().expect("rpc listener addr");
+ let router = build_core_http_router(false);
+ let join = tokio::spawn(async move { axum::serve(listener, router).await });
+
+ Harness {
+ _tmp: tmp,
+ _guards: guards,
+ rpc_base: format!("http://{addr}"),
+ join,
+ }
+}
+
+async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(60))
+ .build()
+ .expect("build client");
+ let url = format!("{}/rpc", base.trim_end_matches('/'));
+ let response = client
+ .post(&url)
+ .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))
+ .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))
+ .send()
+ .await
+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));
+ assert!(
+ response.status().is_success(),
+ "HTTP {} for {method}",
+ response.status()
+ );
+ response
+ .json::<Value>()
+ .await
+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))
+}
+
+fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {
+ if let Some(error) = value.get("error") {
+ panic!("{context}: unexpected JSON-RPC error: {error}");
+ }
+ value
+ .get("result")
+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"))
+}
+
+fn error_message<'a>(value: &'a Value, context: &str) -> &'a str {
+ 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 carries no message: {value}"))
+}
+
+/// The todos handlers return the snapshot unwrapped (see `snapshot_output` —
+/// the catalog names the payload, the handler returns it flat), so cards live
+/// at the top level of `result`.
+fn cards<'a>(result: &'a Value, context: &str) -> &'a Vec<Value> {
+ result
+ .get("cards")
+ .and_then(Value::as_array)
+ .unwrap_or_else(|| panic!("{context}: snapshot carries no `cards` array: {result}"))
+}
+
+/// Card titles, in board order.
+///
+/// The wire field is `title` — note that the `todos_add` / `todos_edit` *input*
+/// params spell the same thing `content`, and `todos_replace`'s input spells it
+/// `title` again. See `~/tinyhuman/bugs/e2e-wave-todos-replace-undocumented-card-shape.md`.
+fn card_titles(result: &Value, context: &str) -> Vec<String> {
+ cards(result, context)
+ .iter()
+ .map(|card| {
+ card.get("title")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("{context}: card without `title`: {card}"))
+ .to_string()
+ })
+ .collect()
+}
+
+// ── Cases ───────────────────────────────────────────────────────────────────
+
+/// `replace` → `list` → `set_session_thread` → `clear`: the write half of the
+/// board that had no e2e coverage at all.
+///
+/// Asserts on content, not on `Ok`: the exact card titles after a wholesale
+/// replace, the session link landing on the right card, and `clear` actually
+/// emptying the list rather than returning a stale snapshot.
+#[tokio::test]
+async fn todos_replace_set_session_thread_and_clear_round_trip() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ let thread = "todos-e2e-thread-a";
+
+ // A wholesale replace on an empty board is the create path.
+ let replaced = rpc(
+ &harness.rpc_base,
+ 1,
+ "openhuman.todos_replace",
+ json!({
+ "thread_id": thread,
+ // `id`, `title` and `status` must all be PRESENT — none of the
+ // three carries `#[serde(default)]`. The schema's "id may be empty
+ // — server generates" means the string may be empty, not the key
+ // may be absent, and the schema names no field at all.
+ "cards": [
+ { "id": "", "title": "draft the migration", "status": "todo" },
+ { "id": "", "title": "review the migration", "status": "in_progress" }
+ ]
+ }),
+ )
+ .await;
+ let replaced = ok(&replaced, "todos_replace");
+ assert_eq!(
+ card_titles(replaced, "todos_replace"),
+ vec![
+ "draft the migration".to_string(),
+ "review the migration".to_string()
+ ],
+ "replace must persist exactly the cards it was given, in order"
+ );
+ assert!(
+ replaced
+ .get("markdown")
+ .and_then(Value::as_str)
+ .is_some_and(|md| md.contains("draft the migration")),
+ "the snapshot's markdown rendering must include the card titles: {replaced}"
+ );
+
+ // The server mints ids for the blank ones; `list` must read back the same
+ // board from disk rather than an in-memory echo of the request.
+ let listed = rpc(
+ &harness.rpc_base,
+ 2,
+ "openhuman.todos_list",
+ json!({ "thread_id": thread }),
+ )
+ .await;
+ let listed = ok(&listed, "todos_list");
+ assert_eq!(
+ card_titles(listed, "todos_list"),
+ card_titles(replaced, "todos_replace"),
+ "list must return the board replace just wrote"
+ );
+ let first_id = cards(listed, "todos_list")[0]
+ .get("id")
+ .and_then(Value::as_str)
+ .expect("server-minted card id")
+ .to_string();
+ assert!(!first_id.is_empty(), "server must mint a non-empty card id");
+
+ // Link the card to an agent session's thread, then clear the link.
+ let linked = rpc(
+ &harness.rpc_base,
+ 3,
+ "openhuman.todos_set_session_thread",
+ json!({ "thread_id": thread, "id": first_id, "sessionThreadId": "agent-session-77" }),
+ )
+ .await;
+ let linked = ok(&linked, "todos_set_session_thread");
+ let linked_card = cards(linked, "todos_set_session_thread")
+ .iter()
+ .find(|card| card.get("id").and_then(Value::as_str) == Some(first_id.as_str()))
+ .expect("the linked card survives the write");
+ assert_eq!(
+ linked_card
+ .get("sessionThreadId")
+ .or_else(|| linked_card.get("session_thread_id"))
+ .and_then(Value::as_str),
+ Some("agent-session-77"),
+ "set_session_thread must stamp the session link onto the named card: {linked_card}"
+ );
+
+ let unlinked = rpc(
+ &harness.rpc_base,
+ 4,
+ "openhuman.todos_set_session_thread",
+ json!({ "thread_id": thread, "id": first_id }),
+ )
+ .await;
+ let unlinked = ok(&unlinked, "todos_set_session_thread clear");
+ let unlinked_card = cards(unlinked, "todos_set_session_thread clear")
+ .iter()
+ .find(|card| card.get("id").and_then(Value::as_str) == Some(first_id.as_str()))
+ .expect("the card survives the clear");
+ assert!(
+ unlinked_card
+ .get("sessionThreadId")
+ .or_else(|| unlinked_card.get("session_thread_id"))
+ .and_then(Value::as_str)
+ .is_none(),
+ "an omitted sessionThreadId must clear the link, not leave it: {unlinked_card}"
+ );
+
+ // Clear empties the board, and the emptiness survives a re-read.
+ let cleared = rpc(
+ &harness.rpc_base,
+ 5,
+ "openhuman.todos_clear",
+ json!({ "thread_id": thread }),
+ )
+ .await;
+ let cleared = ok(&cleared, "todos_clear");
+ assert!(
+ cards(cleared, "todos_clear").is_empty(),
+ "clear must return an empty board: {cleared}"
+ );
+
+ let after_clear = rpc(
+ &harness.rpc_base,
+ 6,
+ "openhuman.todos_list",
+ json!({ "thread_id": thread }),
+ )
+ .await;
+ assert!(
+ cards(
+ ok(&after_clear, "todos_list after clear"),
+ "todos_list after clear"
+ )
+ .is_empty(),
+ "the cleared board must still be empty when re-read from disk"
+ );
+
+ harness.join.abort();
+}
+
+/// `decide_plan` on a card awaiting approval, plus the two failure paths the
+/// board's write handlers share: a blank `thread_id` and an unknown card id.
+#[tokio::test]
+async fn todos_decide_plan_approves_and_rejects_and_refuses_bad_input() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ let thread = "todos-e2e-thread-b";
+
+ let seeded = rpc(
+ &harness.rpc_base,
+ 10,
+ "openhuman.todos_replace",
+ json!({
+ "thread_id": thread,
+ "cards": [
+ { "id": "", "title": "ship the thing", "status": "awaiting_approval" },
+ { "id": "", "title": "ship the other thing", "status": "awaiting_approval" }
+ ]
+ }),
+ )
+ .await;
+ let seeded = ok(&seeded, "seed for decide_plan");
+ let seeded_cards = cards(seeded, "seed for decide_plan");
+ assert_eq!(seeded_cards.len(), 2, "two cards seeded: {seeded}");
+ let approve_id = seeded_cards[0]["id"].as_str().expect("card id").to_string();
+ let reject_id = seeded_cards[1]["id"].as_str().expect("card id").to_string();
+
+ let approved = rpc(
+ &harness.rpc_base,
+ 11,
+ "openhuman.todos_decide_plan",
+ json!({ "thread_id": thread, "id": approve_id, "approve": true }),
+ )
+ .await;
+ let approved = ok(&approved, "todos_decide_plan approve");
+ let approved_status = cards(approved, "todos_decide_plan approve")
+ .iter()
+ .find(|card| card["id"].as_str() == Some(approve_id.as_str()))
+ .and_then(|card| card.get("status"))
+ .and_then(Value::as_str)
+ .expect("approved card keeps a status")
+ .to_string();
+ assert_ne!(
+ approved_status, "awaiting_approval",
+ "approving must move the card off awaiting_approval, got {approved_status}"
+ );
+ assert_ne!(
+ approved_status, "rejected",
+ "approving must not reject the card"
+ );
+
+ let rejected = rpc(
+ &harness.rpc_base,
+ 12,
+ "openhuman.todos_decide_plan",
+ json!({ "thread_id": thread, "id": reject_id, "approve": false }),
+ )
+ .await;
+ let rejected = ok(&rejected, "todos_decide_plan reject");
+ assert_eq!(
+ cards(rejected, "todos_decide_plan reject")
+ .iter()
+ .find(|card| card["id"].as_str() == Some(reject_id.as_str()))
+ .and_then(|card| card.get("status"))
+ .and_then(Value::as_str),
+ Some("rejected"),
+ "rejecting must set the card's status to rejected: {rejected}"
+ );
+
+ // Failure path 1: a blank thread_id is refused before any store is opened.
+ let blank_thread = rpc(
+ &harness.rpc_base,
+ 13,
+ "openhuman.todos_decide_plan",
+ json!({ "thread_id": " ", "id": approve_id, "approve": true }),
+ )
+ .await;
+ assert!(
+ error_message(&blank_thread, "todos_decide_plan blank thread")
+ .contains("thread_id must not be empty"),
+ "a blank thread_id must be named in the error, got: {blank_thread}"
+ );
+
+ // Failure path 2: an unknown card id must error rather than silently
+ // returning an unchanged board — a no-op success here would let the UI
+ // report a decision that never landed.
+ let unknown_card = rpc(
+ &harness.rpc_base,
+ 14,
+ "openhuman.todos_decide_plan",
+ json!({ "thread_id": thread, "id": "no-such-card-id", "approve": true }),
+ )
+ .await;
+ assert!(
+ unknown_card.get("error").is_some(),
+ "deciding an unknown card must be an error, not a silent no-op: {unknown_card}"
+ );
+
+ harness.join.abort();
+}
+
+/// The run-record surface: `run_list`, `run_get`, and `reclaim_stale` on a
+/// thread with no runs — the empty-state contract every caller hits first.
+#[tokio::test]
+async fn todos_run_records_and_reclaim_report_an_honest_empty_state() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ let thread = "todos-e2e-thread-c";
+
+ let runs = rpc(
+ &harness.rpc_base,
+ 20,
+ "openhuman.todos_run_list",
+ json!({ "thread_id": thread }),
+ )
+ .await;
+ let runs = ok(&runs, "todos_run_list");
+ assert_eq!(
+ runs.as_array().map(Vec::len),
+ Some(0),
+ "a thread with no runs must list an empty array, not null or an object: {runs}"
+ );
+
+ // Same, filtered by a card that has never run.
+ let filtered = rpc(
+ &harness.rpc_base,
+ 21,
+ "openhuman.todos_run_list",
+ json!({ "thread_id": thread, "cardId": "card-that-never-ran" }),
+ )
+ .await;
+ assert_eq!(
+ ok(&filtered, "todos_run_list filtered")
+ .as_array()
+ .map(Vec::len),
+ Some(0),
+ "filtering by an unknown card id must return an empty list: {filtered}"
+ );
+
+ // `run_get` for an unknown run is a documented `null`, not an error — the
+ // Tasks board polls this and a thrown error would surface as a red toast.
+ let missing = rpc(
+ &harness.rpc_base,
+ 22,
+ "openhuman.todos_run_get",
+ json!({ "thread_id": thread, "runId": "no-such-run" }),
+ )
+ .await;
+ assert_eq!(
+ ok(&missing, "todos_run_get missing"),
+ &Value::Null,
+ "run_get for an unknown run id must be null: {missing}"
+ );
+
+ // `reclaim_stale` with nothing to reclaim must still report the counters,
+ // so a caller can tell "scanned, found none" from "did not scan".
+ let reclaimed = rpc(
+ &harness.rpc_base,
+ 23,
+ "openhuman.todos_reclaim_stale",
+ json!({ "thread_id": thread, "heartbeatStaleSecs": 1, "claimTtlSecs": 1, "maxReclaimCount": 1 }),
+ )
+ .await;
+ let reclaimed = ok(&reclaimed, "todos_reclaim_stale");
+ assert_eq!(
+ reclaimed.get("reclaimedCount").and_then(Value::as_u64),
+ Some(0),
+ "nothing to reclaim must be reported as 0, not omitted: {reclaimed}"
+ );
+ assert_eq!(
+ reclaimed.get("blockedCount").and_then(Value::as_u64),
+ Some(0),
+ "nothing blocked must be reported as 0: {reclaimed}"
+ );
+ assert_eq!(
+ reclaimed
+ .get("details")
+ .and_then(Value::as_array)
+ .map(Vec::len),
+ Some(0),
+ "an empty reclaim must carry an empty details array: {reclaimed}"
+ );
+
+ // The run surface refuses a blank thread just like the card surface does.
+ let blank = rpc(
+ &harness.rpc_base,
+ 24,
+ "openhuman.todos_run_list",
+ json!({ "thread_id": "" }),
+ )
+ .await;
+ assert!(
+ error_message(&blank, "todos_run_list blank thread")
+ .contains("thread_id must not be empty"),
+ "run_list must refuse a blank thread_id: {blank}"
+ );
+
+ harness.join.abort();
+}
+
+/// `todos_replace`'s declared contract cannot be satisfied from the schema.
+///
+/// The controller catalog declares one input — `cards: Json`, commented
+/// *"Array of card objects (id may be empty — server generates)"* — and names
+/// no field of a card anywhere. The handler deserializes each entry into
+/// `TaskBoardCard`, whose `id`, `title` and `status` all lack
+/// `#[serde(default)]`, so every one of them must be **present**. Two
+/// consequences a caller reading the schema walks straight into, both pinned
+/// below:
+///
+/// 1. The obvious spelling — `content`, which is what the sibling `todos_add`
+/// and `todos_edit` inputs call the very same text — is rejected outright.
+/// 2. "id may be empty" is about the string, not the key: omitting `status`
+/// fails even with a well-formed title.
+///
+/// This is a documentation defect in the schema, not behaviour to change here.
+/// See `~/tinyhuman/bugs/e2e-wave-todos-replace-undocumented-card-shape.md`.
+/// The assertions are written against what the code *does*, so the day the
+/// schema and the handler are reconciled this case fails and gets updated
+/// deliberately rather than silently drifting.
+#[tokio::test]
+async fn todos_replace_rejects_the_card_shape_its_own_schema_implies() {
+ let _lock = env_lock();
+ let harness = setup(Vec::new()).await;
+ let thread = "todos-e2e-thread-shape";
+
+ // `content` — the name every other todos input uses for this field.
+ let with_content = rpc(
+ &harness.rpc_base,
+ 40,
+ "openhuman.todos_replace",
+ json!({
+ "thread_id": thread,
+ "cards": [{ "id": "", "content": "spelled the sibling way", "status": "todo" }]
+ }),
+ )
+ .await;
+ let message = error_message(&with_content, "todos_replace with `content`");
+ assert!(
+ message.contains("missing field") && message.contains("title"),
+ "the `content` spelling must fail naming `title`, got: {message}"
+ );
+
+ // A well-formed title, but no status.
+ let no_status = rpc(
+ &harness.rpc_base,
+ 41,
+ "openhuman.todos_replace",
+ json!({ "thread_id": thread, "cards": [{ "id": "", "title": "no status here" }] }),
+ )
+ .await;
+ let message = error_message(&no_status, "todos_replace without `status`");
+ assert!(
+ message.contains("missing field") && message.contains("status"),
+ "an absent `status` must be rejected, got: {message}"
+ );
+
+ // And a well-formed title with no `id` key at all — "id may be empty" does
+ // not extend to omitting it.
+ let no_id = rpc(
+ &harness.rpc_base,
+ 42,
+ "openhuman.todos_replace",
+ json!({ "thread_id": thread, "cards": [{ "title": "no id key", "status": "todo" }] }),
+ )
+ .await;
+ let message = error_message(&no_id, "todos_replace without `id`");
+ assert!(
+ message.contains("missing field") && message.contains("id"),
+ "an absent `id` key must be rejected even though an empty `id` is fine, got: {message}"
+ );
+
+ // Nothing partial was written on the way through the three refusals.
+ let listed = rpc(
+ &harness.rpc_base,
+ 43,
+ "openhuman.todos_list",
+ json!({ "thread_id": thread }),
+ )
+ .await;
+ assert!(
+ cards(
+ ok(&listed, "board after refused replaces"),
+ "board after refused replaces"
+ )
+ .is_empty(),
+ "a rejected replace must leave the board untouched: {listed}"
+ );
+
+ harness.join.abort();
+}