The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(e2e): cover 37 untested RPC controllers across 10 namespaces\n\nCloses the E2E gap for `flows` (drafts, duplicate/enable, revision history\nand rollback, run-history read/prune, the save-time approval manifest,\nconnector requirements, the canvas tool browser, the copilot Stop button),\n`cron` (run/runs/remove), `workflow_run` (stop/resume), `task_sources`\n(sync, list_databases), `agent_work` (control), `agent_team` (list/close),\n`subagent` (cancel/steer), `harness_init` (run), `agent_experience` (all\nfour) and `hooks` (all three).\n\nEvery case dispatches over the real Axum JSON-RPC router against an\nisolated HOME and asserts on the *content* of the response, not on Ok-ness,\nand each covers at least one failure path. Nothing reaches the network:\n`api_url` is a closed port, `OPENHUMAN_ACTION_DIR` is pinned inside the\ntempdir (it otherwise defaults to the developer's real `~/OpenHuman/\nprojects`), and every provisioning switch harness-init would act on is\nasserted OFF in the parsed config before a step runs — `Config` does not\n`deny_unknown_fields`, so a mistyped table would silently let it download\nNode.js and CPython.\n\nThe three files are modules under `tests/raw_coverage/`, aggregated into\nthe single `raw_coverage_all` target by `build.rs`, so they add no new\nlink step and need no `Cargo.toml` edit. They bind the crate-wide\n`SHARED_ENV_LOCK` rather than a private one, and read the process bearer\nback from `get_rpc_token()` instead of assuming their own literal won the\n`RPC_TOKEN` `OnceLock` — several existing aggregated suites hard-code\nconflicting bearers, and only the first to run wins.\n\nCoverage gate: the ten namespaces go from 46/83 to 83/83; the repo total\nmoves 379 -> 416 of 627 controllers named by an e2e target.\n\nRevert-proofed: eleven independent faults were injected into production\ncode, one per namespace, and produced exactly eleven failures — each one\nnaming the assertion for its own fault. `src/` is unchanged by this commit.\n\nFour defects found while writing these and reported separately (not fixed\nhere; a test PR that also changes behaviour cannot be reviewed as either).\nThe tests pin the current behaviour with a pointer to each report:\n - flows_approval_manifest reports un-granted permissions as\n `already_trusted` when the approval gate is not installed\n - flows_get_tool_contract's `<TOOLKIT>_<ACTION>` guard is unreachable for\n any non-empty slug\n - the whole task_sources fetch pipeline is a hard-coded Err\n - cron_run's schema declares an outcome it never returns; cron_runs\n cannot distinguish an unknown job from one with no runs; and a shell\n job whose action_dir is absent fails with an unattributable ENOENT\n
M3gA-Mind82a71c69fdc6
diff --git a/tests/raw_coverage/agent_orchestration_e2e.rs b/tests/raw_coverage/agent_orchestration_e2e.rsnew file mode 100644index 0000000000..01b26839c9--- /dev/null+++ b/tests/raw_coverage/agent_orchestration_e2e.rs@@ -0,0 +1,1202 @@+//! JSON-RPC E2E coverage for the agent-orchestration controllers that no e2e+//! target reached: durable workflow-run `stop` / `resume`, the command+//! center's `agent_work_control`, `agent_team_list` / `agent_team_close`, the+//! detached sub-agent controls (`subagent_cancel` / `subagent_steer`), and the+//! whole `agent_experience` store.+//!+//! Every case boots the real Axum JSON-RPC router over HTTP against an+//! isolated `HOME` and asserts on the **content** of the response. Nothing+//! here needs a model: the durable ledger writes, the control-verb validation+//! and the sub-agent registry lookups are all reachable offline, and `api_url`+//! points at a closed port so a spawned engine loop fails fast instead of+//! reaching the network.+//!+//! Aggregated into `tests/raw_coverage_all.rs` by `build.rs`. Run with:+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" agent_orchestration_e2e`++use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;++/// Seeded only if this suite is the first in the aggregated binary to+/// initialise the token; the bearer actually sent is always read back from+/// `get_rpc_token()`, because `RPC_TOKEN` is a process-global `OnceLock` and+/// whichever aggregated suite calls `init_rpc_token` first wins it for all.+const TEST_RPC_TOKEN: &str = "agent-orchestration-e2e-token";++/// The one builtin workflow definition (`ops::PARALLEL_RESEARCH_ID`).+const BUILTIN_WORKFLOW_ID: &str = "parallel_research_cross_check";++static AUTH_INIT: OnceLock<()> = OnceLock::new();+static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new();++/// The crate-wide env lock, not a private one. Every aggregated suite in+/// `raw_coverage_all` shares one process, so libtest runs them concurrently+/// and a lock local to this file would isolate nothing.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++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),+ }+ }+}++fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++/// Initialise the process RPC token (idempotent) and return the bearer the+/// router will actually accept.+fn ensure_rpc_auth() -> &'static str {+ AUTH_INIT.get_or_init(|| {+ if get_rpc_token().is_none() {+ std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);+ }+ let token_dir = std::env::temp_dir().join("openhuman-agent-orchestration-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+ get_rpc_token().expect("rpc token initialized")+}++/// The transport-only JSON-RPC router builds no core runtime context, so+/// neither the memory host seams nor the **module host policy** a+/// driver-backed controller (`agent_experience`) needs are installed by booting+/// it. Without the policy every call fails with "the module host policy was+/// never published, so module 'tinymemory' cannot be loaded".+///+/// Both are installed on a thread with a stack of its own: `Config::default()`+/// is large enough to overflow the 2 MiB libtest stack if materialised inside+/// an async test frame.+///+/// `MODULES_POLICY` is a process-global `OnceLock` and several other aggregated+/// suites publish their own, so **this may lose the race** — `set_modules_policy`+/// silently ignores a later call, and the loaded module keeps whichever+/// workspace won. The experience cases below are therefore written not to+/// depend on owning the store: they use ids unique to this suite and assert on+/// their own records rather than on the store being empty.+fn ensure_memory_seams() {+ MEMORY_SEAMS_INIT.get_or_init(|| {+ std::thread::Builder::new()+ .name("agent-orchestration-e2e-memory-seams".to_string())+ .stack_size(8 * 1024 * 1024)+ .spawn(|| {+ let workspace = tempfile::tempdir()+ .expect("module workspace tempdir")+ .keep()+ .join("workspace");+ std::fs::create_dir_all(&workspace).expect("create module workspace");+ let config = Arc::new(openhuman_core::openhuman::config::Config {+ workspace_dir: workspace,+ ..openhuman_core::openhuman::config::Config::default()+ });+ openhuman_core::openhuman::memory::host_impls::install_memory_host_seams(+ Arc::clone(&config),+ );+ #[cfg(feature = "modules")]+ openhuman_core::openhuman::modules::memory::set_modules_policy(config);+ })+ .expect("spawn agent orchestration e2e seam installer")+ .join()+ .expect("agent orchestration e2e seam installer panicked");+ });+}++async fn serve_rpc() -> (+ SocketAddr,+ &'static str,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ let token = ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let join =+ tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });+ (addr, token, join)+}++/// `api_url` points at a closed port on purpose: a workflow run's spawned+/// engine loop must fail fast rather than reach the network.+fn write_min_config(openhuman_dir: &Path) {+ let cfg = r#"api_url = "http://127.0.0.1:9"+default_model = "orchestration-e2e-model"+default_temperature = 0.2+chat_onboarding_completed = true++[secrets]+encrypt = false++[local_ai]+enabled = false++[node]+enabled = false++[runtime_python]+enabled = false++[memory_tree]+embedding_strict = false+spacy_enabled = false+"#;+ let write = |dir: &Path| {+ std::fs::create_dir_all(dir).expect("create config dir");+ std::fs::write(dir.join("config.toml"), cfg).expect("write config.toml");+ };+ write(openhuman_dir);+ // Runtime config resolution is user-scoped before login, so the pre-login+ // `users/local` layer needs the same file or the RPC handlers load defaults.+ write(&openhuman_dir.join("users").join("local"));+ let _: openhuman_core::openhuman::config::Config =+ toml::from_str(cfg).expect("test config must match the Config schema");+}++struct Harness {+ _tmp: TempDir,+ _guards: Vec<EnvVarGuard>,+ rpc_base: String,+ token: &'static str,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++impl Harness {+ async fn rpc(&self, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(120))+ .build()+ .expect("build rpc client");+ let url = format!("{}/rpc", self.rpc_base);+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", self.token))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": method,+ "params": params,+ }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+ }++ async fn ok(&self, id: i64, method: &str, params: Value) -> Value {+ let response = self.rpc(id, method, params).await;+ if let Some(error) = response.get("error") {+ panic!("{method}: unexpected JSON-RPC error: {error}");+ }+ let result = response+ .get("result")+ .unwrap_or_else(|| panic!("{method}: missing result: {response}"));+ match result.get("result") {+ Some(inner) if result.get("logs").is_some() => inner.clone(),+ _ => result.clone(),+ }+ }++ async fn err(&self, id: i64, method: &str, params: Value) -> String {+ let response = self.rpc(id, method, params).await;+ let error = response+ .get("error")+ .unwrap_or_else(|| panic!("{method}: expected a JSON-RPC error, got: {response}"));+ error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{method}: error carries no message: {error}"))+ .to_string()+ }+}++async fn setup() -> Harness {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path().to_path_buf();+ write_min_config(&home.join(".openhuman"));++ // Left at its default, `action_dir` is `~/OpenHuman/projects` — the+ // developer's real directory. Pin it inside the tempdir.+ let action_dir = home.join("actions");+ std::fs::create_dir_all(&action_dir).expect("create action dir");++ let guards = vec![+ EnvVarGuard::set_to_path("HOME", &home),+ EnvVarGuard::set_to_path("OPENHUMAN_ACTION_DIR", &action_dir),+ EnvVarGuard::unset("OPENHUMAN_WORKSPACE"),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let (addr, token, join) = serve_rpc().await;+ Harness {+ _tmp: tmp,+ _guards: guards,+ rpc_base: format!("http://{addr}"),+ token,+ join,+ }+}++fn str_at<'a>(value: &'a Value, pointer: &str) -> &'a str {+ value+ .pointer(pointer)+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("expected a string at {pointer} in {value}"))+}++// ── workflow_run: stop / resume ─────────────────────────────────────────────++/// Stop marks a live run **interrupted** and aborts its children; resume picks+/// it back up from the first incomplete phase. Neither is a no-op, and the+/// phase ledger must survive both — that is what makes a resume a resume+/// rather than a restart.+///+/// The engine loop this starts cannot reach a model (`api_url` is a closed+/// port), so the run settles quickly on its own. The assertion that bites+/// either way is that after a stop the run is **not** `running`.+#[tokio::test]+async fn workflow_run_stop_then_resume_preserves_the_phase_ledger() {+ let _lock = env_lock();+ let h = setup().await;++ let started = h+ .ok(+ 3001,+ "openhuman.workflow_run_start",+ json!({+ "definitionId": BUILTIN_WORKFLOW_ID,+ "input": { "question": "what does stop do?" },+ "parentThreadId": "thread-orchestration-e2e",+ }),+ )+ .await;+ let run = started+ .get("workflowRun")+ .unwrap_or_else(|| panic!("start returns the created run: {started}"));+ let run_id = str_at(run, "/id").to_string();+ assert!(+ run_id.starts_with("wfrun-"),+ "a durable run id is namespaced: {run_id}"+ );+ assert_eq!(+ run.get("definitionId").and_then(Value::as_str),+ Some(BUILTIN_WORKFLOW_ID)+ );+ assert_eq!(+ run.get("status").and_then(Value::as_str),+ Some("running"),+ "start returns the run already Running: {started}"+ );+ assert_eq!(+ run.get("parentThreadId").and_then(Value::as_str),+ Some("thread-orchestration-e2e"),+ "lineage is recorded: {started}"+ );+ let phase_states = run+ .get("phaseStates")+ .and_then(Value::as_object)+ .unwrap_or_else(|| panic!("the run seeds a phase ledger: {started}"));+ for phase in ["decompose", "research", "cross_check", "synthesize"] {+ assert_eq!(+ phase_states+ .get(phase)+ .and_then(|state| state.get("status"))+ .and_then(Value::as_str),+ Some("pending"),+ "every phase starts pending: {started}"+ );+ }++ let stopped = h+ .ok(3002, "openhuman.workflow_run_stop", json!({ "id": run_id }))+ .await;+ let stopped_run = stopped+ .get("workflowRun")+ .filter(|run| !run.is_null())+ .unwrap_or_else(|| panic!("stopping a known run returns it: {stopped}"));+ assert_eq!(str_at(stopped_run, "/id"), run_id);+ let stopped_status = str_at(stopped_run, "/status").to_string();+ assert_ne!(+ stopped_status, "running",+ "after a stop the run is no longer running: {stopped}"+ );++ // The stop is persisted, not just returned.+ let fetched = h+ .ok(3003, "openhuman.workflow_run_get", json!({ "id": run_id }))+ .await;+ let fetched_run = fetched+ .get("workflowRun")+ .filter(|run| !run.is_null())+ .unwrap_or_else(|| panic!("the run is readable after the stop: {fetched}"));+ assert_ne!(+ str_at(fetched_run, "/status"),+ "running",+ "the interrupt was written to the ledger: {fetched}"+ );++ // Resume is refused only for a COMPLETED run. Offline the loop cannot have+ // completed, so this run must be resumable — assert that premise rather+ // than assume it.+ assert_ne!(+ str_at(fetched_run, "/status"),+ "completed",+ "an offline run cannot complete; the resume below assumes it did not: {fetched}"+ );++ let resumed = h+ .ok(3004, "openhuman.workflow_run_resume", json!({ "id": run_id }))+ .await;+ let resumed_run = resumed+ .get("workflowRun")+ .unwrap_or_else(|| panic!("resume returns the run: {resumed}"));+ assert_eq!(str_at(resumed_run, "/id"), run_id, "the SAME run resumed");+ assert_eq!(+ resumed_run.get("status").and_then(Value::as_str),+ Some("running"),+ "resume puts the run back to Running: {resumed}"+ );+ assert_eq!(+ resumed_run+ .get("phaseStates")+ .and_then(Value::as_object)+ .map(|states| states.len()),+ Some(4),+ "resume carries the phase ledger forward rather than reseeding it: {resumed}"+ );+ assert_eq!(+ resumed_run.get("definitionId").and_then(Value::as_str),+ Some(BUILTIN_WORKFLOW_ID)+ );++ // Leave no live engine loop behind for the next case.+ h.ok(3005, "openhuman.workflow_run_stop", json!({ "id": run_id }))+ .await;++ h.join.abort();+}++/// The two controllers disagree on purpose about an unknown id: `stop` is+/// idempotent (nothing to stop is not a failure) while `resume` is not (there+/// is nothing to resume, and the caller asked for something specific).+#[tokio::test]+async fn workflow_run_stop_is_idempotent_where_resume_is_not() {+ let _lock = env_lock();+ let h = setup().await;++ let stopped = h+ .ok(+ 3101,+ "openhuman.workflow_run_stop",+ json!({ "id": "wfrun-does-not-exist" }),+ )+ .await;+ assert!(+ stopped+ .get("workflowRun")+ .is_some_and(Value::is_null),+ "stopping an unknown run yields a null run, not an error: {stopped}"+ );++ let resume_error = h+ .err(+ 3102,+ "openhuman.workflow_run_resume",+ json!({ "id": "wfrun-does-not-exist" }),+ )+ .await;+ assert!(+ resume_error.contains("wfrun-does-not-exist") && resume_error.contains("unknown"),+ "resume names the run it could not find: {resume_error}"+ );++ for (id, method) in [+ (3103, "openhuman.workflow_run_stop"),+ (3104, "openhuman.workflow_run_resume"),+ ] {+ let missing = h.err(id, method, json!({})).await;+ assert!(+ missing.contains("id"),+ "{method} names its required param: {missing}"+ );+ }++ let unknown_definition = h+ .err(+ 3105,+ "openhuman.workflow_run_start",+ json!({ "definitionId": "no-such-definition" }),+ )+ .await;+ assert!(+ unknown_definition.contains("no-such-definition"),+ "start names the definition it could not resolve: {unknown_definition}"+ );++ h.join.abort();+}++// ── agent_work_control ──────────────────────────────────────────────────────++/// `agent_work_control` is the command center's only write. Its guards run in a+/// deliberate order — the message requirement is checked BEFORE the run is+/// looked up — so a `continue` with no message is rejected on its own terms+/// rather than as a missing run.+#[tokio::test]+async fn agent_work_control_validates_verb_and_message_before_touching_the_ledger() {+ let _lock = env_lock();+ let h = setup().await;++ let unknown_verb = h+ .err(+ 3201,+ "openhuman.agent_work_control",+ json!({ "runId": "run-1", "action": "detonate" }),+ )+ .await;+ assert!(+ unknown_verb.contains("detonate"),+ "an unknown verb is quoted back: {unknown_verb}"+ );++ // `continue` and `follow_up` both require a message. The run does not+ // exist, so a "run not found" here would prove the guard ran too late.+ for (id, action) in [(3202, "continue"), (3203, "follow_up")] {+ let no_message = h+ .err(+ id,+ "openhuman.agent_work_control",+ json!({ "runId": "run-does-not-exist", "action": action }),+ )+ .await;+ assert!(+ no_message.to_lowercase().contains("message"),+ "{action} without a message is rejected for the message, not the run: {no_message}"+ );+ assert!(+ !no_message.contains("run-does-not-exist"),+ "the message guard runs before the ledger lookup: {no_message}"+ );++ // A whitespace-only message is not a message.+ let blank_message = h+ .err(+ id + 10,+ "openhuman.agent_work_control",+ json!({ "runId": "run-does-not-exist", "action": action, "message": " " }),+ )+ .await;+ assert!(+ blank_message.to_lowercase().contains("message"),+ "{action} treats a blank message as absent: {blank_message}"+ );+ }++ // `stop` needs no message, so it reaches the ledger and fails there.+ let unknown_run = h+ .err(+ 3204,+ "openhuman.agent_work_control",+ json!({ "runId": "run-does-not-exist", "action": "stop" }),+ )+ .await;+ assert!(+ unknown_run.contains("run-does-not-exist"),+ "a verb needing no message reaches the lookup and names the run: {unknown_run}"+ );++ for (id, key) in [(3205, "runId"), (3206, "action")] {+ let params = if key == "runId" {+ json!({ "action": "stop" })+ } else {+ json!({ "runId": "run-1" })+ };+ let missing = h.err(id, "openhuman.agent_work_control", params).await;+ assert!(+ missing.contains(key),+ "the required `{key}` param is named: {missing}"+ );+ }++ // The read side agrees there is nothing to control.+ let view = h.ok(3207, "openhuman.agent_work_list", json!({})).await;+ assert_eq!(+ view.get("total").and_then(Value::as_u64),+ Some(0),+ "a fresh workspace has no background agent runs: {view}"+ );++ h.join.abort();+}++// ── agent_team: list / close ────────────────────────────────────────────────++/// The team lifecycle across the two uncovered controllers: a created team is+/// `active` and listed; closing it flips the status, stamps `closedAt` and+/// records the summary; and the status filter must then move it from one+/// bucket to the other.+#[tokio::test]+async fn agent_team_close_flips_the_status_the_list_filter_selects_on() {+ let _lock = env_lock();+ let h = setup().await;++ let created = h+ .ok(+ 3301,+ "openhuman.agent_team_create",+ json!({+ "leadAgentId": "planner",+ "parentThreadId": "thread-team-e2e",+ "summary": "ship the e2e wave",+ "members": [+ { "name": "Ada", "agentId": "researcher" },+ { "name": "Grace" }+ ],+ }),+ )+ .await;+ let team_id = str_at(&created, "/team/id").to_string();+ assert_eq!(+ created.pointer("/team/status").and_then(Value::as_str),+ Some("active"),+ "a new team is active: {created}"+ );+ assert_eq!(+ created.pointer("/team/leadAgentId").and_then(Value::as_str),+ Some("planner")+ );+ assert_eq!(+ created.pointer("/members").and_then(Value::as_array).map(Vec::len),+ Some(2),+ "both seeded members are created: {created}"+ );+ assert!(+ created.pointer("/team/closedAt").is_none_or(Value::is_null),+ "an active team has no close stamp: {created}"+ );++ let listed = h.ok(3302, "openhuman.agent_team_list", json!({})).await;+ assert_eq!(+ listed.get("count").and_then(Value::as_u64),+ Some(1),+ "the new team is listed: {listed}"+ );+ assert_eq!(str_at(&listed, "/teams/0/id"), team_id);++ let by_thread = h+ .ok(+ 3303,+ "openhuman.agent_team_list",+ json!({ "parentThreadId": "thread-team-e2e" }),+ )+ .await;+ assert_eq!(by_thread.get("count").and_then(Value::as_u64), Some(1));++ let other_thread = h+ .ok(+ 3304,+ "openhuman.agent_team_list",+ json!({ "parentThreadId": "some-other-thread" }),+ )+ .await;+ assert_eq!(+ other_thread.get("count").and_then(Value::as_u64),+ Some(0),+ "the parent-thread filter actually filters: {other_thread}"+ );++ let active_only = h+ .ok(+ 3305,+ "openhuman.agent_team_list",+ json!({ "status": "active" }),+ )+ .await;+ assert_eq!(active_only.get("count").and_then(Value::as_u64), Some(1));++ let closed = h+ .ok(+ 3306,+ "openhuman.agent_team_close",+ json!({ "teamId": team_id, "summary": "wave landed" }),+ )+ .await;+ assert_eq!(+ closed.pointer("/team/status").and_then(Value::as_str),+ Some("closed"),+ "close flips the status: {closed}"+ );+ assert_eq!(+ closed.pointer("/team/summary").and_then(Value::as_str),+ Some("wave landed"),+ "the closing summary replaces the opening one: {closed}"+ );+ assert!(+ closed+ .pointer("/team/closedAt")+ .and_then(Value::as_str)+ .is_some(),+ "closing stamps a time: {closed}"+ );++ let after_active = h+ .ok(+ 3307,+ "openhuman.agent_team_list",+ json!({ "status": "active" }),+ )+ .await;+ assert_eq!(+ after_active.get("count").and_then(Value::as_u64),+ Some(0),+ "the closed team left the active bucket: {after_active}"+ );++ let after_closed = h+ .ok(+ 3308,+ "openhuman.agent_team_list",+ json!({ "status": "closed" }),+ )+ .await;+ assert_eq!(+ after_closed.get("count").and_then(Value::as_u64),+ Some(1),+ "and entered the closed one: {after_closed}"+ );+ assert_eq!(str_at(&after_closed, "/teams/0/id"), team_id);++ h.join.abort();+}++/// Both controllers refuse malformed input rather than degrading to a default:+/// a wrongly typed pagination field must not silently become "all teams".+#[tokio::test]+async fn agent_team_list_and_close_reject_malformed_input() {+ let _lock = env_lock();+ let h = setup().await;++ let bad_limit = h+ .err(+ 3401,+ "openhuman.agent_team_list",+ json!({ "limit": "not-a-number" }),+ )+ .await;+ assert!(+ bad_limit.contains("limit") && bad_limit.contains("agent_team.list"),+ "a mistyped filter is rejected, not ignored: {bad_limit}"+ );+ assert!(+ bad_limit.contains("expected unsigned integer"),+ "and the rejection says what the field should have been: {bad_limit}"+ );++ let unknown_team = h+ .err(+ 3402,+ "openhuman.agent_team_close",+ json!({ "teamId": "team-does-not-exist" }),+ )+ .await;+ assert!(+ unknown_team.contains("team-does-not-exist"),+ "close names the team it could not find: {unknown_team}"+ );++ let no_team_id = h.err(3403, "openhuman.agent_team_close", json!({})).await;+ assert!(+ no_team_id.contains("teamId"),+ "the required `teamId` param is named: {no_team_id}"+ );++ let blank_team_id = h+ .err(+ 3404,+ "openhuman.agent_team_close",+ json!({ "teamId": " " }),+ )+ .await;+ assert!(+ blank_team_id.contains("teamId"),+ "a blank teamId is treated as absent: {blank_team_id}"+ );++ h.join.abort();+}++// ── subagent: cancel / steer ────────────────────────────────────────────────++/// The background-tasks drawer's Cancel and steer controls. Both answer+/// **structurally** for a task that is not running rather than erroring — the+/// drawer's row may be stale, and a stale row must not raise. `steer` goes+/// further and says *why* it did nothing.+#[tokio::test]+async fn subagent_cancel_and_steer_report_structurally_for_an_unknown_task() {+ let _lock = env_lock();+ let h = setup().await;++ let cancelled = h+ .ok(+ 3501,+ "openhuman.subagent_cancel",+ json!({ "taskId": "sub-not-running" }),+ )+ .await;+ assert_eq!(+ cancelled.get("cancelled").and_then(Value::as_bool),+ Some(false),+ "nothing was running, and that is an answer not a failure: {cancelled}"+ );+ assert_eq!(+ cancelled.get("taskId").and_then(Value::as_str),+ Some("sub-not-running"),+ "the answer echoes the task asked about: {cancelled}"+ );++ // A reason is accepted on the cancel path and must not change the verdict.+ let with_reason = h+ .ok(+ 3502,+ "openhuman.subagent_cancel",+ json!({ "taskId": "sub-not-running", "reason": "changed my mind" }),+ )+ .await;+ assert_eq!(+ with_reason.get("cancelled").and_then(Value::as_bool),+ Some(false)+ );++ let steered = h+ .ok(+ 3503,+ "openhuman.subagent_steer",+ json!({ "taskId": "sub-not-running", "message": "focus on the failing test" }),+ )+ .await;+ assert_eq!(+ steered.get("steered").and_then(Value::as_bool),+ Some(false),+ "an unknown task cannot be steered: {steered}"+ );+ assert_eq!(+ steered.get("reason").and_then(Value::as_str),+ Some("unknown"),+ "and the caller is told which of the failure modes it hit: {steered}"+ );+ assert_eq!(+ steered.get("mode").and_then(Value::as_str),+ Some("steer"),+ "steer is the default queue mode: {steered}"+ );++ let collect = h+ .ok(+ 3504,+ "openhuman.subagent_steer",+ json!({+ "taskId": "sub-not-running",+ "message": "note this for later",+ "mode": "collect",+ }),+ )+ .await;+ assert_eq!(+ collect.get("mode").and_then(Value::as_str),+ Some("collect"),+ "an explicit queue mode is honoured and echoed: {collect}"+ );++ // An unrecognised mode falls back to steer rather than erroring.+ let bogus_mode = h+ .ok(+ 3505,+ "openhuman.subagent_steer",+ json!({ "taskId": "sub-not-running", "message": "hi", "mode": "teleport" }),+ )+ .await;+ assert_eq!(+ bogus_mode.get("mode").and_then(Value::as_str),+ Some("steer"),+ "an unknown mode degrades to the default: {bogus_mode}"+ );++ h.join.abort();+}++/// `taskId` is **trimmed** before it reaches the registry, so a whitespace-+/// padded id must be rejected up front — it would otherwise pass a naive+/// non-empty check and then silently never match a registry key.+#[tokio::test]+async fn subagent_controls_reject_blank_and_absent_required_params() {+ let _lock = env_lock();+ let h = setup().await;++ // Each method gets its own param shape: the RPC layer rejects an unknown+ // param, and `subagent_cancel` declares no `message`.+ for (id, method, extra) in [+ (3601, "openhuman.subagent_cancel", json!({})),+ (3602, "openhuman.subagent_steer", json!({ "message": "hi" })),+ ] {+ let mut blank = extra.as_object().cloned().expect("params object");+ blank.insert("taskId".to_string(), json!(" "));+ let blank = h.err(id, method, Value::Object(blank)).await;+ assert!(+ blank.contains("taskId"),+ "{method} rejects a whitespace-only taskId: {blank}"+ );++ let absent = h.err(id + 10, method, extra).await;+ assert!(+ absent.contains("taskId"),+ "{method} names its required taskId: {absent}"+ );+ }++ let no_message = h+ .err(+ 3603,+ "openhuman.subagent_steer",+ json!({ "taskId": "sub-1" }),+ )+ .await;+ assert!(+ no_message.contains("message"),+ "steer names its required message: {no_message}"+ );++ let blank_message = h+ .err(+ 3604,+ "openhuman.subagent_steer",+ json!({ "taskId": "sub-1", "message": " " }),+ )+ .await;+ assert!(+ blank_message.contains("message"),+ "a blank steer message is treated as absent: {blank_message}"+ );++ h.join.abort();+}++// ── agent_experience ────────────────────────────────────────────────────────++fn experience(id: &str, summary: &str, lesson: &str, tools: &[&str], tags: &[&str]) -> Value {+ let now = 1_760_000_000_000i64;+ json!({+ "id": id,+ "created_at_ms": now,+ "updated_at_ms": now,+ "source": "manual",+ "agent_id": "planner",+ "entrypoint": "chat",+ "task_fingerprint": format!("fp-{id}"),+ "task_summary": summary,+ "tools_used": tools,+ "tool_sequence": tools,+ "outcome": "success",+ "error_class": null,+ "lesson": lesson,+ "reuse_hint": "reuse when the same tools are available",+ "avoid_hint": null,+ "confidence": 0.9,+ "tags": tags,+ "payload_hash": null,+ "dismissed": false+ })+}++/// The procedural-experience store end to end: capture persists, list reads+/// back, retrieve ranks against a task query, and dismiss takes a record out of+/// retrieval **without** deleting it.+#[tokio::test]+async fn agent_experience_capture_list_retrieve_and_dismiss_round_trip() {+ let _lock = env_lock();+ ensure_memory_seams();+ let h = setup().await;++ let before: Vec<String> = h+ .ok(3701, "openhuman.agent_experience_list", json!({}))+ .await+ .as_array()+ .expect("list returns an array")+ .iter()+ .map(|entry| str_at(entry, "/id").to_string())+ .collect();+ assert!(+ !before.iter().any(|id| id.starts_with("w1exp-")),+ "this suite's ids are unique to it, so none may pre-exist: {before:?}"+ );++ let stored = h+ .ok(+ 3702,+ "openhuman.agent_experience_capture",+ json!({+ "experience": experience(+ "w1exp-deploy",+ "deploy the staging build",+ "run the migration before restarting the service",+ &["shell_exec", "http_request"],+ &["deploy", "staging"],+ ),+ }),+ )+ .await;+ assert_eq!(+ stored.get("id").and_then(Value::as_str),+ Some("w1exp-deploy"),+ "capture returns the stored record: {stored}"+ );+ assert_eq!(+ stored.get("dismissed").and_then(Value::as_bool),+ Some(false)+ );++ h.ok(+ 3703,+ "openhuman.agent_experience_capture",+ json!({+ "experience": experience(+ "w1exp-unrelated",+ "reconcile the invoice ledger",+ "always reconcile before closing the month",+ &["read_file"],+ &["finance"],+ ),+ }),+ )+ .await;++ let listed = h+ .ok(3704, "openhuman.agent_experience_list", json!({}))+ .await;+ let mine: Vec<&str> = listed+ .as_array()+ .expect("list returns an array")+ .iter()+ .map(|entry| str_at(entry, "/id"))+ .filter(|id| id.starts_with("w1exp-"))+ .collect();+ assert_eq!(mine.len(), 2, "both captures are readable: {listed}");+ assert!(mine.contains(&"w1exp-deploy") && mine.contains(&"w1exp-unrelated"));++ // Retrieval must RANK, not just return everything: the deploy query has to+ // put the deploy experience first.+ let hits = h+ .ok(+ 3705,+ "openhuman.agent_experience_retrieve",+ json!({+ "query": "deploy the staging build",+ "tools": ["shell_exec"],+ "tags": ["deploy"],+ "max_hits": 5,+ }),+ )+ .await;+ let hits = hits.as_array().expect("retrieve returns an array").clone();+ let rank = |id: &str| {+ hits.iter()+ .position(|hit| hit.pointer("/experience/id").and_then(Value::as_str) == Some(id))+ };+ let deploy_rank = rank("w1exp-deploy")+ .unwrap_or_else(|| panic!("the captured experience is recalled: {hits:?}"));+ if let Some(unrelated_rank) = rank("w1exp-unrelated") {+ assert!(+ deploy_rank < unrelated_rank,+ "retrieval RANKS: the deploy query puts the deploy experience above \+ the finance one ({deploy_rank} vs {unrelated_rank}): {hits:?}"+ );+ }+ let hit = &hits[deploy_rank];+ assert!(+ hit.get("score")+ .and_then(Value::as_f64)+ .is_some_and(|score| score > 0.0),+ "a hit carries a positive score: {hit:?}"+ );+ assert!(+ hit.get("match_reasons")+ .and_then(Value::as_array)+ .is_some_and(|reasons| !reasons.is_empty()),+ "and says why it matched: {hit:?}"+ );++ // `max_hits` is a cap, not a hint.+ let capped = h+ .ok(+ 3706,+ "openhuman.agent_experience_retrieve",+ json!({ "query": "deploy the staging build", "max_hits": 1 }),+ )+ .await;+ assert!(+ capped.as_array().map(Vec::len).unwrap_or(0) <= 1,+ "retrieve honours max_hits: {capped}"+ );++ let dismissed = h+ .ok(+ 3707,+ "openhuman.agent_experience_dismiss",+ json!({ "id": "w1exp-deploy" }),+ )+ .await;+ assert_eq!(+ dismissed.get("id").and_then(Value::as_str),+ Some("w1exp-deploy")+ );+ assert_eq!(+ dismissed.get("dismissed").and_then(Value::as_bool),+ Some(true),+ "an existing experience is marked dismissed: {dismissed}"+ );++ let after = h+ .ok(+ 3708,+ "openhuman.agent_experience_retrieve",+ json!({ "query": "deploy the staging build", "max_hits": 5 }),+ )+ .await;+ assert!(+ !after+ .as_array()+ .expect("retrieve array")+ .iter()+ .any(|hit| hit.pointer("/experience/id").and_then(Value::as_str) == Some("w1exp-deploy")),+ "a dismissed experience is out of retrieval: {after}"+ );++ // Dismissing something absent is reported, not raised.+ let absent = h+ .ok(+ 3709,+ "openhuman.agent_experience_dismiss",+ json!({ "id": "w1exp-does-not-exist" }),+ )+ .await;+ assert_eq!(+ absent.get("dismissed").and_then(Value::as_bool),+ Some(false),+ "dismissing an unknown id reports false rather than erroring: {absent}"+ );++ h.join.abort();+}++/// Every `agent_experience` controller deserializes its params as a typed+/// struct, so a missing or wrongly shaped field is rejected at the boundary+/// instead of being defaulted into a silently wrong record.+#[tokio::test]+async fn agent_experience_controllers_reject_malformed_params() {+ let _lock = env_lock();+ ensure_memory_seams();+ let h = setup().await;++ let no_experience = h+ .err(3801, "openhuman.agent_experience_capture", json!({}))+ .await;+ assert!(+ no_experience.contains("experience"),+ "capture names the field it needs: {no_experience}"+ );++ // A record missing a required field must not be defaulted into existence.+ let incomplete = h+ .err(+ 3802,+ "openhuman.agent_experience_capture",+ json!({ "experience": { "id": "w1exp-partial", "task_summary": "half a record" } }),+ )+ .await;+ assert!(+ !incomplete.is_empty(),+ "an incomplete experience is refused: {incomplete}"+ );++ let no_query = h+ .err(3803, "openhuman.agent_experience_retrieve", json!({}))+ .await;+ assert!(+ no_query.contains("query"),+ "retrieve names its required query: {no_query}"+ );++ let no_id = h+ .err(3804, "openhuman.agent_experience_dismiss", json!({}))+ .await;+ assert!(+ no_id.contains("id"),+ "dismiss names its required id: {no_id}"+ );++ // An unknown profile partition is an error, not an empty result — a typo+ // must not read as "this profile has no experiences".+ let unknown_profile = h+ .err(+ 3805,+ "openhuman.agent_experience_list",+ json!({ "profile_id": "profile-does-not-exist" }),+ )+ .await;+ assert!(+ unknown_profile.contains("profile-does-not-exist"),+ "an unknown profile is named rather than silently empty: {unknown_profile}"+ );++ h.join.abort();+}diff --git a/tests/raw_coverage/automation_scheduling_e2e.rs b/tests/raw_coverage/automation_scheduling_e2e.rsnew file mode 100644index 0000000000..dea6f75b5c--- /dev/null+++ b/tests/raw_coverage/automation_scheduling_e2e.rs@@ -0,0 +1,1021 @@+//! JSON-RPC E2E coverage for the automation/scheduling controllers that no+//! e2e target reached: `cron_remove` / `cron_run` / `cron_runs`,+//! `task_sources_sync` / `task_sources_list_databases`, the whole `hooks`+//! namespace, and `harness_init_run`.+//!+//! Every case boots the real Axum JSON-RPC router over HTTP against an+//! isolated `HOME` and asserts on the **content** of the response. Nothing+//! here reaches the network: `api_url` points at a closed port, and the+//! provisioning switches harness-init would act on are asserted OFF in the+//! parsed config before a single step runs.+//!+//! Aggregated into `tests/raw_coverage_all.rs` by `build.rs`. Run with:+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" automation_scheduling_e2e`++use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;++/// Seeded only if this suite is the first in the aggregated binary to+/// initialise the token; the bearer actually sent is always read back from+/// `get_rpc_token()`, because `RPC_TOKEN` is a process-global `OnceLock` and+/// whichever aggregated suite calls `init_rpc_token` first wins it for all.+const TEST_RPC_TOKEN: &str = "automation-scheduling-e2e-token";++static AUTH_INIT: OnceLock<()> = OnceLock::new();++/// The crate-wide env lock, not a private one. Every aggregated suite in+/// `raw_coverage_all` shares one process, so libtest runs them concurrently+/// and a lock local to this file would isolate nothing.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++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),+ }+ }+}++fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++/// Initialise the process RPC token (idempotent) and return the bearer the+/// router will actually accept.+fn ensure_rpc_auth() -> &'static str {+ AUTH_INIT.get_or_init(|| {+ if get_rpc_token().is_none() {+ std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);+ }+ let token_dir = std::env::temp_dir().join("openhuman-automation-scheduling-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+ get_rpc_token().expect("rpc token initialized")+}++async fn serve_rpc() -> (+ SocketAddr,+ &'static str,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ let token = ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let join =+ tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });+ (addr, token, join)+}++/// The config every case here runs against.+///+/// `[node] enabled = false` and `[runtime_python] enabled = false` are load-+/// bearing: `harness_init_run` would otherwise **download** a managed Node.js+/// and CPython. `Config` does not `deny_unknown_fields`, so a mistyped table+/// name would be silently ignored and the download would happen anyway —+/// [`assert_provisioning_is_disabled`] is the guard against exactly that.+const TEST_CONFIG_TOML: &str = r#"api_url = "http://127.0.0.1:9"+default_model = "automation-e2e-model"+default_temperature = 0.2+chat_onboarding_completed = true++[secrets]+encrypt = false++[local_ai]+enabled = false++[node]+enabled = false++[runtime_python]+enabled = false++[memory]+provider = "none"+embedding_provider = "none"+embedding_model = "none"+embedding_dimensions = 0++[memory_tree]+embedding_strict = false+spacy_enabled = false+"#;++/// Prove the disable switches actually bound to the fields harness-init reads,+/// rather than being silently dropped as unknown keys.+fn assert_provisioning_is_disabled() -> openhuman_core::openhuman::config::Config {+ let parsed: openhuman_core::openhuman::config::Config =+ toml::from_str(TEST_CONFIG_TOML).expect("test config must match the Config schema");+ assert!(+ !parsed.node.enabled,+ "[node] enabled=false must bind — otherwise harness_init downloads Node.js"+ );+ assert!(+ !parsed.runtime_python.enabled,+ "[runtime_python] enabled=false must bind — otherwise harness_init downloads CPython"+ );+ assert!(+ !parsed.memory_tree.spacy_enabled,+ "[memory_tree] spacy_enabled=false must bind — otherwise harness_init provisions spaCy"+ );+ parsed+}++fn write_min_config(openhuman_dir: &Path) {+ let write = |dir: &Path| {+ std::fs::create_dir_all(dir).expect("create config dir");+ std::fs::write(dir.join("config.toml"), TEST_CONFIG_TOML).expect("write config.toml");+ };+ write(openhuman_dir);+ // Runtime config resolution is user-scoped before login, so the pre-login+ // `users/local` layer needs the same file or the RPC handlers load defaults.+ write(&openhuman_dir.join("users").join("local"));+ assert_provisioning_is_disabled();+}++struct Harness {+ tmp: TempDir,+ _guards: Vec<EnvVarGuard>,+ rpc_base: String,+ token: &'static str,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++impl Harness {+ fn home(&self) -> &Path {+ self.tmp.path()+ }++ async fn rpc(&self, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(120))+ .build()+ .expect("build rpc client");+ let url = format!("{}/rpc", self.rpc_base);+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", self.token))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": method,+ "params": params,+ }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+ }++ async fn ok(&self, id: i64, method: &str, params: Value) -> Value {+ let response = self.rpc(id, method, params).await;+ if let Some(error) = response.get("error") {+ panic!("{method}: unexpected JSON-RPC error: {error}");+ }+ let result = response+ .get("result")+ .unwrap_or_else(|| panic!("{method}: missing result: {response}"));+ match result.get("result") {+ Some(inner) if result.get("logs").is_some() => inner.clone(),+ _ => result.clone(),+ }+ }++ async fn err(&self, id: i64, method: &str, params: Value) -> String {+ let response = self.rpc(id, method, params).await;+ let error = response+ .get("error")+ .unwrap_or_else(|| panic!("{method}: expected a JSON-RPC error, got: {response}"));+ error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{method}: error carries no message: {error}"))+ .to_string()+ }+}++async fn setup() -> Harness {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path().to_path_buf();+ write_min_config(&home.join(".openhuman"));++ // A cron shell job spawns `sh` with `current_dir(config.action_dir)`, and a+ // hook's project layer is read from `<action_dir>/.openhuman/hooks.json`.+ // Left at its default that is `~/OpenHuman/projects` — the developer's real+ // directory, which is both a leak and (when absent) an ENOENT that surfaces+ // only as "spawn error: No such file or directory".+ let action_dir = home.join("actions");+ std::fs::create_dir_all(&action_dir).expect("create action dir");++ let guards = vec![+ EnvVarGuard::set_to_path("HOME", &home),+ EnvVarGuard::set_to_path("OPENHUMAN_ACTION_DIR", &action_dir),+ EnvVarGuard::unset("OPENHUMAN_WORKSPACE"),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::unset("COMPOSIO_API_KEY"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let (addr, token, join) = serve_rpc().await;+ Harness {+ tmp,+ _guards: guards,+ rpc_base: format!("http://{addr}"),+ token,+ join,+ }+}++fn str_at<'a>(value: &'a Value, pointer: &str) -> &'a str {+ value+ .pointer(pointer)+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("expected a string at {pointer} in {value}"))+}++// ── cron ────────────────────────────────────────────────────────────────────++/// The half of the cron surface no e2e target reached: run-now, its run+/// history, and removal. A shell job is used because it is the only job type+/// that completes without a model.+#[tokio::test]+async fn cron_run_records_history_and_remove_is_not_idempotent() {+ let _lock = env_lock();+ let h = setup().await;++ let job = h+ .ok(+ 2001,+ "openhuman.cron_add",+ json!({+ "name": "e2e echo",+ "schedule": { "kind": "every", "every_ms": 3_600_000u64 },+ "job_type": "shell",+ "command": "echo automation-e2e-marker",+ }),+ )+ .await;+ let job_id = str_at(&job, "/id").to_string();+ assert_eq!(job.get("name").and_then(Value::as_str), Some("e2e echo"));++ // `cron_run` enqueues and returns immediately — the run itself is a+ // background task, so the RPC's own answer is the queue acknowledgement.+ let queued = h+ .ok(2002, "openhuman.cron_run", json!({ "job_id": job_id }))+ .await;+ assert_eq!(+ queued.get("job_id").and_then(Value::as_str),+ Some(job_id.as_str()),+ "cron_run echoes the job it enqueued: {queued}"+ );+ assert_eq!(+ queued.get("status").and_then(Value::as_str),+ Some("queued"),+ "cron_run reports the enqueue, not the outcome: {queued}"+ );++ // The queued placeholder is written synchronously, so history is non-empty+ // the instant the RPC returns — that is the property the frontend poller+ // depends on.+ let immediate = h+ .ok(2003, "openhuman.cron_runs", json!({ "job_id": job_id }))+ .await;+ assert!(+ !immediate+ .as_array()+ .expect("cron_runs returns an array")+ .is_empty(),+ "the queued placeholder is recorded before cron_run returns: {immediate}"+ );++ // Wait for the background execution to replace the placeholder with a real+ // result. `echo` is immediate; the generous budget is for a loaded machine.+ let mut settled: Option<Value> = None;+ for _ in 0..120 {+ let runs = h+ .ok(2004, "openhuman.cron_runs", json!({ "job_id": job_id }))+ .await;+ let runs = runs.as_array().expect("cron_runs array").clone();+ if let Some(run) = runs+ .iter()+ .find(|run| run.get("status").and_then(Value::as_str) != Some("queued"))+ {+ settled = Some(run.clone());+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ let settled = settled.expect("the shell job must finish and record a terminal run");+ assert_eq!(+ settled.get("status").and_then(Value::as_str),+ Some("ok"),+ "`echo` succeeds: {settled}"+ );+ assert!(+ settled+ .get("output")+ .and_then(Value::as_str)+ .is_some_and(|out| out.contains("automation-e2e-marker")),+ "the run record captures the command's own output: {settled}"+ );+ assert_eq!(+ settled.get("job_id").and_then(Value::as_str),+ Some(job_id.as_str())+ );++ // `limit` is honoured rather than ignored.+ let capped = h+ .ok(+ 2005,+ "openhuman.cron_runs",+ json!({ "job_id": job_id, "limit": 1 }),+ )+ .await;+ assert_eq!(+ capped.as_array().map(Vec::len),+ Some(1),+ "cron_runs honours limit: {capped}"+ );++ let removed = h+ .ok(2006, "openhuman.cron_remove", json!({ "job_id": job_id }))+ .await;+ assert_eq!(+ removed.get("job_id").and_then(Value::as_str),+ Some(job_id.as_str())+ );+ assert_eq!(+ removed.get("removed").and_then(Value::as_bool),+ Some(true),+ "removal is reported explicitly: {removed}"+ );++ let listed = h.ok(2007, "openhuman.cron_list", json!({})).await;+ assert!(+ !listed+ .as_array()+ .expect("cron_list array")+ .iter()+ .any(|entry| entry.get("id").and_then(Value::as_str) == Some(job_id.as_str())),+ "the removed job is gone from the list: {listed}"+ );++ // A second removal is an ERROR, not a silent success — the caller is told+ // its id no longer names anything.+ let again = h+ .err(2008, "openhuman.cron_remove", json!({ "job_id": job_id }))+ .await;+ assert!(+ again.contains(&job_id) && again.to_lowercase().contains("not found"),+ "removing an absent job names it: {again}"+ );++ h.join.abort();+}++/// Every cron controller validates its `job_id` before touching the store, and+/// a whitespace-only id must not slip through as a valid one.+#[tokio::test]+async fn cron_controllers_reject_absent_and_blank_job_ids() {+ let _lock = env_lock();+ let h = setup().await;++ for (id, method) in [+ (2101, "openhuman.cron_remove"),+ (2102, "openhuman.cron_run"),+ (2103, "openhuman.cron_runs"),+ ] {+ let blank = h.err(id, method, json!({ "job_id": " " })).await;+ assert!(+ blank.contains("job_id"),+ "{method} rejects a blank job_id by name: {blank}"+ );++ let absent = h.err(id + 10, method, json!({})).await;+ assert!(+ absent.contains("job_id"),+ "{method} names its required param: {absent}"+ );+ }++ // The three diverge on an id that does not name a job, and the divergence+ // is worth pinning. `remove` and `run` both go through `cron::get_job` /+ // `remove_job` and raise; `runs` queries the run table by id and cannot+ // tell "no such job" from "job with no runs", so a typo reads as an empty+ // history. See `~/tinyhuman/bugs/e2e-wave-cron-run-schema-declares-an-outcome-it-never-returns.md`.+ for (id, method) in [+ (2121, "openhuman.cron_remove"),+ (2122, "openhuman.cron_run"),+ ] {+ let unknown = h+ .err(id, method, json!({ "job_id": "no-such-job" }))+ .await;+ assert!(+ unknown.contains("no-such-job"),+ "{method} names the unknown job: {unknown}"+ );+ }++ let unknown_history = h+ .ok(+ 2123,+ "openhuman.cron_runs",+ json!({ "job_id": "no-such-job" }),+ )+ .await;+ assert_eq!(+ unknown_history.as_array().map(Vec::len),+ Some(0),+ "cron_runs cannot distinguish an unknown job from one with no runs: {unknown_history}"+ );++ h.join.abort();+}++// ── task_sources ────────────────────────────────────────────────────────────++/// `task_sources_sync` fans out over every ENABLED source and reports one+/// outcome each, so an empty workspace yields an empty list rather than an+/// error.+///+/// With a source configured the outcome carries the fetch failure instead of+/// raising it — one broken source must not abort the sweep. That failure is+/// currently unconditional: see+/// `~/tinyhuman/bugs/e2e-wave-task_sources-fetch-pipeline-unavailable.md`.+#[tokio::test]+async fn task_sources_sync_reports_one_outcome_per_enabled_source() {+ let _lock = env_lock();+ let h = setup().await;++ let empty = h.ok(2201, "openhuman.task_sources_sync", json!({})).await;+ assert_eq!(+ empty.as_array().map(Vec::len),+ Some(0),+ "no sources configured means no outcomes, not an error: {empty}"+ );++ let source = h+ .ok(+ 2202,+ "openhuman.task_sources_add",+ json!({+ "provider": "github",+ "name": "e2e source",+ "filter": {+ "provider": "github",+ "repo": "tinyhumansai/openhuman",+ "labels": ["bug"],+ },+ }),+ )+ .await;+ let source_id = str_at(&source, "/id").to_string();+ assert_eq!(+ source.get("enabled").and_then(Value::as_bool),+ Some(true),+ "a new source is enabled, so sync must pick it up: {source}"+ );++ let synced = h.ok(2203, "openhuman.task_sources_sync", json!({})).await;+ let outcomes = synced.as_array().expect("sync returns an outcomes array");+ assert_eq!(outcomes.len(), 1, "one outcome per enabled source: {synced}");+ let outcome = &outcomes[0];+ assert_eq!(+ outcome.get("sourceId").and_then(Value::as_str),+ Some(source_id.as_str()),+ "the outcome names the source it swept: {outcome}"+ );+ assert_eq!(+ outcome.get("provider").and_then(Value::as_str),+ Some("github")+ );+ assert_eq!(outcome.get("fetched").and_then(Value::as_u64), Some(0));+ assert_eq!(outcome.get("routed").and_then(Value::as_u64), Some(0));+ let error = outcome+ .get("error")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("a failing fetch is carried on the outcome: {outcome}"));+ assert!(+ error.contains("unavailable"),+ "the fetch failure is reported per-source, not raised: {error}"+ );++ // A disabled source is skipped entirely rather than reported as a failure.+ // `update` takes a partial-patch object, not loose fields.+ let disabled = h+ .ok(+ 2204,+ "openhuman.task_sources_update",+ json!({ "id": source_id, "patch": { "enabled": false } }),+ )+ .await;+ assert_eq!(+ disabled.get("enabled").and_then(Value::as_bool),+ Some(false),+ "the patch is applied and echoed: {disabled}"+ );+ let after = h.ok(2205, "openhuman.task_sources_sync", json!({})).await;+ assert_eq!(+ after.as_array().map(Vec::len),+ Some(0),+ "a disabled source contributes no outcome: {after}"+ );++ h.join.abort();+}++/// `task_sources_list_databases` promises a `databases` array but cannot+/// deliver one for any provider — the underlying `ComposioProvider::+/// list_databases` was deleted upstream with no replacement. The controller is+/// reachable and returns a diagnosable error rather than an empty list, which+/// is what this pins.+///+/// Documented at+/// `~/tinyhuman/bugs/e2e-wave-task_sources-fetch-pipeline-unavailable.md`.+#[tokio::test]+async fn task_sources_list_databases_is_unavailable_for_every_provider() {+ let _lock = env_lock();+ let h = setup().await;++ for (id, provider) in [+ (2301, "notion"),+ (2302, "github"),+ (2303, "linear"),+ (2304, "clickup"),+ ] {+ let error = h+ .err(+ id,+ "openhuman.task_sources_list_databases",+ json!({ "provider": provider }),+ )+ .await;+ assert!(+ error.contains(provider) && error.contains("unavailable"),+ "list_databases names the toolkit it cannot serve: {error}"+ );+ }++ let unknown = h+ .err(+ 2305,+ "openhuman.task_sources_list_databases",+ json!({ "provider": "jira" }),+ )+ .await;+ assert!(+ unknown.to_lowercase().contains("jira") || unknown.to_lowercase().contains("provider"),+ "an unsupported provider is rejected before the unavailability: {unknown}"+ );++ let missing = h+ .err(2306, "openhuman.task_sources_list_databases", json!({}))+ .await;+ assert!(+ missing.contains("provider"),+ "the required `provider` param is named: {missing}"+ );++ h.join.abort();+}++// ── hooks ───────────────────────────────────────────────────────────────────++/// Write a `hooks.json` into the user layer (`~/.openhuman/hooks.json`) with a+/// single `beforeShellExecution` hook that denies anything matching `^rm `.+fn write_user_hooks(home: &Path) {+ let hooks = json!({+ "version": 1,+ "hooks": {+ "beforeShellExecution": [+ {+ "command": r#"printf '{"permission":"deny","agent_message":"blocked by the e2e hook"}'"#,+ "matcher": "^rm ",+ "timeout": 15+ }+ ]+ }+ });+ let dir = home.join(".openhuman");+ std::fs::create_dir_all(&dir).expect("create .openhuman");+ std::fs::write(+ dir.join("hooks.json"),+ serde_json::to_string_pretty(&hooks).expect("serialize hooks.json"),+ )+ .expect("write hooks.json");+}++/// The whole `hooks` namespace: `reload` re-reads the layer files, `list`+/// answers "what is configured and where did it come from", and `test` fires+/// one synthetic event so an author can see the verdict without provoking the+/// real moment.+#[tokio::test]+async fn hooks_reload_list_and_test_round_trip_a_deny_rule() {+ let _lock = env_lock();+ let h = setup().await;++ // Before the file exists, reload must produce an empty, warning-free config+ // — a host with no hooks is the common case, not a misconfiguration.+ let bare = h.ok(2401, "openhuman.hooks_reload", json!({})).await;+ assert_eq!(+ bare.pointer("/hooks/total").and_then(Value::as_u64),+ Some(0),+ "no hooks.json anywhere means an empty config: {bare}"+ );+ assert_eq!(+ bare.pointer("/hooks/warnings").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "a missing file is not a warning: {bare}"+ );++ write_user_hooks(h.home());++ // `list` reads the in-memory snapshot, so it must still be empty until a+ // reload swaps the new file in. That is the distinction between the two.+ let stale = h.ok(2402, "openhuman.hooks_list", json!({})).await;+ assert_eq!(+ stale.pointer("/hooks/total").and_then(Value::as_u64),+ Some(0),+ "list reports the live snapshot, not the files on disk: {stale}"+ );++ let reloaded = h.ok(2403, "openhuman.hooks_reload", json!({})).await;+ assert_eq!(+ reloaded.pointer("/hooks/total").and_then(Value::as_u64),+ Some(1),+ "reload picked up the new user-layer hook: {reloaded}"+ );+ let sources = reloaded+ .pointer("/hooks/sources")+ .and_then(Value::as_array)+ .expect("sources array");+ assert!(+ sources+ .iter()+ .filter_map(Value::as_str)+ .any(|source| source.ends_with("hooks.json")),+ "the config names the file every definition came from: {sources:?}"+ );++ let definition = reloaded+ .pointer("/hooks/by_event/beforeShellExecution/definitions/0")+ .unwrap_or_else(|| panic!("the hook is filed under its event: {reloaded}"));+ assert_eq!(+ definition.get("matcher").and_then(Value::as_str),+ Some("^rm ")+ );+ assert_eq!(definition.get("timeout").and_then(Value::as_u64), Some(15));+ assert_eq!(+ definition.get("layer").and_then(Value::as_str),+ Some("user"),+ "the layer is resolved from the file's location, never read from it: {definition}"+ );+ assert_eq!(+ definition.get("enabled").and_then(Value::as_bool),+ Some(true)+ );+ assert_eq!(+ definition.get("fail_closed").and_then(Value::as_bool),+ Some(false),+ "fail_closed is opt-in, so a broken audit script cannot brick the agent: {definition}"+ );++ // `list` now agrees with the reload — the snapshot was swapped, not copied.+ let listed = h.ok(2404, "openhuman.hooks_list", json!({})).await;+ assert_eq!(+ listed.pointer("/hooks/total").and_then(Value::as_u64),+ Some(1),+ "list reflects the reloaded config: {listed}"+ );++ // A command that matches: the hook runs and its verdict is the decision.+ let denied = h+ .ok(+ 2405,+ "openhuman.hooks_test",+ json!({+ "event": "beforeShellExecution",+ "payload": { "command": "rm -rf /", "sandbox": false },+ }),+ )+ .await;+ assert_eq!(+ denied.pointer("/result/event").and_then(Value::as_str),+ Some("beforeShellExecution")+ );+ assert_eq!(+ denied.pointer("/result/decision/permission").and_then(Value::as_str),+ Some("deny"),+ "the matching hook's verdict is the merged decision: {denied}"+ );+ assert_eq!(+ denied+ .pointer("/result/decision/agent_message")+ .and_then(Value::as_str),+ Some("blocked by the e2e hook"),+ "the model-facing reason survives the round trip: {denied}"+ );+ let runs = denied+ .pointer("/result/runs")+ .and_then(Value::as_array)+ .expect("runs array");+ assert_eq!(runs.len(), 1, "exactly the one matching hook ran: {denied}");+ assert!(+ runs[0].get("error").is_none_or(Value::is_null),+ "the hook ran cleanly: {denied}"+ );++ // A command that does NOT match the matcher: the hook is not run at all.+ let allowed = h+ .ok(+ 2406,+ "openhuman.hooks_test",+ json!({+ "event": "beforeShellExecution",+ "payload": { "command": "ls -la", "sandbox": false },+ }),+ )+ .await;+ assert_eq!(+ allowed.pointer("/result/runs").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "the matcher gates which occurrences reach the hook: {allowed}"+ );+ assert!(+ allowed+ .pointer("/result/decision/permission")+ .is_none_or(Value::is_null),+ "no hook ran, so nothing was decided: {allowed}"+ );++ // A different event the hook is not registered for is likewise untouched.+ let other_event = h+ .ok(+ 2407,+ "openhuman.hooks_test",+ json!({ "event": "sessionStart", "payload": { "entrypoint": "e2e" } }),+ )+ .await;+ assert_eq!(+ other_event.pointer("/result/runs").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "an event with no hooks configured runs nothing: {other_event}"+ );++ // Teardown, and an assertion in its own right. The hook engine and the+ // harness bridge are PROCESS-global: a loaded config here would stay+ // installed for every other suite in the aggregated binary, and a deny rule+ // pointing at this test's since-deleted tempdir would then judge their+ // shell calls. Removing the file and reloading must empty the engine again+ // — which is also the only way to observe that `reload` *unloads*, not just+ // loads.+ std::fs::remove_file(h.home().join(".openhuman").join("hooks.json"))+ .expect("remove hooks.json");+ let unloaded = h.ok(2408, "openhuman.hooks_reload", json!({})).await;+ assert_eq!(+ unloaded.pointer("/hooks/total").and_then(Value::as_u64),+ Some(0),+ "reload unloads a removed layer rather than keeping the last good one: {unloaded}"+ );++ h.join.abort();+}++/// `hooks_test` refuses an event name it does not know, and says which names it+/// does — the endpoint exists so an author never has to guess.+#[tokio::test]+async fn hooks_test_rejects_unknown_events_and_malformed_payloads() {+ let _lock = env_lock();+ let h = setup().await;++ let unknown = h+ .err(+ 2501,+ "openhuman.hooks_test",+ json!({ "event": "beforeLaunchingRockets" }),+ )+ .await;+ assert!(+ unknown.contains("beforeLaunchingRockets"),+ "the rejection quotes the name given: {unknown}"+ );+ assert!(+ unknown.contains("beforeShellExecution") && unknown.contains("preToolUse"),+ "and lists the known events so the author can correct it: {unknown}"+ );++ // The payload is parsed against the event's own body type, so a shell+ // payload missing its required `command` is a typed error, not a panic.+ let malformed = h+ .err(+ 2502,+ "openhuman.hooks_test",+ json!({ "event": "beforeShellExecution", "payload": { "sandbox": false } }),+ )+ .await;+ assert!(+ malformed.contains("beforeShellExecution") && malformed.contains("payload"),+ "the payload error names the event it failed to parse for: {malformed}"+ );++ let no_event = h.err(2503, "openhuman.hooks_test", json!({})).await;+ assert!(+ no_event.contains("event"),+ "the required `event` param is named: {no_event}"+ );++ h.join.abort();+}++/// A malformed `hooks.json` is a **warning**, not a silent drop: the author+/// believes that file is running, so `list` must say why it is not.+#[tokio::test]+async fn hooks_reload_surfaces_a_malformed_file_as_a_warning() {+ let _lock = env_lock();+ let h = setup().await;++ let dir = h.home().join(".openhuman");+ std::fs::create_dir_all(&dir).expect("create .openhuman");+ std::fs::write(dir.join("hooks.json"), "{ this is not json").expect("write bad hooks.json");++ let reloaded = h.ok(2601, "openhuman.hooks_reload", json!({})).await;+ assert_eq!(+ reloaded.pointer("/hooks/total").and_then(Value::as_u64),+ Some(0),+ "an unparseable file contributes no definitions: {reloaded}"+ );+ let warnings = reloaded+ .pointer("/hooks/warnings")+ .and_then(Value::as_array)+ .expect("warnings array");+ assert!(+ warnings+ .iter()+ .filter_map(Value::as_str)+ .any(|warning| warning.contains("hooks.json")),+ "the warning names the file that failed to load: {warnings:?}"+ );++ h.join.abort();+}++// ── harness_init ────────────────────────────────────────────────────────────++/// `harness_init_run` is the retry behind the first-run setup overlay. With+/// every provisioning backend switched off, each step's cheap probe reports it+/// satisfied and the run must settle `done` **without downloading anything**.+///+/// `force` is the interesting parameter: it must bypass the probe and actually+/// invoke each step, which is observable in the per-step message — the+/// probe-satisfied path stamps "already provisioned" and the forced path does+/// not.+#[tokio::test]+async fn harness_init_run_completes_offline_and_force_bypasses_the_probes() {+ let _lock = env_lock();+ let h = setup().await;++ let snapshot = h+ .ok(2701, "openhuman.harness_init_run", json!({}))+ .await;+ let steps = snapshot+ .pointer("/snapshot/steps")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("the snapshot carries a steps array: {snapshot}"));+ assert_eq!(+ snapshot.pointer("/snapshot/overall").and_then(Value::as_str),+ Some("done"),+ "no required step can fail when every backend is off: {snapshot}"+ );++ let step_ids: Vec<&str> = steps.iter().map(|step| str_at(step, "/id")).collect();+ for expected in [+ "python_runtime",+ "spacy",+ "kompress",+ "runtime_python_server",+ ] {+ assert!(+ step_ids.contains(&expected),+ "the registry step {expected} must appear in the snapshot, got {step_ids:?}"+ );+ }++ for step in steps {+ assert_eq!(+ step.get("state").and_then(Value::as_str),+ Some("done"),+ "every disabled step probes satisfied: {step}"+ );+ assert_eq!(+ step.get("message").and_then(Value::as_str),+ Some("already provisioned"),+ "the unforced path marks Done from the probe, without running: {step}"+ );+ assert_eq!(step.get("percent").and_then(Value::as_u64), Some(100));+ assert_eq!(+ step.get("required").and_then(Value::as_bool),+ Some(false),+ "every registered step is non-required today: {step}"+ );+ assert!(+ step.get("updated_at").and_then(Value::as_str).is_some(),+ "each state change is stamped: {step}"+ );+ }++ let forced = h+ .ok(2702, "openhuman.harness_init_run", json!({ "force": true }))+ .await;+ assert_eq!(+ forced.pointer("/snapshot/overall").and_then(Value::as_str),+ Some("done"),+ "a forced re-run of disabled steps still settles done: {forced}"+ );+ let forced_steps = forced+ .pointer("/snapshot/steps")+ .and_then(Value::as_array)+ .expect("forced steps array");+ for step in forced_steps {+ assert_eq!(+ step.get("state").and_then(Value::as_str),+ Some("done"),+ "a forced disabled step returns Ok immediately: {step}"+ );+ assert!(+ step.get("message").and_then(Value::as_str) != Some("already provisioned"),+ "force must bypass the probe, so the probe's message cannot appear: {step}"+ );+ }+ assert!(+ forced.pointer("/snapshot/finished_at").and_then(Value::as_str).is_some(),+ "a finished run is stamped: {forced}"+ );++ // `harness_init_status` must report the same snapshot the run just left+ // behind, not recompute one.+ let status = h.ok(2703, "openhuman.harness_init_status", json!({})).await;+ assert_eq!(+ status.pointer("/snapshot/overall").and_then(Value::as_str),+ Some("done"),+ "status reads the store the run wrote: {status}"+ );+ assert_eq!(+ status.pointer("/snapshot/steps").and_then(Value::as_array).map(Vec::len),+ forced_steps.len().into(),+ "status and run agree on the step list: {status}"+ );++ h.join.abort();+}diff --git a/tests/raw_coverage/flows_lifecycle_e2e.rs b/tests/raw_coverage/flows_lifecycle_e2e.rsnew file mode 100644index 0000000000..188ccdf039--- /dev/null+++ b/tests/raw_coverage/flows_lifecycle_e2e.rs@@ -0,0 +1,1182 @@+//! JSON-RPC E2E coverage for the uncovered half of the `flows` namespace:+//! core-managed drafts, duplicate/enable, revision history + rollback, the+//! run-history read/prune surface, the save-time approval manifest and+//! connector requirements, the canvas tool-browser surface, and the copilot's+//! Stop button.+//!+//! Every case boots the real Axum JSON-RPC router over HTTP against an+//! isolated `HOME`, dispatches through `/rpc`, and asserts on the **content**+//! of the response. Paths that would reach Composio are asserted at the+//! credential boundary so the suite stays hermetic and offline.+//!+//! Aggregated into `tests/raw_coverage_all.rs` by `build.rs`. Run with:+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" flows_lifecycle_e2e`++#![cfg(feature = "flows")]++use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;++/// Seeded only if this suite is the first in the aggregated binary to+/// initialise the token; the bearer actually sent is always read back from+/// `get_rpc_token()`, because `RPC_TOKEN` is a process-global `OnceLock` and+/// whichever aggregated suite calls `init_rpc_token` first wins it for all.+const TEST_RPC_TOKEN: &str = "flows-lifecycle-e2e-token";++/// `tinyflows_sqlite::flows::MAX_FLOW_RUNS_PER_FLOW` — the retention cap+/// `flows_prune_runs` reports as `kept`. Hard-coded rather than imported so a+/// silent change to the cap fails this test instead of tracking it.+const EXPECTED_RUN_RETENTION_CAP: u64 = 100;++static AUTH_INIT: OnceLock<()> = OnceLock::new();++/// The crate-wide env lock, not a private one. Every aggregated suite in+/// `raw_coverage_all` shares one process, so libtest runs them concurrently+/// and a lock local to this file would isolate nothing.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++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 case in this binary: `HOME` and the backend-URL overrides+/// are process-global, so two cases running in parallel would resolve each+/// other's `config.toml` and each other's flows database.+fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++/// Initialise the process RPC token (idempotent) and return the bearer the+/// router will actually accept.+fn ensure_rpc_auth() -> &'static str {+ AUTH_INIT.get_or_init(|| {+ if get_rpc_token().is_none() {+ std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);+ }+ let token_dir = std::env::temp_dir().join("openhuman-flows-lifecycle-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+ get_rpc_token().expect("rpc token initialized")+}++async fn serve_rpc() -> (+ SocketAddr,+ &'static str,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ let token = ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let join =+ tokio::spawn(async move { axum::serve(listener, build_core_http_router(false)).await });+ (addr, token, join)+}++/// `api_url` points at a closed port on purpose: no case here may reach the+/// network, and a refused connection is the fastest deterministic failure.+fn write_min_config(openhuman_dir: &Path) {+ let cfg = r#"api_url = "http://127.0.0.1:9"+default_model = "flows-e2e-model"+default_temperature = 0.2+chat_onboarding_completed = true++[secrets]+encrypt = false++[local_ai]+enabled = false++[memory]+provider = "none"+embedding_provider = "none"+embedding_model = "none"+embedding_dimensions = 0++[memory_tree]+embedding_strict = false+"#;+ let write = |dir: &Path| {+ std::fs::create_dir_all(dir).expect("create config dir");+ std::fs::write(dir.join("config.toml"), cfg).expect("write config.toml");+ };+ write(openhuman_dir);+ // Runtime config resolution is user-scoped before login, so the pre-login+ // `users/local` layer needs the same file or the RPC handlers load defaults.+ write(&openhuman_dir.join("users").join("local"));+ let _: openhuman_core::openhuman::config::Config =+ toml::from_str(cfg).expect("test config must match the Config schema");+}++struct Harness {+ _tmp: TempDir,+ _guards: Vec<EnvVarGuard>,+ rpc_base: String,+ token: &'static str,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++impl Harness {+ async fn rpc(&self, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("build rpc client");+ let url = format!("{}/rpc", self.rpc_base);+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", self.token))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": method,+ "params": params,+ }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+ }++ /// Dispatch and unwrap the controller payload, panicking on a JSON-RPC error.+ async fn ok(&self, id: i64, method: &str, params: Value) -> Value {+ let response = self.rpc(id, method, params).await;+ if let Some(error) = response.get("error") {+ panic!("{method}: unexpected JSON-RPC error: {error}");+ }+ let result = response+ .get("result")+ .unwrap_or_else(|| panic!("{method}: missing result: {response}"));+ // Controllers return `{ result, logs }`; peel that envelope when present.+ match result.get("result") {+ Some(inner) if result.get("logs").is_some() => inner.clone(),+ _ => result.clone(),+ }+ }++ /// Dispatch and return the JSON-RPC error message, panicking on success.+ async fn err(&self, id: i64, method: &str, params: Value) -> String {+ let response = self.rpc(id, method, params).await;+ let error = response+ .get("error")+ .unwrap_or_else(|| panic!("{method}: expected a JSON-RPC error, got: {response}"));+ error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{method}: error carries no message: {error}"))+ .to_string()+ }+}++async fn setup() -> Harness {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ write_min_config(&home.join(".openhuman"));++ // `flows_approval_manifest` builds a `SecurityPolicy` from `action_dir`,+ // which defaults to `~/OpenHuman/projects` — the developer's real+ // directory. Pin it inside the tempdir so no case reads host state.+ let action_dir = home.join("actions");+ std::fs::create_dir_all(&action_dir).expect("create action dir");++ let guards = vec![+ EnvVarGuard::set_to_path("HOME", home),+ EnvVarGuard::set_to_path("OPENHUMAN_ACTION_DIR", &action_dir),+ EnvVarGuard::unset("OPENHUMAN_WORKSPACE"),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::unset("COMPOSIO_API_KEY"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let (addr, token, join) = serve_rpc().await;+ Harness {+ _tmp: tmp,+ _guards: guards,+ rpc_base: format!("http://{addr}"),+ token,+ join,+ }+}++/// The smallest structurally valid graph: one manual trigger.+fn trigger_only_graph() -> Value {+ json!({+ "nodes": [{ "id": "t", "kind": "trigger", "name": "Manual" }],+ "edges": []+ })+}++/// A trigger plus a pass-through parser — runs to completion with no model.+fn two_node_graph() -> Value {+ json!({+ "nodes": [+ { "id": "t", "kind": "trigger", "name": "Manual" },+ { "id": "p", "kind": "output_parser", "name": "Passthrough" }+ ],+ "edges": [{ "from_node": "t", "to_node": "p" }]+ })+}++fn str_at<'a>(value: &'a Value, pointer: &str) -> &'a str {+ value+ .pointer(pointer)+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("expected a string at {pointer} in {value}"))+}++// ── drafts ──────────────────────────────────────────────────────────────────++/// The whole core-managed draft surface: create → list → get → update →+/// promote, plus the three ways it refuses. `draft_promote` is the interesting+/// one: it must run the *same* create gates as a direct save and then delete+/// the draft, so the draft store is empty afterwards and the flow store is not.+#[tokio::test]+async fn flows_draft_surface_round_trips_and_promotes_into_a_saved_flow() {+ let _lock = env_lock();+ let h = setup().await;++ let draft = h+ .ok(+ 1001,+ "openhuman.flows_draft_create",+ json!({ "name": "Draft One", "graph": trigger_only_graph(), "origin": "chat" }),+ )+ .await;+ let draft_id = str_at(&draft, "/id").to_string();+ assert!(!draft_id.is_empty(), "draft_create must mint an id");+ assert_eq!(draft.get("name").and_then(Value::as_str), Some("Draft One"));+ assert_eq!(draft.get("origin").and_then(Value::as_str), Some("chat"));+ assert!(+ draft.get("flow_id").is_none_or(Value::is_null),+ "an unlinked draft carries no flow_id: {draft}"+ );+ assert_eq!(+ draft.pointer("/graph/nodes").and_then(Value::as_array).map(Vec::len),+ Some(1),+ "draft_create stores the graph verbatim: {draft}"+ );++ let listed = h.ok(1002, "openhuman.flows_draft_list", json!({})).await;+ let drafts = listed.as_array().expect("draft_list returns an array");+ assert_eq!(drafts.len(), 1, "exactly the draft just created: {listed}");+ assert_eq!(str_at(&drafts[0], "/id"), draft_id);++ let fetched = h+ .ok(1003, "openhuman.flows_draft_get", json!({ "id": draft_id }))+ .await;+ assert_eq!(str_at(&fetched, "/name"), "Draft One");++ let missing = h+ .err(+ 1004,+ "openhuman.flows_draft_get",+ json!({ "id": "no-such-draft" }),+ )+ .await;+ assert!(+ missing.contains("no-such-draft") && missing.contains("not found"),+ "draft_get names the absent id: {missing}"+ );++ let updated = h+ .ok(+ 1005,+ "openhuman.flows_draft_update",+ json!({ "id": draft_id, "name": "Draft Renamed", "graph": two_node_graph() }),+ )+ .await;+ assert_eq!(str_at(&updated, "/name"), "Draft Renamed");+ assert_eq!(+ updated.pointer("/graph/nodes").and_then(Value::as_array).map(Vec::len),+ Some(2),+ "draft_update replaces the graph: {updated}"+ );++ // A non-string `flow_id` must be REJECTED, not coerced into an unlink —+ // silently unlinking would make the later promote create a second flow.+ let bad_link = h+ .err(+ 1006,+ "openhuman.flows_draft_update",+ json!({ "id": draft_id, "flow_id": 42 }),+ )+ .await;+ assert!(+ bad_link.to_lowercase().contains("flow_id"),+ "a numeric flow_id is rejected by name: {bad_link}"+ );++ let promoted = h+ .ok(+ 1007,+ "openhuman.flows_draft_promote",+ json!({ "id": draft_id }),+ )+ .await;+ let flow_id = str_at(&promoted, "/id").to_string();+ assert_eq!(+ str_at(&promoted, "/name"),+ "Draft Renamed",+ "promote carries the draft's name onto the flow"+ );+ assert_ne!(flow_id, draft_id, "the flow gets its own id");++ let flows = h.ok(1008, "openhuman.flows_list", json!({})).await;+ let flows = flows.as_array().expect("flows_list returns an array");+ assert_eq!(flows.len(), 1, "promote saved exactly one flow: {flows:?}");+ assert_eq!(str_at(&flows[0], "/id"), flow_id);++ let after = h.ok(1009, "openhuman.flows_draft_list", json!({})).await;+ assert_eq!(+ after.as_array().map(Vec::len),+ Some(0),+ "promote deletes the draft it consumed: {after}"+ );++ // Delete is idempotent and says so rather than erroring.+ let deleted = h+ .ok(+ 1010,+ "openhuman.flows_draft_delete",+ json!({ "id": draft_id }),+ )+ .await;+ assert_eq!(deleted.get("id").and_then(Value::as_str), Some(draft_id.as_str()));+ assert_eq!(+ deleted.get("deleted").and_then(Value::as_bool),+ Some(false),+ "deleting an already-absent draft reports deleted=false: {deleted}"+ );++ let promote_missing = h+ .err(+ 1011,+ "openhuman.flows_draft_promote",+ json!({ "id": "no-such-draft" }),+ )+ .await;+ assert!(+ promote_missing.contains("no-such-draft"),+ "promote names the absent draft: {promote_missing}"+ );++ h.join.abort();+}++/// A draft that names a `flow_id` must UPDATE that flow on promote rather than+/// create a second one — the behaviour `parse_draft_update_flow_id` exists to+/// protect.+#[tokio::test]+async fn flows_draft_promote_updates_the_linked_flow_instead_of_creating_a_second() {+ let _lock = env_lock();+ let h = setup().await;++ let flow = h+ .ok(+ 1101,+ "openhuman.flows_create",+ json!({ "name": "Original", "graph": trigger_only_graph() }),+ )+ .await;+ let flow_id = str_at(&flow, "/id").to_string();++ let draft = h+ .ok(+ 1102,+ "openhuman.flows_draft_create",+ json!({+ "name": "Edited In Canvas",+ "graph": two_node_graph(),+ "flow_id": flow_id,+ }),+ )+ .await;+ assert_eq!(+ draft.get("flow_id").and_then(Value::as_str),+ Some(flow_id.as_str()),+ "the draft records the flow it edits: {draft}"+ );++ let promoted = h+ .ok(+ 1103,+ "openhuman.flows_draft_promote",+ json!({ "id": str_at(&draft, "/id") }),+ )+ .await;+ assert_eq!(+ str_at(&promoted, "/id"),+ flow_id,+ "promoting a linked draft updates the SAME flow: {promoted}"+ );+ assert_eq!(str_at(&promoted, "/name"), "Edited In Canvas");++ let flows = h.ok(1104, "openhuman.flows_list", json!({})).await;+ assert_eq!(+ flows.as_array().map(Vec::len),+ Some(1),+ "no second flow was created: {flows}"+ );++ h.join.abort();+}++// ── duplicate / set_enabled ─────────────────────────────────────────────────++/// A duplicate is a copy that is deliberately born DISABLED and unbound, so it+/// can never fire on its own schedule before the user has reviewed it.+#[tokio::test]+async fn flows_duplicate_copies_the_graph_and_lands_disabled() {+ let _lock = env_lock();+ let h = setup().await;++ let source = h+ .ok(+ 1201,+ "openhuman.flows_create",+ json!({ "name": "Nightly Report", "graph": two_node_graph() }),+ )+ .await;+ let source_id = str_at(&source, "/id").to_string();+ assert_eq!(+ source.get("enabled").and_then(Value::as_bool),+ Some(true),+ "a manually triggered flow is created enabled"+ );++ let copy = h+ .ok(+ 1202,+ "openhuman.flows_duplicate",+ json!({ "id": source_id }),+ )+ .await;+ assert_ne!(str_at(©, "/id"), source_id, "the copy gets a fresh id");+ assert_eq!(+ str_at(©, "/name"),+ "Nightly Report (copy)",+ "the copy is suffixed: {copy}"+ );+ assert_eq!(+ copy.get("enabled").and_then(Value::as_bool),+ Some(false),+ "a duplicate is born disabled: {copy}"+ );+ assert_eq!(+ copy.pointer("/graph/nodes").and_then(Value::as_array).map(Vec::len),+ Some(2),+ "the copy carries the source graph: {copy}"+ );++ let flows = h.ok(1203, "openhuman.flows_list", json!({})).await;+ assert_eq!(flows.as_array().map(Vec::len), Some(2));++ let missing = h+ .err(+ 1204,+ "openhuman.flows_duplicate",+ json!({ "id": "no-such-flow" }),+ )+ .await;+ assert!(+ missing.contains("no-such-flow") && missing.contains("not found"),+ "duplicate names the absent flow: {missing}"+ );++ h.join.abort();+}++/// `set_enabled` is the toggle behind the flow list's switch. Both directions+/// must be reflected in the stored flow, and a re-read must agree.+#[tokio::test]+async fn flows_set_enabled_toggles_both_ways_and_persists() {+ let _lock = env_lock();+ let h = setup().await;++ let flow = h+ .ok(+ 1301,+ "openhuman.flows_create",+ json!({ "name": "Toggle Me", "graph": trigger_only_graph() }),+ )+ .await;+ let flow_id = str_at(&flow, "/id").to_string();++ let off = h+ .ok(+ 1302,+ "openhuman.flows_set_enabled",+ json!({ "id": flow_id, "enabled": false }),+ )+ .await;+ assert_eq!(off.get("enabled").and_then(Value::as_bool), Some(false));++ let reread = h+ .ok(1303, "openhuman.flows_get", json!({ "id": flow_id }))+ .await;+ assert_eq!(+ reread.get("enabled").and_then(Value::as_bool),+ Some(false),+ "the disable is persisted, not just echoed: {reread}"+ );++ let on = h+ .ok(+ 1304,+ "openhuman.flows_set_enabled",+ json!({ "id": flow_id, "enabled": true }),+ )+ .await;+ assert_eq!(on.get("enabled").and_then(Value::as_bool), Some(true));++ let missing = h+ .err(+ 1305,+ "openhuman.flows_set_enabled",+ json!({ "id": "no-such-flow", "enabled": true }),+ )+ .await;+ assert!(+ missing.to_lowercase().contains("not found") || missing.contains("no-such-flow"),+ "set_enabled on an absent flow is an error: {missing}"+ );++ let no_flag = h+ .err(+ 1306,+ "openhuman.flows_set_enabled",+ json!({ "id": flow_id }),+ )+ .await;+ assert!(+ no_flag.contains("enabled"),+ "the required `enabled` param is named: {no_flag}"+ );++ h.join.abort();+}++// ── history / rollback ──────────────────────────────────────────────────────++/// Every update snapshots the *prior* graph, and rollback restores one through+/// the normal update path — so the rollback is itself snapshotted and undoable.+#[tokio::test]+async fn flows_history_records_prior_graphs_and_rollback_restores_them() {+ let _lock = env_lock();+ let h = setup().await;++ let flow = h+ .ok(+ 1401,+ "openhuman.flows_create",+ json!({ "name": "Versioned", "graph": trigger_only_graph() }),+ )+ .await;+ let flow_id = str_at(&flow, "/id").to_string();++ let empty = h+ .ok(+ 1402,+ "openhuman.flows_get_history",+ json!({ "id": flow_id }),+ )+ .await;+ assert_eq!(+ empty.as_array().map(Vec::len),+ Some(0),+ "a freshly created flow has no prior revisions: {empty}"+ );++ h.ok(+ 1403,+ "openhuman.flows_update",+ json!({ "id": flow_id, "graph": two_node_graph() }),+ )+ .await;++ let history = h+ .ok(+ 1404,+ "openhuman.flows_get_history",+ json!({ "id": flow_id }),+ )+ .await;+ let revisions = history.as_array().expect("get_history returns an array");+ assert_eq!(revisions.len(), 1, "one prior snapshot: {history}");+ let revision = &revisions[0];+ let revision_id = str_at(revision, "/id").to_string();+ assert_eq!(+ revision.get("flow_id").and_then(Value::as_str),+ Some(flow_id.as_str())+ );+ assert_eq!(+ revision.pointer("/graph/nodes").and_then(Value::as_array).map(Vec::len),+ Some(1),+ "the snapshot holds the ORIGINAL one-node graph, not the new one: {revision}"+ );++ let rolled = h+ .ok(+ 1405,+ "openhuman.flows_rollback",+ json!({ "id": flow_id, "revision_id": revision_id }),+ )+ .await;+ assert_eq!(+ rolled.pointer("/graph/nodes").and_then(Value::as_array).map(Vec::len),+ Some(1),+ "rollback restored the one-node graph: {rolled}"+ );++ let after = h+ .ok(+ 1406,+ "openhuman.flows_get_history",+ json!({ "id": flow_id }),+ )+ .await;+ assert_eq!(+ after.as_array().map(Vec::len),+ Some(2),+ "the rollback snapshotted the graph it replaced, so it is undoable: {after}"+ );++ let bad_revision = h+ .err(+ 1407,+ "openhuman.flows_rollback",+ json!({ "id": flow_id, "revision_id": "no-such-revision" }),+ )+ .await;+ assert!(+ bad_revision.contains("no-such-revision") && bad_revision.contains(&flow_id),+ "rollback names both the revision and the flow: {bad_revision}"+ );++ // `limit` is honoured, not ignored.+ let capped = h+ .ok(+ 1408,+ "openhuman.flows_get_history",+ json!({ "id": flow_id, "limit": 1 }),+ )+ .await;+ assert_eq!(+ capped.as_array().map(Vec::len),+ Some(1),+ "get_history honours limit: {capped}"+ );++ h.join.abort();+}++// ── run history: list_all_runs / prune_runs ─────────────────────────────────++/// `flows_list_runs` is per-flow; `flows_list_all_runs` is the cross-flow feed+/// behind the global run list. It must see runs from *both* flows, newest+/// first, and honour its limit.+#[tokio::test]+async fn flows_list_all_runs_spans_flows_and_prune_reports_the_retention_cap() {+ let _lock = env_lock();+ let h = setup().await;++ let first = h+ .ok(+ 1501,+ "openhuman.flows_create",+ json!({ "name": "Flow A", "graph": two_node_graph() }),+ )+ .await;+ let first_id = str_at(&first, "/id").to_string();+ let second = h+ .ok(+ 1502,+ "openhuman.flows_create",+ json!({ "name": "Flow B", "graph": two_node_graph() }),+ )+ .await;+ let second_id = str_at(&second, "/id").to_string();++ h.ok(1503, "openhuman.flows_run", json!({ "id": first_id })).await;+ h.ok(1504, "openhuman.flows_run", json!({ "id": second_id })).await;++ let all = h.ok(1505, "openhuman.flows_list_all_runs", json!({})).await;+ let runs = all.as_array().expect("list_all_runs returns an array");+ assert_eq!(runs.len(), 2, "one run recorded per flow: {all}");+ let flow_ids: Vec<&str> = runs.iter().map(|run| str_at(run, "/flow_id")).collect();+ assert!(+ flow_ids.contains(&first_id.as_str()) && flow_ids.contains(&second_id.as_str()),+ "list_all_runs spans both flows, got {flow_ids:?}"+ );+ assert_eq!(+ str_at(&runs[0], "/flow_id"),+ second_id,+ "newest first — Flow B ran last: {all}"+ );++ let one = h+ .ok(1506, "openhuman.flows_list_all_runs", json!({ "limit": 1 }))+ .await;+ assert_eq!(+ one.as_array().map(Vec::len),+ Some(1),+ "list_all_runs honours limit: {one}"+ );++ // Two runs are far inside the retention window, so an explicit sweep must+ // remove nothing while still reporting the cap it swept against.+ let pruned = h+ .ok(+ 1507,+ "openhuman.flows_prune_runs",+ json!({ "id": first_id }),+ )+ .await;+ assert_eq!(+ pruned.get("flow_id").and_then(Value::as_str),+ Some(first_id.as_str())+ );+ assert_eq!(+ pruned.get("pruned").and_then(Value::as_u64),+ Some(0),+ "nothing to prune inside the window: {pruned}"+ );+ assert_eq!(+ pruned.get("kept").and_then(Value::as_u64),+ Some(EXPECTED_RUN_RETENTION_CAP),+ "prune reports the retention cap it applied: {pruned}"+ );++ let still_there = h.ok(1508, "openhuman.flows_list_all_runs", json!({})).await;+ assert_eq!(+ still_there.as_array().map(Vec::len),+ Some(2),+ "a no-op prune must not delete live history: {still_there}"+ );++ let missing_id = h+ .err(1509, "openhuman.flows_prune_runs", json!({}))+ .await;+ assert!(+ missing_id.contains("id"),+ "prune_runs names its required param: {missing_id}"+ );++ h.join.abort();+}++// ── approval manifest / required connections ────────────────────────────────++/// The save+enable pre-authorization card: one row per permission a run will+/// prompt for, classified, deduped on the trust key, and joined against the+/// grants the flow already holds.+#[tokio::test]+async fn flows_approval_manifest_classifies_every_gated_node_kind() {+ let _lock = env_lock();+ let h = setup().await;++ let graph = json!({+ "nodes": [+ { "id": "t", "kind": "trigger", "name": "Manual" },+ { "id": "http", "kind": "http_request", "name": "Call",+ "config": { "url": "https://example.invalid/hook", "method": "POST" } },+ { "id": "code", "kind": "code", "name": "Transform",+ "config": { "language": "javascript", "code": "return items;" } },+ { "id": "dyn", "kind": "tool_call", "name": "Chosen at run time",+ "config": { "slug": "=nodes.t.output.slug", "args": {} } },+ { "id": "ai", "kind": "agent", "name": "Summarize",+ "config": { "agent_ref": "summarizer", "prompt": "summarize" } }+ ],+ "edges": [+ { "from_node": "t", "to_node": "http" },+ { "from_node": "http", "to_node": "code" },+ { "from_node": "code", "to_node": "dyn" },+ { "from_node": "dyn", "to_node": "ai" }+ ]+ });++ let manifest = h+ .ok(+ 1601,+ "openhuman.flows_approval_manifest",+ json!({ "graph": graph }),+ )+ .await;+ let entries = manifest+ .get("entries")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("manifest carries an entries array: {manifest}"));++ let find = |tool: &str| -> &Value {+ entries+ .iter()+ .find(|entry| entry.get("tool_name").and_then(Value::as_str) == Some(tool))+ .unwrap_or_else(|| panic!("manifest must list {tool}: {manifest}"))+ };++ let http = find("flows_http_request");+ assert_eq!(http.get("node_id").and_then(Value::as_str), Some("http"));+ assert_eq!(http.get("class").and_then(Value::as_str), Some("Network"));+ assert_eq!(+ str_at(http, "/label"),+ "Call https://example.invalid/hook",+ "the label names the destination so the card is readable: {http}"+ );++ let code = find("flows_code");+ assert_eq!(code.get("class").and_then(Value::as_str), Some("Write"));++ assert!(+ entries+ .iter()+ .any(|entry| entry.get("kind").and_then(Value::as_str) == Some("dynamic")+ && entry.get("node_id").and_then(Value::as_str) == Some("dyn")),+ "an `=` slug cannot be pre-approved and must be disclosed as dynamic: {manifest}"+ );+ assert!(+ entries+ .iter()+ .any(|entry| entry.get("kind").and_then(Value::as_str) == Some("agent")+ && entry.get("node_id").and_then(Value::as_str) == Some("ai")),+ "an agent node's inner tool calls are unknowable and must be disclosed: {manifest}"+ );++ // `missing` and `already_trusted` partition the APPROVABLE keys — the+ // dynamic and agent rows have no trust key to grant, so neither list may+ // name them.+ let gate_installed = manifest+ .get("gate_installed")+ .and_then(Value::as_bool)+ .unwrap_or_else(|| panic!("gate_installed is reported as a boolean: {manifest}"));+ let missing: Vec<&str> = manifest+ .get("missing")+ .and_then(Value::as_array)+ .expect("missing array")+ .iter()+ .filter_map(Value::as_str)+ .collect();+ let already: Vec<&str> = manifest+ .get("already_trusted")+ .and_then(Value::as_array)+ .expect("already_trusted array")+ .iter()+ .filter_map(Value::as_str)+ .collect();++ if gate_installed {+ // No `id` was given, so no grants can be joined: every approvable key+ // is missing and nothing is already trusted.+ assert!(+ missing.contains(&"flows_http_request") && missing.contains(&"flows_code"),+ "un-granted approvable keys are listed as missing: {missing:?}"+ );+ assert!(+ already.is_empty(),+ "a candidate graph joined against no flow holds no grants: {already:?}"+ );+ } else {+ // Gate uninstalled: nothing ever parks, so `missing` is empty by+ // definition. The approvable keys are currently routed into+ // `already_trusted` instead of a third state, which claims grants the+ // flow does not hold — see+ // `~/tinyhuman/bugs/e2e-wave-flows-approval-manifest-already-trusted-without-gate.md`.+ // Pinned as-is so the fix has to come past this assertion.+ assert!(+ missing.is_empty(),+ "with no gate installed nothing can park, so nothing is missing: {missing:?}"+ );+ assert!(+ already.contains(&"flows_http_request") && already.contains(&"flows_code"),+ "current behaviour: un-gated approvable keys land in already_trusted: {already:?}"+ );+ }+ for list in [&missing, &already] {+ assert!(+ !list.contains(&"dyn") && !list.contains(&"ai"),+ "only approvable rows carry a trust key: {list:?}"+ );+ }++ let neither = h+ .err(1602, "openhuman.flows_approval_manifest", json!({}))+ .await;+ assert!(+ neither.contains("'id'") && neither.contains("'graph'"),+ "the manifest says which of the two inputs it needs: {neither}"+ );++ let unknown = h+ .err(+ 1603,+ "openhuman.flows_approval_manifest",+ json!({ "id": "no-such-flow" }),+ )+ .await;+ assert!(+ unknown.contains("no-such-flow"),+ "the manifest names the absent flow: {unknown}"+ );++ h.join.abort();+}++/// The "Connect <toolkit>" CTAs. Composio slugs contribute a toolkit; native+/// `oh:` tools and plain HTTP nodes deliberately do not.+#[tokio::test]+async fn flows_required_connections_lists_only_composio_toolkits() {+ let _lock = env_lock();+ let h = setup().await;++ let graph = json!({+ "nodes": [+ { "id": "t", "kind": "trigger", "name": "Manual" },+ { "id": "send", "kind": "tool_call", "name": "Send",+ "config": { "slug": "GMAIL_SEND_EMAIL", "args": {} } },+ { "id": "native", "kind": "tool_call", "name": "Native",+ "config": { "slug": "oh:web_search", "args": {} } },+ { "id": "http", "kind": "http_request", "name": "Webhook",+ "config": { "url": "https://example.invalid/hook", "method": "POST" } }+ ],+ "edges": [+ { "from_node": "t", "to_node": "send" },+ { "from_node": "send", "to_node": "native" },+ { "from_node": "native", "to_node": "http" }+ ]+ });++ let out = h+ .ok(+ 1701,+ "openhuman.flows_required_connections",+ json!({ "graph": graph }),+ )+ .await;+ let required = out+ .get("required_connections")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("required_connections array: {out}"));+ assert_eq!(+ required.len(),+ 1,+ "only the Composio slug needs a connection — `oh:` and http_request do not: {out}"+ );+ assert_eq!(required[0].get("toolkit").and_then(Value::as_str), Some("gmail"));+ assert_eq!(+ required[0].get("status").and_then(Value::as_str),+ Some("missing"),+ "a fresh workspace has no Gmail connection: {out}"+ );++ let none = h+ .ok(+ 1702,+ "openhuman.flows_required_connections",+ json!({ "graph": trigger_only_graph() }),+ )+ .await;+ assert_eq!(+ none.get("required_connections").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "a trigger-only graph needs no connection: {none}"+ );++ let no_graph = h+ .err(1703, "openhuman.flows_required_connections", json!({}))+ .await;+ assert!(+ no_graph.contains("graph"),+ "the required `graph` param is named: {no_graph}"+ );++ h.join.abort();+}++// ── canvas tool browser ─────────────────────────────────────────────────────++/// The in-canvas tool browser reads the LIVE Composio catalog. With no+/// credentials configured there is nothing to read, and the two endpoints+/// degrade differently on purpose: search returns an empty list (a keyword miss+/// is not an error), while a contract fetch for a named action is.+#[tokio::test]+async fn flows_tool_catalog_surface_degrades_without_composio_credentials() {+ let _lock = env_lock();+ let h = setup().await;++ let search = h+ .ok(+ 1801,+ "openhuman.flows_search_tool_catalog",+ json!({ "query": "send email", "toolkit": "gmail", "limit": 5 }),+ )+ .await;+ assert_eq!(+ search.get("tools").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "an unreachable catalog contributes zero rows rather than erroring: {search}"+ );++ // The `<TOOLKIT>_<ACTION>` shape diagnostic. `toolkit_from_slug` splits on+ // `_` and falls back to the whole string, so the ONLY input that reaches+ // this message is one that trims to empty — a single-token slug like+ // `nodashhere` is accepted as its own toolkit and fails later, at the+ // catalog, with a much less useful message. See+ // `~/tinyhuman/bugs/e2e-wave-flows-tool-contract-slug-guard-unreachable.md`.+ let malformed = h+ .err(+ 1802,+ "openhuman.flows_get_tool_contract",+ json!({ "slug": " " }),+ )+ .await;+ assert!(+ malformed.contains("GMAIL_SEND_EMAIL"),+ "the shape diagnostic names the expected form: {malformed}"+ );++ // Current behaviour for a single-token slug: it is treated as a toolkit+ // name rather than rejected, so the failure surfaces at the catalog.+ let single_token = h+ .err(+ 1806,+ "openhuman.flows_get_tool_contract",+ json!({ "slug": "nodashhere" }),+ )+ .await;+ assert!(+ single_token.contains("nodashhere") && single_token.contains("catalog"),+ "a dashless slug is not caught by the shape guard: {single_token}"+ );++ let unreachable = h+ .err(+ 1803,+ "openhuman.flows_get_tool_contract",+ json!({ "slug": "GMAIL_SEND_EMAIL" }),+ )+ .await;+ assert!(+ unreachable.contains("gmail") && unreachable.contains("catalog"),+ "a well-formed slug fails at the catalog, naming the toolkit: {unreachable}"+ );++ let no_slug = h+ .err(1804, "openhuman.flows_get_tool_contract", json!({}))+ .await;+ assert!(+ no_slug.contains("slug"),+ "the required `slug` param is named: {no_slug}"+ );++ let no_query = h+ .err(1805, "openhuman.flows_search_tool_catalog", json!({}))+ .await;+ assert!(+ no_query.contains("query"),+ "the required `query` param is named: {no_query}"+ );++ h.join.abort();+}++// ── copilot Stop button ─────────────────────────────────────────────────────++/// `flows_build_cancel` is the real cancellation behind the Workflow Copilot's+/// Stop button. `cancelled: false` is a normal answer, not an error — nothing+/// was in flight — and that distinction is the whole contract, because a stale+/// Stop must never kill a newer turn.+#[tokio::test]+async fn flows_build_cancel_reports_no_turn_in_flight_without_erroring() {+ let _lock = env_lock();+ let h = setup().await;++ let unscoped = h+ .ok(+ 1901,+ "openhuman.flows_build_cancel",+ json!({ "thread_id": "thread-with-no-build" }),+ )+ .await;+ assert_eq!(+ unscoped.get("cancelled").and_then(Value::as_bool),+ Some(false),+ "nothing in flight is reported, not raised: {unscoped}"+ );++ let scoped = h+ .ok(+ 1902,+ "openhuman.flows_build_cancel",+ json!({ "thread_id": "thread-with-no-build", "request_id": "req-1" }),+ )+ .await;+ assert_eq!(+ scoped.get("cancelled").and_then(Value::as_bool),+ Some(false),+ "a scoped cancel for an unregistered turn is also a no-op: {scoped}"+ );++ let no_thread = h+ .err(1903, "openhuman.flows_build_cancel", json!({}))+ .await;+ assert!(+ no_thread.contains("thread_id"),+ "the required `thread_id` param is named: {no_thread}"+ );++ h.join.abort();+}